% Author     : Christophe Poulain
% licence    : Released under the LaTeX Project Public License v1.3c
% or later, see http://www.latex-project.org/lppl.txtf
\NeedsTeXFormat{LaTeX2e}%
\def\filedate{2023/01/01}%
\let\PfCfiledate\filedate%
\def\fileversion{0.99-z-d}%
\let\PfCfileversion\fileversion%
\ProvidesPackage{ProfCollege}[\filedate\space v\fileversion\space Aide pour utiliser LaTeX au college]

\RequirePackage{verbatim}

\RequirePackage{mathtools}
\RequirePackage{amssymb}

% mathématiques
\RequirePackage{siunitx}
\sisetup{%
  locale=FR,%
  mode = match, propagate-math-font = true,%
  reset-math-version = false, reset-text-family = false,%
  reset-text-series = false, reset-text-shape = false,%
  text-family-to-math = true, text-series-to-math = true,%
  output-decimal-marker={,},%
  group-minimum-digits=4%
}%
\DeclareSIUnit{\kmh}{\km\per\hour}
\newcommand\speed[1]{\SI{#1}{\kmh}}
\newcommand\Speed[1]{\SI[per-mode=symbol]{#1}{\kmh}}

\DeclareSIUnit{\are}{a}
\DeclareSIUnit{\annee}{an}
\DeclareSIUnit{\mois}{mois}
\DeclareSIUnit{\jour}{j}
\DeclareSIUnit{\quintal}{q}
\DeclareSIUnit{\octet}{o}
\DeclareSIUnit{\fahrenheit}{\text{\textdegree}F}
\DeclareSIUnit{\EuRo}{€}

\RequirePackage[table,svgnames]{xcolor}%Gestion des couleurs
\RequirePackage{xstring}%Gestion de chaines de caractères
\RequirePackage{simplekv}%Gestion de paramètres sous forme de clés
\RequirePackage{ifthen}
\RequirePackage{modulus}%Pour certains calculs arithmétiques.
\RequirePackage{xinttools}%Pour la création dynamique d'un tableau

\newif\if@shellescape \@shellescapetrue
\DeclareOption{nonshellescape}{\@shellescapefalse}
\ProcessOptions\relax

\RequirePackage{iftex}

\ifluatex
\RequirePackage{luacas}
\RequirePackage{luamplib}
\everymplib{input PfCSvgnames; input PfCConstantes; input PfCGeometrie; input PfCAfficheur; beginfig(1);}
\everyendmplib{endfig;}
\else
\if@shellescape
\RequirePackage[shellescape,latex]{gmp}%inclusion de figures metapost "à la volée"%
\gmpoptions{everymp={prologues:=3; input PfCLaTeX; input PfCSvgnames; input PfCConstantes; input PfCGeometrie; input PfCAfficheur;}}
\usempxclass{article}
\usempxpackage[locale=FR,mode = match, propagate-math-font = true,reset-math-version = false, reset-text-family = false,reset-text-series = false, reset-text-shape = false,text-family-to-math = true, text-series-to-math = true, output-decimal-marker={,},group-minimum-digits=4]{siunitx}
\usempxpackage[utf8]{inputenc}
\usempxpackage[T1]{fontenc}
\usempxpackage{fourier}
\usempxpackage[french]{babel}
\usempxpackage{pifont}
\else
\RequirePackage[latex]{gmp}%inclusion de figures metapost "à la volée"%
\gmpoptions{everymp={prologues:=3; input PfCLaTeX; input PfCSvgnames; input PfCConstantes; input PfCGeometrie; input PfCAfficheur;}}
\usempxclass{article}
\usempxpackage[locale=FR,mode = match, propagate-math-font = true,reset-math-version = false, reset-text-family = false,reset-text-series = false, reset-text-shape = false,text-family-to-math = true, text-series-to-math = true, output-decimal-marker={,},group-minimum-digits=4]{siunitx}
\usempxpackage[utf8]{inputenc}
\usempxpackage[T1]{fontenc}
\usempxpackage{fourier}
\usempxpackage[french]{babel}
\usempxpackage{pifont}
\fi
\fi

\RequirePackage{xintexpr}
\RequirePackage{listofitems}
\RequirePackage{datatool}
\RequirePackage{multido}

\RequirePackage{xlop}
\RequirePackage{xfp}

\RequirePackage[most]{tcolorbox}

\RequirePackage{tikz}
% https://tex.stackexchange.com/questions/349259/curved-arrow-describing-a-step-in-a-equation-derivation
%https://tex.stackexchange.com/questions/58656/best-way-to-draw-a-chevron-diagram-using-tikz
\usetikzlibrary{calc,shapes,arrows,tikzmark,chains,positioning,shapes.symbols,babel,fit}

\RequirePackage{suffix}%pour la commande étoilée

\RequirePackage{multicol}

\RequirePackage{hhline}

\RequirePackage{stackengine}
\RequirePackage[thicklines]{cancel}

\RequirePackage{fontawesome5}%Pour l'environnement Twitter
\RequirePackage{pifont}%Pour la commande \Autonomie
\RequirePackage{nicematrix}%
\NiceMatrixOptions{allow-duplicate-names}

\let\myoldmulticolumn\multicolumn
\AtBeginEnvironment{tabular}{\let\multicolumn\myoldmulticolumn}

\RequirePackage{fmtcount}
\FCloadlang{french}

% https://stackoverflow.com/questions/3391103/how-to-make-the-grayed-round-box-using-tiks
\RequirePackage{environ}

%%%%% Quelques besoins particuliers

\def\bla{}%JCC :) Pour les tests sur arguments vides

%% Colorer en mode mathématique. \color ne gère pas les espaces propres au mode mathématique. Donc besoin de changer
% https://tex.stackexchange.com/questions/21598/how-to-color-math-symbols
\makeatletter
\def\mathcolor#1#{\@mathcolor{#1}}
\def\@mathcolor#1#2#3{%
  \protect\leavevmode
  \begingroup
    \color#1{#2}#3%
  \endgroup
}
\makeatother

% Pb ProfCollege<->Chinois soulev\'e par Denis
% Solution by egreg :)
\newcommand\getstrut[1]{%
  \the\expandafter#1\expanded{\strutbox}%
}

% Colorer uniquement la barre de soulignement
% https://tex.stackexchange.com/questions/9466/color-underline-a-formula/153884
\def\mathunderline#1#2{\color{#1}\underline{{\color{black}#2}}\color{black}}

% Ecrire des lignes d'équations
\catcode`\@=11
\def\Eqalign#1{\null\,\vcenter{\openup\jot\m@th\ialign{
      \strut\hfil$\displaystyle{##}$&$\displaystyle{{}##}$\hfil
      &&\quad\strut\hfil$\displaystyle{##}$&$\displaystyle{{}##}$
      \hfil\crcr #1\crcr}}\,}
\catcode`\@=12

%%%
% Commandes "utiles"
%%%
%encadrer avec des "sommets arrondis"
\newsavebox{\logobox}

\newcommand\Logo[2]{%
\setbox1=\hbox{\includegraphics[scale=#2]{#1}}
\begin{tikzpicture}%
\clip[rounded corners=5mm] (0,0) rectangle (\wd1,\ht1);
\node[xshift=0.5\wd1, yshift=0.5\ht1, inner xsep=0pt, inner ysep=0pt] (box) {%
\includegraphics[scale=#2]{#1}%
};%
\end{tikzpicture}%
}

\newcommand\LogoTW[2]{%
\setbox1=\hbox{\includegraphics[scale=#2]{#1}}%
\begin{tikzpicture}%
  \clip (0,0) circle (4mm);
  \draw (0,0) circle (4mm);
  \node[xshift=0mm, yshift=0mm, inner xsep=0pt, inner ysep=0pt] (0,0) {%
    \includegraphics[scale=#2]{#1}%
  };%
\end{tikzpicture}%
}%

\makeatletter%
\NewDocumentCommand\Dotfill{}{%
\leavevmode%
\cleaders\hb@xt@.44em{\hss\xleaders\hrule width0.33em\hss}\hfill%
\kern\z@}%

\NewDocumentCommand\PfCdotover{}{\leavevmode\cleaders\hb@xt@ .22em{\hss $\cdot$\hss}\hfill\kern\z@}

\makeatother%

\NewDocumentCommand\pointilles{o}{%
  \IfNoValueTF{#1}{\Dotfill}{\makebox[#1]{\Dotfill}}%
}%

\NewDocumentCommand\Lignespointilles{m}{%
  \xintifboolexpr{#1>1}{%
    \xintFor* ##1 in {\xintSeq {1}{#1}}\do{%
      \pointilles\par%
    }%
  }{}%
}%

%https://tex.stackexchange.com/questions/128991/frac-or-inference-rule-with-dotted-line
\newcommand\PfCfrac[2]{%
\ooalign{$\genfrac{}{}{0pt}{0}{#1}{#2}$\cr\PfCdotover\cr}
}%
\makeatother

\newcommand\MultiCol[2]{%
  \setsepchar[*]{/}%
  \readlist*\ListeNombreCol{#1}%
  \setsepchar[*]{§}%
  \readlist*\ListeContenuCol{#2}%
  \xintFor* ##1 in {\xintSeq {1}{\ListeNombreCollen}}\do{%
    \begin{minipage}{\ListeNombreCol[##1]\linewidth}
      \ListeContenuCol[##1]
    \end{minipage}%
    \xintifboolexpr{##1<\ListeNombreCollen}{\hfill}{}%
  }%
}%

\newcount\PfCrappeljour

\newcommand\Demain{%
  \PfCrappeljour=\day\relax%
  \advance\day by 1\relax%
  \ifnum\month=1\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=2\relax%
  \ifnum\day>28\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=3\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=4\relax%
  \ifnum\day>30\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=5\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=6\relax%
  \ifnum\day>30\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=7\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=8\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=9\relax%
  \ifnum\day>30\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=10\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=11\relax%
  \ifnum\day>30\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \ifnum\month=12\relax%
  \ifnum\day>31\relax%
  \day=\numexpr1\relax%
  \advance\month by 1\relax%
  \today\relax%
  \advance\month by -1\relax%
  \else%
  \today\relax%
  \fi%
  \fi%
  \day=\the\PfCrappeljour\relax%
}

%%%
% Calisson
%
\setKVdefault[Calisson]{Taille=3,Solution=false,Rayon=5cm,Couleur=red}%

\def\UpdatetoksCalissong#1\nil{\addtotok\tokcalissonlistetracesg{,"#1"}}%
\def\UpdatetoksCalissongDepart#1\nil{\addtotok\tokcalissonlistetracesg{"#1"}}%
\def\UpdatetoksCalissond#1\nil{\addtotok\tokcalissonlistetracesd{,"#1"}}%
\def\UpdatetoksCalissondDepart#1\nil{\addtotok\tokcalissonlistetracesd{"#1"}}%

\newtoks\tokcalissonlistetracesg
\newtoks\tokcalissonlistetracesd

\NewDocumentCommand\Calisson{o m}{%
  \useKVdefault[Calisson]%
  \setKV[Calisson]{#1}%
  % Essai de cassage du code
  \tokcalissonlistetracesg{}%
  \tokcalissonlistetracesd{}%
  %Partie Gauche -> ok
  \StrLeft{0#2}{2}[\Depart]%
  \StrGobbleLeft{0#2}{2}[\Reste]%
  \expandafter\UpdatetoksCalissongDepart\Depart0\nil%
  \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}-1}}}\do{%
    \StrLeft{0\Reste}{3}[\Depart]%
    \expandafter\UpdatetoksCalissong\Depart\nil%
    \StrGobbleLeft{0\Reste}{3}[\Reste]%
  }%
  \StrLeft{00\Reste}{3}[\Depart]%
  \StrGobbleLeft{00\Reste}{3}[\Reste]%
  \expandafter\UpdatetoksCalissong\Depart\nil%
  % fin premiere ligne
  \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}-1}}}\do{%
    \StrLeft{\Reste}{2}[\Depart]%
    \expandafter\UpdatetoksCalissong\Depart0\nil%
    \StrGobbleLeft{\Reste}{2}[\Reste]%
    \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}-1}}}\do{%
      \StrLeft{\Reste}{3}[\Depart]%
      \expandafter\UpdatetoksCalissong\Depart\nil%
      \StrGobbleLeft{\Reste}{3}[\Reste]%
    }%
    \StrLeft{00\Reste}{3}[\Depart]%
    \expandafter\UpdatetoksCalissong\Depart\nil%
    \StrGobbleLeft{00\Reste}{3}[\Reste]%
  }%
  % fin des lignes intermédiaires
  \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}}}}\do{%
    \StrLeft{\Reste}{2}[\Depart]%
    \expandafter\UpdatetoksCalissong\Depart0\nil%
    \StrGobbleLeft{\Reste}{2}[\Reste]
    \xintifboolexpr{##1>\fpeval{\useKV[Calisson]{Taille}-1}}{}{%
      \xintFor* ##2 in {\xintSeq{\fpeval{\useKV[Calisson]{Taille}-##1}}{1}}\do{%
        \StrLeft{\Reste}{3}[\Depart]%
        \expandafter\UpdatetoksCalissong\Depart\nil%
        \StrGobbleLeft{\Reste}{3}[\Reste]%
      }%
    }%
  }%
  %Liste gauche : \the\tokcalissonlistetracesg%
  % Partie droite
  \StrLeft{0\Reste}{3}[\Depart]%
  \expandafter\UpdatetoksCalissondDepart\Depart\nil%
  \StrGobbleLeft{0\Reste}{3}[\Reste]%
  \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}-2}}}\do{%
    \StrLeft{0\Reste}{3}[\Depart]%
    \expandafter\UpdatetoksCalissond\Depart\nil%
    \StrGobbleLeft{0\Reste}{3}[\Reste]%
  }%
  \StrLeft{00\Reste}{3}[\Depart]%
  \StrGobbleLeft{00\Reste}{3}[\Reste]%
  \expandafter\UpdatetoksCalissond\Depart\nil%
% fin premiere ligne
  \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}-1}}}\do{%
    \StrLeft{\Reste}{1}[\Depart]%
    \expandafter\UpdatetoksCalissond\Depart00\nil%
    \StrGobbleLeft{\Reste}{1}[\Reste]%
    \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}-1}}}\do{%
      \StrLeft{\Reste}{3}[\Depart]%
      \expandafter\UpdatetoksCalissond\Depart\nil%
      \StrGobbleLeft{\Reste}{3}[\Reste]%
    }%
    \StrLeft{00\Reste}{3}[\Depart]%
    \expandafter\UpdatetoksCalissond\Depart\nil%
    \StrGobbleLeft{00\Reste}{3}[\Reste]%
  }%
  %% fin des lignes intermédiaires
  \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Calisson]{Taille}}}}\do{%
    \StrLeft{\Reste}{1}[\Depart]%
    \expandafter\UpdatetoksCalissond\Depart00\nil%
    \StrGobbleLeft{\Reste}{1}[\Reste]%
    \xintifboolexpr{##1>\fpeval{\useKV[Calisson]{Taille}-1}}{}{%
      \xintFor* ##2 in {\xintSeq{\fpeval{\useKV[Calisson]{Taille}-##1}}{1}}\do{%
        \StrLeft{\Reste}{3}[\Depart]%
        \expandafter\UpdatetoksCalissond\Depart\nil%
        \StrGobbleLeft{\Reste}{3}[\Reste]%
      }%
    }%
  }%
%  \par Liste droite :\the\tokcalissonlistetracesd
  \BuildCalisson{\the\tokcalissonlistetracesg}{\the\tokcalissonlistetracesd}%
}%

\NewDocumentCommand\BuildCalisson{m m}{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    boolean Solution;
    Solution:=\useKV[Calisson]{Solution};

    color CouleurSolution;
    CouleurSolution:=\useKV[Calisson]{Couleur};
    
    Rayon=\useKV[Calisson]{Rayon};
    Taille=\useKV[Calisson]{Taille};
    
    pair A,B,C,D,E,F,O;
    O=(0,0);
    path cc;
    cc=cercles(O,Rayon);
    D=pointarc(cc,30);
    E=pointarc(cc,90);
    F=pointarc(cc,150);
    A=pointarc(cc,210);
    B=pointarc(cc,270);
    C=pointarc(cc,330);
    trace polygone(A,B,C,D,E,F) withpen pencircle scaled 2;
    path Gauche,Droit,Haut,Bas,TopGauche,BasDroit;
    Gauche=F--A--B;
    Droit=E--D--C;
    Haut=F--E--D;
    Bas=A--B--C;
    TopGauche=E--F--A;
    BasDroit=D--C--B;
    for k=1 upto 2*Taille-1:
    trace (point(k*length Gauche/(2*Taille)) of Gauche)--(point(k*length Droit/(2*Taille)) of Droit) dashed evenly;
    trace (point(k*length Haut/(2*Taille)) of Haut)--(point(k*length Bas/(2*Taille)) of Bas) dashed evenly;
    trace (point(k*length TopGauche/(2*Taille)) of TopGauche)--(point(k*length BasDroit/(2*Taille)) of BasDroit) dashed evenly;
    endfor;
    
    pair Hor,Ver,Horn;
    Hor=(1/Taille)[E,F];
    Ver=rotation(Hor,E,60);
    Horn=rotation(Hor,E,120);

    % On positionne les points
    pair M[];
    n=0;
    %Partie Gauche -> ok
    for k=0 upto Taille-1:
    for l=0 upto Taille:
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Hor-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    for k=Taille upto 2*Taille-1:
    for l=0 upto (2*Taille-1-k):
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Hor-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    % Partie Droite -> ok
    for k=1 upto Taille:
    n:=n+1;
    M[n]=E+k*(Horn-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    for k=1 upto Taille-1:
    for l=0 upto Taille:
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Horn-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    for k=Taille upto 2*Taille-1:
    for l=0 upto (2*Taille-1-k):
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Horn-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    %
    
    string Retiens;
    Retiens="";

    pair Depla;
    Depla:=Hor;
    
    vardef LesTracesg(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    for d=1 upto 3:
    Retiens:=substring(d-1,d) of p_;
    if d=1:Depla:=Hor
    elseif d=2:Depla:=Ver
    else : Depla:=Horn
    fi;
    if (Retiens="0") or (Retiens="f"):
    elseif Retiens="t":
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2;
    elseif Retiens="s":
    if Solution:
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2 withcolor CouleurSolution;
    fi;
    fi;
    endfor;
    endfor;
    enddef;

    vardef LesTracesd(text t)=
    for p_=t:
    n:=n+1;
    for d=1 upto 3:
    Retiens:=substring(d-1,d) of p_;
    if d=1:Depla:=Horn
    elseif d=2:Depla:=Ver
    else : Depla:=Hor
    fi;
    if (Retiens="0") or (Retiens="f"):
    elseif Retiens="t":
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2;
    elseif Retiens="s":
    if Solution:
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2 withcolor CouleurSolution;
    fi;
    fi;
    endfor;
    endfor;
    enddef;
    
    LesTracesg(#1);
    LesTracesd(#2);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={boolean Solution; Solution:=\useKV[Calisson]{Solution}; Rayon=\useKV[Calisson]{Rayon};Taille=\useKV[Calisson]{Taille};color CouleurSolution; CouleurSolution:=\useKV[Calisson]{Couleur};}]
    pair A,B,C,D,E,F,O;
    O=(0,0);
    path cc;
    cc=cercles(O,Rayon);
    D=pointarc(cc,30);
    E=pointarc(cc,90);
    F=pointarc(cc,150);
    A=pointarc(cc,210);
    B=pointarc(cc,270);
    C=pointarc(cc,330);
    trace polygone(A,B,C,D,E,F) withpen pencircle scaled 2;
    path Gauche,Droit,Haut,Bas,TopGauche,BasDroit;
    Gauche=F--A--B;
    Droit=E--D--C;
    Haut=F--E--D;
    Bas=A--B--C;
    TopGauche=E--F--A;
    BasDroit=D--C--B;
    for k=1 upto 2*Taille-1:
    trace (point(k*length Gauche/(2*Taille)) of Gauche)--(point(k*length Droit/(2*Taille)) of Droit) dashed evenly;
    trace (point(k*length Haut/(2*Taille)) of Haut)--(point(k*length Bas/(2*Taille)) of Bas) dashed evenly;
    trace (point(k*length TopGauche/(2*Taille)) of TopGauche)--(point(k*length BasDroit/(2*Taille)) of BasDroit) dashed evenly;
    endfor;
    
    pair Hor,Ver,Horn;
    Hor=(1/Taille)[E,F];
    Ver=rotation(Hor,E,60);
    Horn=rotation(Hor,E,120);

    % On positionne les points
    pair M[];
    n=0;
    %Partie Gauche -> ok
    for k=0 upto Taille-1:
    for l=0 upto Taille:
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Hor-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    for k=Taille upto 2*Taille-1:
    for l=0 upto (2*Taille-1-k):
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Hor-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    % Partie Droite -> ok
    for k=1 upto Taille:
    n:=n+1;
    M[n]=E+k*(Horn-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    for k=1 upto Taille-1:
    for l=0 upto Taille:
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Horn-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    for k=Taille upto 2*Taille-1:
    for l=0 upto (2*Taille-1-k):
    n:=n+1;
    M[n]=E+k*(Ver-E)+l*(Horn-E);
    %dotlabel.top(decimal(n),M[n]);
    endfor;
    endfor;
    %
    
    string Retiens;
    Retiens="";

    pair Depla;
    Depla:=Hor;
    
    vardef LesTracesg(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    for d=1 upto 3:
    Retiens:=substring(d-1,d) of p_;
    if d=1:Depla:=Hor
    elseif d=2:Depla:=Ver
    else : Depla:=Horn
    fi;
    if (Retiens="0") or (Retiens="f"):
    elseif Retiens="t":
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2;
    elseif Retiens="s":
    if Solution:
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2 withcolor CouleurSolution;
    fi;
    fi;
    endfor;
    endfor;
    enddef;

    vardef LesTracesd(text t)=
    for p_=t:
    n:=n+1;
    for d=1 upto 3:
    Retiens:=substring(d-1,d) of p_;
    if d=1:Depla:=Horn
    elseif d=2:Depla:=Ver
    else : Depla:=Hor
    fi;
    if (Retiens="0") or (Retiens="f"):
    elseif Retiens="t":
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2;
    elseif Retiens="s":
    if Solution:
    trace (chemin(Depla,E) shifted (M[n]-E)) withpen pencircle scaled 2 withcolor CouleurSolution;
    fi;
    fi;
    endfor;
    endfor;
    enddef;
    
    LesTracesg(#1);
    LesTracesd(#2);
  \end{mpost}
  \fi
}

%%%
% Tectonic
%%%
\setKVdefault[ClesTectonic]{CouleurCase=LightGray,TLargeur=5,THauteur=5,Solution=false,Largeur=25pt,CouleurSolution=black,Tailles=false,Aide=false}%
\defKV[ClesTectonic]{Taille=\setKV[ClesTectonic]{Tailles}}%
\defKV[ClesTectonic]{ListeNombres=\setKV[ClesTectonic]{Aide}}%

\newlength\PfCTectonic

\NewDocumentCommand\Tectonic{o m}{%
  \useKVdefault[ClesTectonic]%
  \setKV[ClesTectonic]{#1}%
  \ifboolKV[ClesTectonic]{Tailles}{%
    \setKV[ClesTectonic]{THauteur=\useKV[ClesTectonic]{Taille}}%
    \setKV[ClesTectonic]{TLargeur=\useKV[ClesTectonic]{Taille}}%
  }{}%
  \setlength{\PfCTectonic}{\useKV[ClesTectonic]{Largeur}+\tabcolsep}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeCasesTectonic{#2}%
  \savecomparemode%
  \comparestrict%
  \begin{NiceTabular}{*{\useKV[ClesTectonic]{TLargeur}}{m{\useKV[ClesTectonic]{Largeur}}}}%
    \CodeBefore%
    \xintFor* ##1 in {\xintSeq{2}{\fpeval{\useKV[ClesTectonic]{THauteur}}}}\do{%
      \tikz\draw[gray] (##1-|1) -- (##1-|last);%
    }%
    \xintFor* ##1 in {\xintSeq{2}{\fpeval{\useKV[ClesTectonic]{TLargeur}}}}\do{%
      \tikz\draw[gray] (1-|##1) -- (last-|##1);%
    }%
    \Body%
    \xintFor* ##1 in {\xintSeq{0}{\fpeval{\useKV[ClesTectonic]{THauteur}-1}}}\do{%
      \xintFor* ##2 in {\xintSeq{1}{\useKV[ClesTectonic]{TLargeur}}}\do{%
        \rule{0pt}{\PfCTectonic}%
        \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},1]}{b}[\PfCTestb]%\PfCTestb
        \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},1]}{l}[\PfCTestl]%\PfCTestr
        \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},1]}{lb}[\PfCTestlb]%\PfCTestbr
        \xintifboolexpr{\PfCTestb==0}{%
          \Block[borders={bottom},line-width=2pt]{1-1}{%
            \ifboolKV[ClesTectonic]{Solution}{%
              \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},2]}{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}[\PfCTestMeme]
                \xintifboolexpr{\PfCTestMeme>0}{\color{\useKV[ClesTectonic]{CouleurSolution}}}{}%
              \Large\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]%
            }{%
              \ifboolKV[ClesTectonic]{Aide}{%
                \xintifboolexpr{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]==\useKV[ClesTectonic]{Nombre}}{%
                  \cellcolor{LightGray}\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]%
                }{}%
              }{}%
            }%
          }%
        }{%
          \xintifboolexpr{\PfCTestl==0}{%
            \Block[borders={left},line-width=2pt]{1-1}{\ifboolKV[ClesTectonic]{Solution}{%
                \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},2]}{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}[\PfCTestMeme]
                \xintifboolexpr{\PfCTestMeme>0}{\color{\useKV[ClesTectonic]{CouleurSolution}}}{}%
                \Large\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}{%
                \ifboolKV[ClesTectonic]{Aide}{%
                  \xintifboolexpr{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]==\useKV[ClesTectonic]{Nombre}}{%
                    \cellcolor{LightGray}\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]%
                  }{}%
                }{}%
              }%
            }%
          }{%
            \xintifboolexpr{\PfCTestlb==0}{%
              \Block[borders={bottom,left},line-width=2pt]{1-1}{\ifboolKV[ClesTectonic]{Solution}{%
                  \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},2]}{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}[\PfCTestMeme]
                  \xintifboolexpr{\PfCTestMeme>0}{\color{\useKV[ClesTectonic]{CouleurSolution}}}{}
                  \Large\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}{%
                  \ifboolKV[ClesTectonic]{Aide}{%
                    \xintifboolexpr{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]==\useKV[ClesTectonic]{Nombre}}{%
                      \cellcolor{LightGray}\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]%
                    }{}%
                  }{}%
                }%
              }%
            }{%
              \Block{1-1}{\ifboolKV[ClesTectonic]{Solution}{%
                  \StrCompare{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},2]}{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}[\PfCTestMeme]
                  \xintifboolexpr{\PfCTestMeme>0}{\color{\useKV[ClesTectonic]{CouleurSolution}}}{}
                  \Large\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]}{%
                  \ifboolKV[ClesTectonic]{Aide}{%
                    \xintifboolexpr{\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]==\useKV[ClesTectonic]{Nombre}}{%
                      \cellcolor{LightGray}\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*##1+##2},3]%
                    }{}%
                  }{}%
                }%
              }%
            }%
          }%
        }%
        \xintifForLast{\\}{&}%
      }%
    }%
    \CodeAfter%
    \tikz\draw[line width=2pt] (1-|1) rectangle (last-|last);%
    \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[ClesTectonic]{THauteur}}}}\do{%
      \xintFor* ##2 in {\xintSeq{1}{\useKV[ClesTectonic]{TLargeur}}}\do{%
        \ifboolKV[ClesTectonic]{Solution}{%
          %\tikz\node[fill=white] at (\fpeval{##1+0.5} -|\fpeval{##2+0.5}) {\Large$\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*(##1-1)+##2},2]$};%
        }{%
          \tikz\node at (\fpeval{##1+0.5} -|\fpeval{##2+0.5}) {\Large$\ListeCasesTectonic[\fpeval{\useKV[ClesTectonic]{TLargeur}*(##1-1)+##2},2]$};%
        }%
      }%
    }%
  \end{NiceTabular}%
  \restorecomparemode%
}%

%%%
% Enigme Aire
%%%
\setKVdefault[EnigmeAire]{Modele=A,Couleur=LightSteelBlue,Echelle=7mm,Etape=1}

\def\MPEnigmeAireA{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[EnigmeAire]{Echelle};
    pair A[],B[];
    numeric la[];
    la1=ceiling(3+uniformdeviate(7));
    la2=ceiling(3+uniformdeviate(7));
    la3=ceiling(3+uniformdeviate(7));
    la4=ceiling(4+uniformdeviate(6));
    A1=u*(1,1);
    A2-A1=u*(10,0);
    A3-A2=u*(0,5);
    A4-A3=A1-A2;
    B1=(la1/(la1+la2+la3))[A1,A2];
    B2=((la1+la2)/(la1+la2+la3))[A1,A2];
    B3-B2=A4-A1;
    B4-B1=B3-B2;
    fill polygone(B1,B2,B3,B4) withcolor \useKV[EnigmeAire]{Couleur};
    trace polygone(B1,B2,B3,B4);
    trace polygone(A1,A2,A3,A4);
    label(TEX("\Aire[m]{"&decimal(la1*la4)&"}"),iso(A1,B4));
    label(TEX("?\,\si{\square\meter}"),iso(B1,B3));
    label(TEX("\Aire[m]{"&decimal(la3*la4)&"}"),iso(B2,A3));
    trace cotation(A4,B3,3mm,3mm,TEX("\Lg[m]{"&decimal(la1+la2)&"}"));
    trace cotation(B1,A2,-3mm,-3mm,TEX("\Lg[m]{"&decimal(la3+la2)&"}"));
  \end{mplibcode}
  \fi
}

\def\MPEnigmeAireB{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[EnigmeAire]{Echelle};
    pair A[],B[];
    numeric La[],la[],Ca[];
    la1=ceiling(3+uniformdeviate(7));
    la2=ceiling(3+uniformdeviate(7));
    La1=ceiling(8+uniformdeviate(7));
    La2=ceiling(uniformdeviate(5));
    Ca1=1+ceiling(uniformdeviate(La1-La2-2));
    Ca2=ceiling(uniformdeviate(la2-2));
    A1=u*(1,1);
    A2-A1=u*(10,0);
    A3-A2=u*(0,2);
    A4-A3=u*(-7,0);
    A5-A4=u*(0,4);
    A6-A5=(xpart(A1-A4),0);
    A7-A6=A4-A5;
    B1=(Ca1/(La1-La2))[A4,A3];
    B3=((Ca2+1)/la2)[A4,A5];
    B2-B1=B3-A4;
    fill polygone(A4,B1,B2,B3) withcolor \useKV[EnigmeAire]{Couleur};
    trace chemin(B1,B2,B3);
    trace polygone(A1,A2,A3,A4,A5,A6);
    trace chemin(A7,A4);
    label(TEX("\Aire[m]{"&decimal(la1*La1)&"}"),iso(A1,A3));
    label(TEX("?\,\si{\square\meter}"),iso(B1,B3));
    label(TEX("\Aire[m]{"&decimal(la2*La2)&"}"),iso(A7,A5));
    trace appelation(A6,A5,3mm,TEX("\Lg[m]{"&decimal(La2)&"}"));
    trace appelation(B1,A3,3mm,TEX("\Lg[m]{"&decimal(La1-La2-Ca1)&"}"));
    label.rt(TEX("\Lg[m]{"&decimal(la2-Ca2)&"}"),iso(A5,B3));
    label.rt(TEX("\Lg[m]{"&decimal(la1)&"}"),iso(A2,A3));
  \end{mplibcode}
  \fi
}

\def\MPEnigmeAireC{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[EnigmeAire]{Echelle};
    pair A[];
    numeric la[],La[];
    La1=ceiling(3+uniformdeviate(7));
    La2=ceiling(3+uniformdeviate(7));
    La3=ceiling(3+uniformdeviate(7));
    la1=ceiling(3+uniformdeviate(7));
    la2=ceiling(3+uniformdeviate(7));
    la3=ceiling(3+uniformdeviate(7));
    A1=u*(1,1);
    A4-A1=if La1+La2+La3>la1+la2+la3:
    u*(10,0)
    else:
    u*(8,0);
    fi;
    A2=(La1/(La1+La2+La3))[A1,A4];
    A3=((La1+La2)/(La1+La2+La3))[A1,A4];
    A5-A4=if La1+La2+La3>la1+la2+la3:
    u*(0,7)
    else:
    u*(0,10);
    fi;
    A6-A5=A3-A4;
    A7-A3=((la1+la2)/(la1+la2+la3))[A4,A5]-A4;
    A8-A7=A2-A3;
    A9-A2=(la1/(la1+la2+la3))[A4,A5]-A4;
    A10-A9=A1-A2;
    trace polygone(A1,A4,A5,A6,A7,A8,A9,A10);
    trace segment(A2,A9);
    trace segment(A3,A7);
    label(TEX("\Aire[cm]{"&decimal(la1*La1)&"}"),iso(A1,A9));
    label(TEX("\Aire[cm]{"&decimal((la1+la2)*La2)&"}"),iso(A2,A7));
    label(TEX("\Aire[cm]{"&decimal((la1+la2+la3)*La3)&"}"),iso(A3,A5));
    trace cotation(A1,A4,-3mm,-3mm,TEX("\Lg[cm]{"&decimal(La1+La2+La3)&"}"));
    label.lft(TEX("\Lg{"&decimal(la1)&"}"),iso(A1,A10));
    label.lft(TEX("\Lg{"&decimal(la2)&"}"),iso(A9,A8));
    label.lft(TEX("?\,\si{\centi\meter}"),iso(A7,A6));
  \end{mplibcode}
  \fi
}

\def\MPEnigmeAireD{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[EnigmeAire]{Echelle};
    Etape:=\useKV[EnigmeAire]{Etape};
    pair A[];
    numeric la[],La[];
    la[1]=ceiling(3+uniformdeviate(7));
    la[2]=ceiling(3+uniformdeviate(7));
    k=1;
    La[k]=ceiling(3+uniformdeviate(7));
    A[1]=u*(9,-9);
    A[6*(k-1)+2]-A[6*(k-1)+1]=u*(0,3);
    A[6*(k-1)+3]-A[6*(k-1)+2]=u*(-6,0);
    A[6*(k-1)+4]-A[6*(k-1)+3]=A[6*(k-1)+1]-A[6*(k-1)+2];
    A[6*(k-1)+5]=(la[k]/(la[k]+la[k+1]))[A[6*(k-1)+1],A[6*(k-1)+4]];
    A[6*(k-1)+6]-A[6*(k-1)+5]=A[6*(k-1)+2]-A[6*(k-1)+1];
    trace polygone(A[6*(k-1)+1],A[6*(k-1)+2],A[6*(k-1)+3],A[6*(k-1)+4]);
    trace segment(A[6*(k-1)+5],A[6*(k-1)+6]);
    trace cotation(A[6*(k-1)+5],A[6*(k-1)+1],-3mm,-3mm,TEX("?\,\si{\centi\meter}"));
    label(TEX("\Aire{"&decimal(la[k]*La[k])&"}"),iso(A[6*(k-1)+5],A[6*(k-1)+2]));
    label(TEX("\Aire{"&decimal(la[k+1]*La[k])&"}"),iso(A[6*(k-1)+4],A[6*(k-1)+6]));
    if Etape<2:
    trace cotation(A[6*(k-1)+3],A[6*(k-1)+6],3mm,3mm,TEX("\Lg{"&decimal(la[k+1])&"}"));
    fi;
    for k=2 upto Etape:
    La[k]=ceiling(3+uniformdeviate(7));
    la[k+1]=ceiling(3+uniformdeviate(7));
    A[6*(k-1)+1]=A[6*(k-1)];
    A[6*(k-1)+2]-A[6*(k-1)+1]=u*(0,3);
    A[6*(k-1)+3]-A[6*(k-1)+2]=u*(-6,0);
    A[6*(k-1)+4]-A[6*(k-1)+3]=A[6*(k-1)+1]-A[6*(k-1)+2];
    A[6*(k-1)+5]=A[6*(k-1)-3];%(la[k]/(la[k]+la[k+1]))[A[6*(k-1)+1],A[6*(k-1)+4]];
    A[6*(k-1)+6]-A[6*(k-1)+5]=A[6*(k-1)+2]-A[6*(k-1)+1];
    trace polygone(A[6*(k-1)+1],A[6*(k-1)+2],A[6*(k-1)+3],A[6*(k-1)+4]);
    trace segment(A[6*(k-1)+5],A[6*(k-1)+6]);
    if k=Etape:
    trace cotation(A[6*(k-1)+3],A[6*(k-1)+6],3mm,3mm,TEX("\Lg{"&decimal(la[k+1])&"}"));
    fi;
    label(TEX("\Aire[cm]{"&decimal(la[k]*La[k])&"}"),iso(A[6*(k-1)+6],A[6*(k-1)]));
    label(TEX("\Aire[cm]{"&decimal(la[k+1]*La[k])&"}"),iso(A[6*(k-1)+4],A[6*(k-1)+6]));
    endfor;
  \end{mplibcode}
  \fi
}

\def\MPEnigmeAireE{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[EnigmeAire]{Echelle};
    pair A[];
    numeric la[],La[];
    La1=ceiling(3+uniformdeviate(7));
    La2=ceiling(3+uniformdeviate(7));
    La3=ceiling(3+uniformdeviate(7));
    la1=ceiling(4+uniformdeviate(5));
    la2=ceiling(4+uniformdeviate(5));
    la3=la1+la2+2;
    A1=u*(7,1);
    A11-A1=if la3>(La1+La2+La3):u*(0,10) else:u*(0,7) fi;
    A2=(La1/(La1+La2+La3))[A1,A11];
    A3=((La1+La2)/(La1+La2+La3))[A1,A11];
    A8-A2=if la3>(La1+La2+La3):u*(-7,0) else:u*(-10,0) fi;
    A6-A8=A11-A2;
    A7-A8=A3-A2;
    A4=(la2/la3)[A7,A3];
    A5-A4=A6-A7;
    A9=(la1/la3)[A2,A8];
    A10-A9=A1-A2;
    trace polygone(A1,A3,A4,A5,A6,A8,A9,A10);
    trace segment(A7,A4);
    trace segment(A2,A9);
    label(TEX("\Aire[cm]{"&decimal(la1*La1)&"}"),iso(A1,A9));
    label(TEX("\Aire[cm]{"&decimal(la3*La2)&"}"),iso(A2,A7));
    label(TEX("\Aire[cm]{"&decimal(la2*La3)&"}"),iso(A4,A6));
    trace cotationarc(A5,A4,5mm,4,1,TEX("\Lg[cm]{"&decimal(La3)&"}") rotated 90);
    trace cotationarc(A9,A8,3mm,4,1,TEX("\Lg[cm]{"&decimal(la3-la1)&"}") rotated 180);
    trace cotationarc(A4,A3,3mm,4,1,TEX("\Lg[cm]{"&decimal(la3-la2)&"}"));
    trace cotationarc(A3,A1,5mm,3,1,TEX("?") rotated 90);
  \end{mplibcode}
  \fi
}

\def\MPEnigmeAireF{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[EnigmeAire]{Echelle};
    pair A[];
    numeric la[],La[];
    la1=ceiling(2+uniformdeviate(4));
    la2=ceiling(2+uniformdeviate(4));
    la3=ceiling(2+uniformdeviate(4));
    la4=ceiling(2+uniformdeviate(4));
    La1=ceiling(8+uniformdeviate(4));
    La2=ceiling(8+uniformdeviate(4));
    La3=ceiling(8+uniformdeviate(4));
    La4=ceiling(8+uniformdeviate(4));
    A1=(0,0);
    A2-A1=u*(0,-3.5);
    A3-A2=u*(2.25,0);
    A4-A1=A3-A2;
    A5-A1=u*(6,0);
    A6-A5=u*(0,2.5);
    A7-A6=A1-A5;
    A8-A7=u*(0,2);
    A9-A8=u*(-2,0);
    A10-A9=A1-A8;
    A11-A1=u*(-4.5,0);
    A12-A11=u*(0,-1.5);
    A13-A12=A1-A11;
    fill polygone(A1,A5,A6,A7) withcolor \useKV[EnigmeAire]{Couleur};
    trace polygone(A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13);
    trace segment(A7,A13);
    trace segment(A10,A4);
    label(TEX("?\,\si{\square\centi\meter}"),iso(A1,A6));
    label(TEX("\Aire[cm]{"&decimal(la1*La1)&"}"),iso(A2,A4));
    label(TEX("\Aire[cm]{"&decimal(la3*La3)&"}"),iso(A10,A8));
    label(TEX("\Aire[cm]{"&decimal(la4*La4)&"}"),iso(A12,A1));
    trace cotationarc(A12,A11,5mm,4,1,TEX("\Lg[cm]{"&decimal(la4)&"}") rotated -90);
    trace cotationarc(A5,A4,5mm,4,1,TEX("\Lg[cm]{"&decimal(La2-la1)&"}") rotated 180);
    trace cotationarc(A8,A7,5mm,4,1,TEX("\Lg[cm]{"&decimal(La3-la2)&"}") rotated 90);
    trace cotationarc(A11,A10,3mm,4,1,TEX("\Lg[cm]{"&decimal(La4-la3)&"}"));
    trace cotationarc(A2,A13,5mm,3,1,TEX("\Lg[cm]{"&decimal(La1-la4)&"}") rotated -90);
  \end{mplibcode}
  \fi
}

\NewDocumentCommand\EnigmeAire{o}{%
  \useKVdefault[EnigmeAire]%
  \setKV[EnigmeAire]{#1}%
  \IfStrEqCase{\useKV[EnigmeAire]{Modele}}{%
    {A}{\MPEnigmeAireA}
    {B}{\MPEnigmeAireB}
    {C}{\MPEnigmeAireC}
    {D}{\MPEnigmeAireD}
    {E}{\MPEnigmeAireE}
    {F}{\MPEnigmeAireF}
  }%
}%

%%%
% Barres de calculs
%%%
\setKVdefault[SuiteBarre]{Litteral=false,Perso=false,Decimaux=false}

\NewDocumentCommand\BarresCalculs{o m m}{%
  \useKVdefault[SuiteBarre]%
  \setKV[SuiteBarre]{#1}%
  \xdef\PfCListeCalculsBarre{}%
  \xdef\PfCListeResultatsBarre{}%
  \ignoreemptyitems%
  \ifboolKV[SuiteBarre]{Perso}{%
    \setsepchar[*]{,*§}%
    \readlist*\PfCListeBarresCalculs{#2}%
    \foreachitem\compteur\in\PfCListeBarresCalculs{%
      \StrChar{#3}{\compteurcnt}[\PfCLettreB]%
      \StrSubstitute[0]{\PfCLettreB}{*}{Départ}[\PfCLettreC]%
      \xdef\PfCListeResultatsBarre{\PfCListeResultatsBarre \PfCLettreC,}%
    }%
    \setsepchar{,}%
    \readlist*\PfCListeResultats{\PfCListeResultatsBarre}%
    \begin{NiceTabular}{ccc}[hvlines]
      \xintFor* ##1 in{\xintSeq{1}{\PfCListeResultatslen}}\do{%
        \xintifForFirst{\Block{2-1}{}}{\Block{2-1}{\ifboolKV[SuiteBarre]{Decimaux}{%
              \num{\fpeval{\PfCListeBarresCalculs[\fpeval{##1-1},1]}}%
              }{%
                \begin{CAS}
              c = \PfCListeBarresCalculs[\fpeval{##1-1},1]
            \end{CAS}$\print{c:autosimplify()}$}%
        }}&\Block{2-1}{\PfCListeResultats[##1]}&\Block{2-1}{$\PfCListeBarresCalculs[##1,2]$}\\
        &&\\
      }%
    \end{NiceTabular}
  }{%
    \setsepchar{,}%\ignoreemptyitems%
    \readlist*\PfCListeBarresCalculs{#2}%
    \ifboolKV[SuiteBarre]{Litteral}{%
      \foreachitem\compteur\in\PfCListeBarresCalculs{%
        \StrChar{#3}{\compteurcnt}[\PfCLettreB]%
        \StrSubstitute[0]{\PfCLettreB}{*}{Départ}[\PfCLettreC]%
        \xdef\PfCListeResultatsBarre{\PfCListeResultatsBarre \PfCLettreC,}%
      }%
      \setsepchar[*]{,*/}%
      \readlist*\PfCListeResultats{\PfCListeResultatsBarre}%
      \setsepchar{,}%
      \readlist*\PfCListeCalculs{#2}%
      \begin{NiceTabular}{ccc}[hvlines]
        \xintFor* ##1 in{\xintSeq{1}{\PfCListeResultatslen}}\do{%
          \xintifForFirst{\Block{2-1}{}}{\Block{2-1}{$\print{c:expand():topolynomial()}$}}&\Block{2-1}{\PfCListeResultats[##1,1]}&\Block{2-1}{\begin{CAS}
              vars('x')
              c = \PfCListeCalculs[##1]
            \end{CAS}$\print{c}$}\\
          &&\\
        }%
      \end{NiceTabular}
    }{%
      \foreachitem\compteur\in\PfCListeBarresCalculs{%
        \StrChar{#3}{\compteurcnt}[\PfCLettreB]%
        \StrSubstitute[0]{\PfCLettreB}{*}{Départ}[\PfCLettreC]%
        \xdef\PfCListeResultatsBarre{\PfCListeResultatsBarre \num{\fpeval{\compteur}}/\PfCLettreC,}%
        \StrSubstitute[0]{\compteur}{*}{\times}[\PfCListeResultatEtapeA]%
        \StrSubstitute[0]{\PfCListeResultatEtapeA}{/}{\div}[\PfCListeResultatEtapeB]%
        \StrSubstitute[0]{\PfCListeResultatEtapeB}{(}{\left(}[\PfCListeResultatEtapeC]%
          \StrSubstitute[0]{\PfCListeResultatEtapeC}{)}{\right)}[\PfCListeResultatEtapeD]%
        \xdef\PfCListeCalculsBarre{\PfCListeCalculsBarre $\PfCListeResultatEtapeD$,}%
      }%
      \setsepchar[*]{,*/}%
      \readlist*\PfCListeResultats{\PfCListeResultatsBarre}%
      \setsepchar{,}%
      \readlist*\PfCListeCalculs{\PfCListeCalculsBarre}%
      \begin{NiceTabular}{ccc}[hvlines]
        \xintFor* ##1 in{\xintSeq{1}{\PfCListeResultatslen}}\do{%
          \xintifForFirst{\Block{2-1}{}}{\Block{2-1}{\PfCListeResultats[\fpeval{##1-1},1]}}&\Block{2-1}{\PfCListeResultats[##1,2]}&\Block{2-1}{\PfCListeCalculs[##1]}\\
          &&\\
        }%
      \end{NiceTabular}
    }%
  }%
  \reademptyitems%
}%

%%%
% Solide et sections
%%%
\setKVdefault[ClesSolides]{Nom=cube,Aretes,Sommets,Pointilles,Largeur=1.5,Hauteur=1,Profondeur=0.75,ListeSommets={A,B,C,D,E,F,G,H},Rho=1500,Phi=30,Theta=20,Distance=50,Code=false,Couleur=white,Anglex=0,RayonCone=1,HauteurCone=2,HauteurPyramide=2,SommetsPyramide=5,Reguliere=false,DecalageSommet={(0,0,0)},RayonCylindre=1,HauteurCylindre=2,RayonSphere=1,AutoLabel=true,Sections=false,CoefSection=0.3,Axes=false,PointsSection={M,N,O,P},RemplisSection=false,ObjetSection={0.5,E,H,0.25,F,G,G,B}}%
\defKV[ClesSolides]{Traces=\setKV[ClesSolides]{Code}}%
\defKV[ClesSolides]{Section=\setKV[ClesSolides]{Sections}}%
\defKV[ClesSolides]{CouleurSection=\setKV[ClesSolides]{RemplisSection}}%

\newcommand\MPSolideCylindre[3]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCSolid;
    
    boolean NommeSommets,Code,Sections,Axes,RemplisSection;
    NommeSommets=\useKV[ClesSolides]{Sommets};
    Code=\useKV[ClesSolides]{Code};
    Sections:=\useKV[ClesSolides]{Sections};
    Axes:=\useKV[ClesSolides]{Axes};
    RemplisSection=\useKV[ClesSolides]{RemplisSection};
    if RemplisSection:color CouleurSection;CouleurSection=\useKV[ClesSolides]{CouleurSection};fi;
    %Initialisation
    PfCRho=\useKV[ClesSolides]{Rho};
    PfCPhi=\useKV[ClesSolides]{Phi};
    PfCTheta=\useKV[ClesSolides]{Theta};
    PfCDistance=\useKV[ClesSolides]{Distance};
    CoefSection=\useKV[ClesSolides]{CoefSection};
    anglerotationx=\useKV[ClesSolides]{Anglex};
    rayoncylindre=\useKV[ClesSolides]{RayonCylindre};
    hauteurcylindre=\useKV[ClesSolides]{HauteurCylindre};

    string Section;
    if Sections:Section=\useKV[ClesSolides]{Section};fi;
        
    color PfCOutColor;
    PfCOutColor=\useKV[ClesSolides]{Couleur};
    
    vardef BaseCylindre(text t)=
    save Cer;
    picture Cer;
    save n;
    n:=0;
    for p_=t:
    if color p_:
    n:=n+1;
    _T[n]:=p_;
    fi;
    endfor;
    pascercle:=5;
    color ptcer[];
    for k=0 step pascercle until (360+pascercle) :
    ptcer[k div pascercle]-_T[1]=Distance(_T[1],_T[2])*((_T[4]-_T[3])*cosd(k)/Distance(_T[3],_T[4])+(_T[5]-_T[3])*sind(k)/Distance(_T[3],_T[5]));
    endfor;
    %
    color ddcer,cccer;
    nbpointilles:=0;
    nbtraces:=0;
    path PathSection[];
    nbpathsection:=0;
    Cer=image(%
    for k=0 step pascercle until 360:
    ddcer:=Oeil-ptcer[k div pascercle];
    cccer:=-Normal(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle],ptcer[k div pascercle]+Sommet1-Sommet2);
    if (ProduitScalaire(ddcer,cccer)>=0):
    nbtraces:=nbtraces+1;
    if (nbtraces=1) and (nbpointilles>0):
    draw chemin(ptcer[k div pascercle],ptcer[k div pascercle]+Sommet1-Sommet2);
    fi;
    nbpathsection:=nbpathsection+1;
    PathSection[nbpathsection]=chemin(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    draw chemin(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    draw chemin(ptcer[k div pascercle]+Sommet1-Sommet2,ptcer[(k+pascercle) div pascercle]+Sommet1-Sommet2);
    else:
    nbpointilles:=nbpointilles+1;
    nbtraces:=0;
    if (nbpointilles=1):
    draw chemin(ptcer[k div pascercle],ptcer[k div pascercle]+Sommet1-Sommet2);
    fi;
    if k mod (2*pascercle)=0:
    nbpathsection:=nbpathsection+1;
    PathSection[nbpathsection]=chemin(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    draw chemin(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    draw chemin(ptcer[k div pascercle]+Sommet1-Sommet2,ptcer[(k+pascercle) div pascercle]+Sommet1-Sommet2);
    fi;
    fi;
    endfor;
    );
    Cer
    enddef;

    Figure(-10u,-10u,10u,10u);
    Initialisation(PfCRho,PfCPhi,PfCTheta,PfCDistance);
%    Initialisation(1500,30,20,50);
    typetrace:="3D";
    typerepre:="persp";
    eclairage:=false;
    nb:=36;%36
    subh:=1;%
    incolor:=white;
    outcolor:=PfCOutColor;
    Ferme1:=true;
    angx:=anglerotationx;
    Objetcylindre1("r="&decimal(rayoncylindre),"h="&decimal(hauteurcylindre));
    eclairage:=false;
%    traits:=false;
%    AffichageObjet1;

    color O,S,A,M,B,C,D,Sommet[];
    Sommet2=(0,0,0);
    Sommet1-Sommet2=(0,0,hauteurcylindre);
    Sommet3-Sommet2=rayoncylindre*(cosd(0),-sind(0),0);
    Sommet4-Sommet2=rayoncylindre*(cosd(90),-sind(90),0);
    color MSection[];
    MSection[1]-Sommet2=rayoncylindre*(CoefSection,sin(arccos(CoefSection)),0);
    MSection[7]-Sommet2=rayoncylindre*(CoefSection+0.01,sin(arccos(CoefSection+0.01)),0);
    MSection[2]-Sommet2=rayoncylindre*(CoefSection,-sin(arccos(CoefSection)),0);
    MSection[3]-MSection[2]=Sommet1-Sommet2;
    MSection[4]-MSection[1]=Sommet1-Sommet2;
    MSection[5]-Sommet2=CoefSection[Sommet1,Sommet2];
    MSection[6]-MSection[5]=MSection[2]-MSection[1];
    Sommet1:=RotXYZ(Sommet1);
    Sommet2:=RotXYZ(Sommet2);
    Sommet3:=RotXYZ(Sommet3);
    Sommet4:=RotXYZ(Sommet4);
    MSection[1]:=RotXYZ(MSection[1]);
    MSection[2]:=RotXYZ(MSection[2]);
    MSection[3]:=RotXYZ(MSection[3]);
    MSection[4]:=RotXYZ(MSection[4]);
    MSection[5]:=RotXYZ(MSection[5]);
    MSection[6]:=RotXYZ(MSection[6]);
    MSection[7]:=RotXYZ(MSection[7]);

    trace BaseCylindre(Sommet2,Sommet3,Sommet2,Sommet3,Sommet4);
    currentpicture:=nullpicture;
    
    if Sections:
    if Section="parallele":
    if RemplisSection:
    fill polygone(MSection[1],MSection[2],MSection[3],MSection[4]) withcolor CouleurSection;
    fi;
    color dcer,ccer;
    invnormale:=if CoefSection<=0:-1 else:1 fi;
    %1er côté et 3eme côté : face "basse" et face "haute"
    dcer:=Oeil-Sommet3;
    ccer:=-Normal(Sommet3,MSection1,MSection2);
    draw chemin(MSection1,MSection2) if (ProduitScalaire(dcer,ccer)<0):dashed evenly fi;
    draw chemin(MSection3,MSection4) if (ProduitScalaire(dcer,ccer)>0):dashed evenly fi;
    % 2eme côté et 4eme coté
    dcer:=Oeil-MSection7;
    ccer:=-Normal(MSection7,MSection4,MSection1);
    draw chemin(MSection4,MSection1) if (ProduitScalaire(dcer,ccer)<0):dashed evenly fi;
    draw chemin(MSection2,MSection3) if (ProduitScalaire(dcer,ccer)>0):dashed evenly fi;
    else:
    if RemplisSection:
    fill (PathSection[1] for p_=2 upto nbpathsection:--PathSection[p_] endfor--cycle) shifted(Projette(CoefSection[Sommet1,Sommet2]-Sommet2)) withcolor CouleurSection;
    fi;
    for p_=1 upto nbpathsection:
    draw (PathSection[p_] shifted(Projette(CoefSection[Sommet1,Sommet2]-Sommet2)));
    endfor;
    fi;
    fi;
    
    trace BaseCylindre(Sommet2,Sommet3,Sommet2,Sommet3,Sommet4);

    color dcer,ccer;
    dcer:=Oeil-Sommet2;
    ccer:=Normal(Sommet2,Sommet3,Sommet4);
    if (ProduitScalaire(dcer,ccer)>=0):
    draw Cercles(Sommet2,Sommet3,Sommet2,Sommet3,Sommet4);
    fi;
    dcer:=Oeil-Sommet1;
    ccer:=Normal(Sommet1,Sommet4+Sommet1-Sommet2,Sommet3+Sommet1-Sommet2);
    if (ProduitScalaire(dcer,ccer)>=0):
    draw Cercles(Sommet1,Sommet3+Sommet1-Sommet2,Sommet1,Sommet3+Sommet1-Sommet2,Sommet4+Sommet1-Sommet2);
    fi;

    vardef EcrireSommets(text t)=
    nb:=0;
    for p_=t:
    nb:=nb+1;
    if bluepart(Sommet1)>bluepart(Sommet2):
    if nb=1:
    label.ulft(TEX(p_),Projette(Sommet1));%p_
    elseif nb=2:
    dotlabel.rt(TEX(p_),Projette(Sommet2));%p_
    fi;
    else:
    if nb=1:
    label.bot(TEX(p_),Projette(Sommet1));
    elseif nb=2:
    dotlabel.ulft(TEX(p_),Projette(Sommet2));
    fi;
    fi;
    endfor;
    enddef;

    DefinirSommets(#1);
    DefinirSommetsSection(#3);
    
    if Axes:
    draw segment(1.5[Sommet1,Sommet2],1.5[Sommet2,Sommet1]) dashed dashpattern(on6 off3 on3 off 3);
    remplis (fullcircle scaled 1mm) shifted(Projette(Sommet1));
    remplis (fullcircle scaled 1mm) shifted(Projette(Sommet2));
    fi;
    
    if Code:
    \useKV[ClesSolides]{Traces};
    fi;
    
  \end{mplibcode}
  \fi
}

\newcommand\MPSolidePyramide[4]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}

    input PfCSolid;
    
    boolean Pointilles,TraceArete,NommeSommets,Code,Reguliere,AutoLabel,Sections,RemplisSection;
    Sections:=\useKV[ClesSolides]{Sections};
    RemplisSection=\useKV[ClesSolides]{RemplisSection};
    if RemplisSection:color CouleurSection;CouleurSection=\useKV[ClesSolides]{CouleurSection};fi;
    AutoLabel:=\useKV[ClesSolides]{AutoLabel};
    Pointilles=\useKV[ClesSolides]{Pointilles};
    TraceArete=\useKV[ClesSolides]{Aretes};
    NommeSommets=\useKV[ClesSolides]{Sommets};
    Code=\useKV[ClesSolides]{Code};
    Reguliere:=\useKV[ClesSolides]{Reguliere};
    % Initialisation
    PfCRho=\useKV[ClesSolides]{Rho};
    PfCPhi=\useKV[ClesSolides]{Phi};
    PfCTheta=\useKV[ClesSolides]{Theta};
    PfCDistance=\useKV[ClesSolides]{Distance};
    CoefSection=\useKV[ClesSolides]{CoefSection};
    anglerotationx=\useKV[ClesSolides]{Anglex};
    hauteurpyramide=\useKV[ClesSolides]{HauteurPyramide};
    nombresommets=\useKV[ClesSolides]{SommetsPyramide};
    color PfCOutColor,DecalageSommet;
    PfCOutColor=\useKV[ClesSolides]{Couleur};
    DecalageSommet=if Reguliere:(0,0,0) else: #3 fi;
    
    Figure(-10u,-10u,10u,10u);
    Initialisation(PfCRho,PfCPhi,PfCTheta,PfCDistance);
    typetrace:="3D";
    typerepre:="persp";
    if Pointilles=false:
    pointilles:="non";
    fi;

    Ferme1:=true;

    color O,A[],S;
    O=(0,0,0);
    S-O=(0,0,hauteurpyramide)+DecalageSommet;

    NbS:=nombresommets;
    Sommet1:=S;
    ecartangle=360/(NbS-1);
    for k=2 upto NbS:
    if Reguliere:
    repereangle:=(k-2)*ecartangle;
    else:
    repereangle:=(k-2)*ecartangle+(ecartangle*0.25+uniformdeviate(floor(ecartangle/2)));
    fi;
    Sommet[k]:=(cosd(repereangle),-sind(repereangle),0);
    endfor;
    Sommet[NbS+1]:=Sommet[2];

    color TS[];
    for k=1 upto (NbS+1):
    TS[k]=Sommet[k];
    endfor;
    color PiedHauteur;
    PiedHauteur=ProjectionsurPlan(Sommet1,Sommet2,Sommet3,Sommet4);
    eclairage:=false;
    traits:=false;
    outcolor:=PfCOutColor;
    angx:=anglerotationx;
    for k=1 upto (NbS+1):
    TS[k]:=RotXYZ(TS[k]);
    endfor;
    angx:=0;

    color MSection[];
    for p_=2 upto NbS:
    MSection[p_-1]=CoefSection[Sommet[1],Sommet[p_]];
    endfor;

    DefinirSommetsSection(#4);
    
    vardef SectionPyramide(expr fracsection)=
    save Section;
    picture Section;
    Section=image(%
    if RemplisSection:
    remplis polygone(fracsection[Sommet1,Sommet2],for p_=3 upto NbS-1:fracsection[Sommet1,Sommet[p_]],endfor fracsection[Sommet1,Sommet[NbS]]) withcolor CouleurSection;
    fi;
    color dcer,ccer;
    for p_=2 upto NbS:
    dcer:=Oeil-Sommet[p_];
    ccer:=-Normal(Sommet1,Sommet[p_],Sommet[p_+1]);
    if (ProduitScalaire(dcer,ccer)>=0):
    draw chemin(fracsection[Sommet1,Sommet[p_]],fracsection[Sommet1,Sommet[p_+1]]);
    else:
    draw chemin(fracsection[Sommet1,Sommet[p_]],fracsection[Sommet1,Sommet[p_+1]]) dashed evenly;
    fi;
    endfor;
    );
    Section
    enddef;
    
    ObjetNew1(%
    TS1, for k=2 upto NbS:TS[k], endfor TS[NbS+1]
    )(%
    NbS-1, for p_=2 upto NbS:p_, endfor 
    for p=2 upto NbS:
    3,1,p+1,p,%
    endfor);
    AffichageObjet1;

    Sommet[NbS+1]:=Sommet[2];

    if Sections:
    draw SectionPyramide(CoefSection);
    fi;
    
    NF:=NbS;%nombresommets;
    % Fc[100] est la base
    Fc[100]:=NbS-1;
    for k=2 upto NbS:
    Fc[100+k-1]:=k;
    endfor;
    for k=2 upto NF:
    Fc[k*100]:=3;
    Fc[k*100+1]:=1;
    Fc[k*100+2]:=k+1;
    Fc[k*100+3]:=k;
    endfor;
    DessineObjet;

    vardef EcrireSommets(text t)=
    if AutoLabel:
    nb:=0;
    for p_=t:
    nb:=nb+1;
    if nb<NbS+1:
    if nb>1:
    label(TEX(""&p_&""),1.1[Projette(Sommet1),Projette(Sommet[nb])]);
    else:
    label(TEX(p_),1.1[Projette(Sommet[2]),Projette(Sommet[1])]);
    fi;
    fi;
    endfor;
    fi;
    enddef;
     
    DefinirSommets(#1);

    if TraceArete=false:
    currentpicture:=nullpicture;    
    fi;
    if NommeSommets:
    EcrireSommets(#2);
    fi;
    u:=0.25u;
    marque_p:="croix";
    nbcroix=0;
    for p_=#1:
    nbcroix:=nbcroix+1;
    if nbcroix<NbS+1:
    pointe(p_);
    fi;
    endfor;
    u:=1cm;
    if Code:
    \useKV[ClesSolides]{Traces};
    fi;

  \end{mplibcode}
  \fi
}

\newcommand\MPSolideCone[3]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    boolean NommeSommets,Code,Sections,Axes,RemplisSection;
    NommeSommets=\useKV[ClesSolides]{Sommets};
    Code=\useKV[ClesSolides]{Code};
    Axes:=\useKV[ClesSolides]{Axes};
    Sections=\useKV[ClesSolides]{Sections};
    RemplisSection=\useKV[ClesSolides]{RemplisSection};
    if RemplisSection:color CouleurSection;CouleurSection=\useKV[ClesSolides]{CouleurSection};fi;
    %Initialisation
    PfCRho=\useKV[ClesSolides]{Rho};
    PfCPhi=\useKV[ClesSolides]{Phi};
    PfCTheta=\useKV[ClesSolides]{Theta};
    PfCDistance=\useKV[ClesSolides]{Distance};
    CoefSection=\useKV[ClesSolides]{CoefSection};
    anglerotationx=\useKV[ClesSolides]{Anglex};
    rayoncone=\useKV[ClesSolides]{RayonCone};
    hauteurcone=\useKV[ClesSolides]{HauteurCone};
    
    color PfCOutColor;
    PfCOutColor=\useKV[ClesSolides]{Couleur};
    input PfCSolid;
    
    vardef BaseCone(text t)=
    save Cer;
    picture Cer;
    save n;
    n:=0;
    for p_=t:
    if color p_:
    n:=n+1;
    _T[n]:=p_;
    fi;
    endfor;
    pascercle:=5;
    color ptcer[];
    for k=0 step pascercle until (360+pascercle) :
    ptcer[k div pascercle]-_T[1]=Distance(_T[1],_T[2])*((_T[4]-_T[3])*cosd(k)/Distance(_T[3],_T[4])+(_T[5]-_T[3])*sind(k)/Distance(_T[3],_T[5]));
    endfor;
    %
    color ddcer,cccer;
    nbpointilles:=0;
    nbtraces:=0;
    Cer=image(%
    for k=0 step pascercle until 360:
    ddcer:=Oeil-ptcer[k div pascercle];
    cccer:=-Normal(Sommet1,ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    if (ProduitScalaire(ddcer,cccer)>=0):
    nbtraces:=nbtraces+1;
    if (nbtraces=1) and (nbpointilles>0):
    draw chemin(ptcer[k div pascercle],Sommet1);
    fi;
    draw chemin(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    else:
    nbpointilles:=nbpointilles+1;
    nbtraces:=0;
    if (nbpointilles=1):
    draw chemin(ptcer[k div pascercle],Sommet1);
    fi;
    if k mod (2*pascercle)=0:
    draw chemin(ptcer[k div pascercle],ptcer[(k+pascercle) div pascercle]);
    fi;
    fi;
    endfor;
    );
    Cer
    enddef;

    Figure(-10u,-10u,10u,10u);
    Initialisation(PfCRho,PfCPhi,PfCTheta,PfCDistance);
    typetrace:="3D";
    typerepre:="persp";
    eclairage:=false;
    nb:=36;%36
    subh:=1;%
    incolor:=white;
    outcolor:=PfCOutColor;
    Ferme1:=true;
    angx:=anglerotationx;
    Objetcone1("r="&decimal(rayoncone),"h="&decimal(hauteurcone));
    traits:=false;
    AffichageObjet1;

    color Sommet[];%O,S,A,M,B,C,D,
    Sommet2=(0,0,0);
    Sommet1-Sommet2=(0,0,hauteurcone);
    Sommet3-Sommet2=rayoncone*(cosd(0),-sind(0),0);
    Sommet4-Sommet2=rayoncone*(cosd(90),-sind(90),0);
    Sommet1:=RotXYZ(Sommet1);
    Sommet3:=RotXYZ(Sommet3);
    Sommet4:=RotXYZ(Sommet4);

    color MSection[];
    MSection[1]=CoefSection[Sommet1,Sommet2];

    DefinirSommetsSection(#3);
    
    if Sections:
    if RemplisSection:
    remplis Cercles(CoefSection[Sommet1,Sommet2],CoefSection[Sommet1,Sommet3],CoefSection[Sommet1,Sommet2],CoefSection[Sommet1,Sommet3],CoefSection[Sommet1,Sommet4]) withcolor CouleurSection;
    fi;
    trace BaseCone(CoefSection[Sommet1,Sommet2],CoefSection[Sommet1,Sommet3],CoefSection[Sommet1,Sommet2],CoefSection[Sommet1,Sommet3],CoefSection[Sommet1,Sommet4]);
    fi;

    trace BaseCone(Sommet2,Sommet3,Sommet2,Sommet3,Sommet4);
    color dcer,ccer;
    dcer:=Oeil-Sommet2;
    ccer:=Normal(Sommet2,Sommet3,Sommet4);
    if (ProduitScalaire(dcer,ccer)>=0):
    draw Cercles(Sommet2,Sommet3,Sommet2,Sommet3,Sommet4);
    fi;

    vardef EcrireSommets(text t)=
    nb:=0;
    for p_=t:
    nb:=nb+1;
    if bluepart(Sommet1)>bluepart(Sommet2):
    if nb=1:
    label.ulft(TEX(p_),Projette(Sommet1));
    elseif nb=2:
    dotlabel.rt(TEX(p_),Projette(Sommet2));
    fi;
    else:
    if nb=1:
    label.bot(TEX(p_),Projette(Sommet1));
    elseif nb=2:
    dotlabel.ulft(TEX(p_),Projette(Sommet2));
    fi;
    fi;
    endfor;
    enddef;

    DefinirSommets(#1);

    if Axes:
    draw segment(1.5[Sommet1,Sommet2],1.5[Sommet2,Sommet1]) dashed dashpattern(on6 off3 on3 off 3);
    remplis (fullcircle scaled 1mm) shifted(Projette(Sommet1));
    remplis (fullcircle scaled 1mm) shifted(Projette(Sommet2));
    fi;

    if Code:
    \useKV[ClesSolides]{Traces};
    fi;

  \end{mplibcode}
  \fi
}

\newcommand\MPSolidePave[5]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCSolid;
    
    boolean Pointilles,TraceArete,NommeSommets,Code,AutoLabel,Sections,RemplisSection;
    AutoLabel:=\useKV[ClesSolides]{AutoLabel};
    Pointilles=\useKV[ClesSolides]{Pointilles};
    TraceArete=\useKV[ClesSolides]{Aretes};
    NommeSommets=\useKV[ClesSolides]{Sommets};
    Code=\useKV[ClesSolides]{Code};
    Sections:=\useKV[ClesSolides]{Sections};
    RemplisSection=\useKV[ClesSolides]{RemplisSection};
    if RemplisSection:color CouleurSection;CouleurSection=\useKV[ClesSolides]{CouleurSection};fi;

    string Section;
    if Sections:Section=\useKV[ClesSolides]{Section};fi;
    
    %Initialisation
    PfCRho=\useKV[ClesSolides]{Rho};
    PfCPhi=\useKV[ClesSolides]{Phi};
    PfCTheta=\useKV[ClesSolides]{Theta};
    PfCDistance=\useKV[ClesSolides]{Distance};
    
    Figure(-10u,-10u,10u,10u);
    Initialisation(PfCRho,PfCPhi,PfCTheta,PfCDistance);
    typetrace:="3D";
    typerepre:="persp";
    if Pointilles=false:
    pointilles:="non";
    fi;
    color A,B,C,D,E,F,G,H;
    color Sommet[];
    trace Pave(A,B,C,D,E,F,G,H)(#3);
    currentpicture:=nullpicture;
    Sommet1=A;
    Sommet2=B;
    Sommet3=C;
    Sommet4=D;
    Sommet5=E;
    Sommet6=F;
    Sommet7=G;
    Sommet8=H;

    DefinirSommets(#1);
    
    color MSection[];
    numeric RetiensSection[];
    numretienssection:=0;
    color RetiensDefSection[];
    numretiensdefsection:=0;
    if Sections:
    if Section="arete":
    for p_=#5:
    if numeric p_:
    numretienssection:=numretienssection+1;
    RetiensSection[numretienssection]=p_;
    elseif color p_:
    numretiensdefsection:=numretiensdefsection+1;
    RetiensDefSection[numretiensdefsection]=p_;
    fi;    
    endfor;
    % On dessine la section
    MSection[1]=(RetiensSection[1])[RetiensDefSection[1],RetiensDefSection[2]];
    MSection[2]=(RetiensSection[2])[RetiensDefSection[3],RetiensDefSection[4]];
    MSection[3]-MSection[2]=RetiensDefSection[6]-RetiensDefSection[5];
    MSection[4]-MSection[1]=RetiensDefSection[6]-RetiensDefSection[5];
    if RemplisSection:
    fill polygone(MSection1,MSection2,MSection3,MSection4) withcolor CouleurSection;
    fi;
%    DotLabel.top(TEX("M1"),MSection[1]);
%    DotLabel.top(TEX("M2"),MSection[2]);
%    DotLabel.top(TEX("M3"),MSection[3]);
%    DotLabel.top(TEX("M4"),MSection[4]);
%    if RemplisSection:
%    fill polygone(MSection1,MSection2,MSection3,MSection4) withcolor CouleurSection;
%    fi;
%    trace polygone(MSection1,MSection2,MSection3,MSection4);
    color dcer,ccer;
    % 1er cote -> ok
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[4],RetiensDefSection[2],RetiensDefSection[1]);
    draw chemin(MSection1,MSection2) if (ProduitScalaire(dcer,ccer)<0):dashed evenly fi;
    % 2eme cote
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[4],RetiensDefSection[3],RetiensDefSection[4]+RetiensDefSection[6]-RetiensDefSection[5]);
    draw chemin(MSection2,MSection3) if (ProduitScalaire(dcer,ccer)<0):dashed evenly fi;
    % 3eme cote
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[4],RetiensDefSection[2],RetiensDefSection[1]);
    draw chemin(MSection3,MSection4) if (ProduitScalaire(dcer,ccer)>=0):dashed evenly fi;
    % 4eme cote
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[4],RetiensDefSection[3],RetiensDefSection[4]+RetiensDefSection[6]-RetiensDefSection[5]);
    draw chemin(MSection4,MSection1) if (ProduitScalaire(dcer,ccer)>=0):dashed evenly fi;
    else:
    %face 
    for p_=#5:
    if numeric p_:
    numretienssection:=numretienssection+1;
    RetiensSection[numretienssection]=p_;
    elseif color p_:
    numretiensdefsection:=numretiensdefsection+1;
    RetiensDefSection[numretiensdefsection]=p_;
    fi;    
    endfor;
    % On dessine la section
    MSection[1]=(RetiensSection[1])[RetiensDefSection[1],RetiensDefSection[2]];
    MSection[2]-MSection[1]=RetiensDefSection[4]-RetiensDefSection[3];
    MSection[3]-MSection[2]=RetiensDefSection[5]-RetiensDefSection[4];
    MSection[4]-MSection[1]=MSection[3]-MSection[2];
%    DotLabel.top(TEX("M1"),MSection[1]);
%    DotLabel.top(TEX("M2"),MSection[2]);
%    DotLabel.top(TEX("M3"),MSection[3]);
%    DotLabel.top(TEX("M4"),MSection[4]);
    if RemplisSection:
    fill polygone(MSection1,MSection2,MSection3,MSection4) withcolor CouleurSection;
    fi;
    color dcer,ccer;
    % 1er cote -> ok
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[4],RetiensDefSection[2],RetiensDefSection[1]);
    draw chemin(MSection1,MSection2) if (ProduitScalaire(dcer,ccer)<0):dashed evenly fi;
    % 2eme cote
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[5],RetiensDefSection[4],RetiensDefSection[5]+RetiensDefSection[1]-RetiensDefSection[2]);
    draw chemin(MSection2,MSection3) if (ProduitScalaire(dcer,ccer)<0):dashed evenly fi;
    % 3eme cote
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[4],RetiensDefSection[2],RetiensDefSection[1]);
    draw chemin(MSection3,MSection4) if (ProduitScalaire(dcer,ccer)>=0):dashed evenly fi;
    % 4eme cote
    dcer:=Oeil-RetiensDefSection[4];
    ccer:=Normal(RetiensDefSection[5],RetiensDefSection[4],RetiensDefSection[5]+RetiensDefSection[1]-RetiensDefSection[2]);
    draw chemin(MSection4,MSection1) if (ProduitScalaire(dcer,ccer)>=0):dashed evenly fi;
    fi;
    %On trace la section considérée
    %trace polygone(MSection1,MSection2,MSection3,MSection4);
    fi;

    trace Pave(A,B,C,D,E,F,G,H)(#3);
    
    DefinirSommetsSection(#4);
    
    if TraceArete=false:
    currentpicture:=nullpicture;    
    fi;
    if NommeSommets:
    EcrireSommetsPave(#2);
    fi;
    u:=0.25u;
    marque_p:="croix";
    nbcroix=0;
    for p_=#1:
    nbcroix:=nbcroix+1;
    if nbcroix=4:
    if Pointilles:
    pointe(p_);
    fi;
    else:
    pointe(p_);
    fi;
    endfor;
    u:=1cm;
    if Code:
    \useKV[ClesSolides]{Traces};
    fi;
  \end{mplibcode}
  \fi
}

\newcommand\MPSolideSphere[3]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    boolean NommeSommets,Code,Sections,Axes,RemplisSection;
    NommeSommets=\useKV[ClesSolides]{Sommets};
    Code=\useKV[ClesSolides]{Code};
    Axes:=\useKV[ClesSolides]{Axes};
    Sections=\useKV[ClesSolides]{Sections};
    RemplisSection=\useKV[ClesSolides]{RemplisSection};
    if RemplisSection:color CouleurSection;CouleurSection=\useKV[ClesSolides]{CouleurSection};fi;
    %Initialisation
    PfCRho=\useKV[ClesSolides]{Rho};
    PfCPhi=0;%\useKV[ClesSolides]{Phi};
    PfCTheta=10;%\useKV[ClesSolides]{Theta};
    PfCDistance=\useKV[ClesSolides]{Distance};
    CoefSection=\useKV[ClesSolides]{CoefSection};
    anglerotationx=\useKV[ClesSolides]{Anglex};
    rayonsphere=\useKV[ClesSolides]{RayonSphere};
    
    color PfCOutColor;
    PfCOutColor=\useKV[ClesSolides]{Couleur};
    input PfCSolid;
    
    vardef BaseSphere=
    save Cer;
    picture Cer;
    color PtInter.iso,PtInter[];
    vardef Famille(expr u,v)=(R*(cos(u)*cos(v),cos(u)*sin(v),sin(u))) enddef;
    subh:=72;
    Cer=image(%
    if Sections:
    if RemplisSection:fill (Cercles(Image((0,0,0)),Image((0,1,0)),Image((0,0,0)),Image((0,1,0)),Image((-1,0,0))) scaled (sqrt(1-(abs(CoefSection+0.02))**2))) shifted(Projette(MSection1-Sommet1)) withcolor CouleurSection; fi;
    fi;
    %Equateur
    umin:=0; umax:=pi/nb; upas:=pi/nb;
    vmin:=0; vpas:=2*pi/subh; vmax:=2*pi;
    for l=0 upto subh-1:
    PtInter[1]:=Image(Famille(umin+(0+1)*upas,vmin+l*vpas));
    PtInter[2]:=Image(Famille(umin+0*upas,vmin+l*vpas));
    PtInter[3]:=Image(Famille(umin+0*upas,vmin+(l+1)*vpas));
    PtInter[4]:=Image(Famille(umin+(0+1)*upas,vmin+(l+1)*vpas));
    PtInter.iso:=(PtInter[1]+PtInter[2]+PtInter[3]+PtInter[4])/4;
    if ProduitScalaire(Oeil-PtInter.iso,Normal(PtInter.iso,PtInter[4],PtInter[1]))>=0:
    if Sections:
    draw (segment(PtInter[3],PtInter[2]) scaled (sqrt(1-(abs(CoefSection+0.02))**2))) shifted(Projette(MSection1-Sommet1));
    fi;
    draw segment(PtInter[3],PtInter[2]);
    else:
    if l mod 2=0:
    if Sections:
    draw (segment(PtInter[3],PtInter[2]) scaled (sqrt(1-(abs(CoefSection+0.02))**2))) shifted(Projette(MSection1-Sommet1));
    fi;
    draw segment(PtInter[3],PtInter[2]);
    fi;
    fi;
    endfor;
    
    % "Exterieur"
    nb:=72;
    subh:=18;
    umin:=-pi; umax:=pi; upas:=2*pi/nb;
    vpas:=2*pi/subh; vmin:=pi/2; vmax:=2*pi;
    for k=0 upto nb-1:
    PtInter[1]:=Image(Famille(umin+(k+1)*upas,vmin+0*vpas));
    PtInter[2]:=Image(Famille(umin+k*upas,vmin+0*vpas));
    PtInter[3]:=Image(Famille(umin+k*upas,vmin+(0+1)*vpas));
    PtInter[4]:=Image(Famille(umin+(k+1)*upas,vmin+(0+1)*vpas));
    PtInter.iso:=(PtInter[1]+PtInter[2]+PtInter[3]+PtInter[4])/4;
    draw segment(PtInter[2],PtInter[1]);
    endfor;
    );
    Cer
    enddef;

    Figure(-10u,-10u,10u,10u);
    Initialisation(PfCRho,PfCPhi,PfCTheta,PfCDistance);
    typetrace:="3D";
    typerepre:="persp";
    eclairage:=false;
    nb:=24;%36
    subh:=36;%
    incolor:=blue;
    outcolor:=white;%PfCOutColor;
    Ferme1:=true;
    angx:=anglerotationx;
    Objetsphere1("R="&decimal(rayonsphere));
    % traits:=false;
    % AffichageObjet1;
    color Sommet[],SommetN,SommetS,SommetB;
    Sommet1=(0,0,0);
    Sommet2=(0,rayonsphere,0);
    Sommet3=(-rayonsphere,0,0);
    Sommet4=(0,0,rayonsphere);
    SommetN=Sommet4;
    SommetS=(0,0,-rayonsphere);
    SommetB=(rayonsphere,0,0);
    Sommet2:=RotXYZ(Sommet2);
    Sommet3:=RotXYZ(Sommet3);
    Sommet4:=RotXYZ(Sommet4);
    SommetN:=RotXYZ(SommetN);
    SommetS:=RotXYZ(SommetS);
    SommetB:=RotXYZ(SommetB);
    color MSection[];
    MSection[1]=CoefSection[Sommet1,SommetN];
    MSection[2]=Image((0,sqrt(1-CoefSection**2),CoefSection));    

    trace BaseSphere;

    DefinirSommets(#1);
    DefinirSommetsSection(#3);

    if Axes:
    draw segment(1.25[SommetN,SommetS],1.25[SommetS,SommetN]) dashed dashpattern(on6 off3 on3 off3);
    remplis (fullcircle scaled 1mm) shifted(Projette(SommetN));
    remplis (fullcircle scaled 1mm) shifted(Projette(SommetS));
    fi;

    if Code:
    \useKV[ClesSolides]{Traces};
    fi;

  \end{mplibcode}
  \fi
}

\def\UpdatetoksSolide#1\nil{\addtotok\toksolidelistesommets{"#1",}}
\newtoks\toksolidelistesommets%
\newtoks\toksolidelistepointssections%

\newcommand\Solide[1][]{%
  \useKVdefault[ClesSolides]%
  \setKV[ClesSolides]{#1}%
  \setsepchar{,}\ignoreemptyitems%
  \xdef\foo{\useKV[ClesSolides]{ListeSommets}}%
  \readlist*\ListeNomSommet{\foo}%\showitems\ListeNomSommet
  \reademptyitems%
  \toksolidelistesommets{}
  \foreachitem\compteur\in\ListeNomSommet{\expandafter\UpdatetoksSolide\compteur\nil}%\the\toksolidelistesommets%
  \IfStrEqCase{\useKV[ClesSolides]{Nom}}{%
    {cube}{%
      \MPSolidePave{\useKV[ClesSolides]{ListeSommets}}{\the\toksolidelistesommets}{1,1,1}{\useKV[ClesSolides]{PointsSection}}{\useKV[ClesSolides]{ObjetSection}}%
    }%
    {pave}{%
      \MPSolidePave{\useKV[ClesSolides]{ListeSommets}}{\the\toksolidelistesommets}{\useKV[ClesSolides]{Profondeur},\useKV[ClesSolides]{Largeur},\useKV[ClesSolides]{Hauteur}}{\useKV[ClesSolides]{PointsSection}}{\useKV[ClesSolides]{ObjetSection}}%
    }%
    {cone}{%
      \MPSolideCone{\useKV[ClesSolides]{ListeSommets}}{\the\toksolidelistesommets}{\useKV[ClesSolides]{PointsSection}}%
    }%
    {pyramide}{%
      \MPSolidePyramide{\useKV[ClesSolides]{ListeSommets}}{\the\toksolidelistesommets}{\useKV[ClesSolides]{DecalageSommet}}{\useKV[ClesSolides]{PointsSection}}%
    }%
    {cylindre}{%
      \MPSolideCylindre{\useKV[ClesSolides]{ListeSommets}}{\the\toksolidelistesommets}{\useKV[ClesSolides]{PointsSection}}%
    }%
    {sphere}{%
      \MPSolideSphere{\useKV[ClesSolides]{ListeSommets}}{\the\toksolidelistesommets}{\useKV[ClesSolides]{PointsSection}}%
    }%
  }%
}%

%%%
% Vue Cubes
%%%
\setKVdefault[VueCubes]{Solution=false,Hauteur=5,Profondeur=4,Largeur=3,Angle=60,Nom=Ex1,Trou=false,Echelle=0.25,CouleurCube=LightSteelBlue,CouleurFleche=LightGray,Face=false,Creation=false,Grilles=false}

\newtoks\toklisteVueCube%
\def\UpdatetoksVueCube#1\nil{\addtotok\toklisteVueCube{#1,}}%

\NewDocumentCommand\VueCubes{o m}{%
  \useKVdefault[VueCubes]%
  \setKV[VueCubes]{#1}
  \ifboolKV[VueCubes]{Solution}{%
    \BuildVueCubesSolution%
  }{%
    \ifboolKV[VueCubes]{Creation}{%Le nombre de données doit être compatible avec le "volume du pavé droit"
      \ignoreemptyitems%
      \readlist*\PfCListeHauteursCubes{#2}%
      \reademptyitems%
      \toklisteVueCube{}%
      \foreachitem\compteur\in\PfCListeHauteursCubes{\expandafter\UpdatetoksVueCube\compteur\nil}%
      \BuildVueCubes{\useKV[VueCubes]{Angle}}{\the\toklisteVueCube}%
    }{%
      \BuildVueCubes{\useKV[VueCubes]{Angle}}{}%
    }%
  }%
}%

\NewDocumentCommand\BuildVueCubes{m m}{%
  \ifluatex
  \mplibforcehmode
  \xdef\PfCVueCubeNom{\useKV[VueCubes]{Nom}}%
  \begin{mplibcode}[\PfCVueCubeNom]
    input PfCSolid;

    intensite:=1.5;

    Ferme[0]:=false;
    outcolor:=\useKV[VueCubes]{CouleurCube};
    incolor:=white;
    nb:=1;subh:=1;
    creux:=true;

    Profondeur:=\useKV[VueCubes]{Profondeur};
    Largeur:=\useKV[VueCubes]{Largeur};
    Hauteur:=\useKV[VueCubes]{Hauteur};
    Phi:=#1;
    Echelle:=\useKV[VueCubes]{Echelle};

    color CouleurFleche;
    CouleurFleche:=\useKV[VueCubes]{CouleurFleche};
    
    boolean Trou,FaceVue,Creation,Grille;
    Trou:=\useKV[VueCubes]{Trou};
    FaceVue:=\useKV[VueCubes]{Face};
    Creation:=\useKV[VueCubes]{Creation};
    Grille:=\useKV[VueCubes]{Grilles};
    
    TotalObj:=0;

    vardef CreationSolide(text t)=
    PfCnbcubes:=0;
    for p_=t:
    m:=(PfCnbcubes div Profondeur);
    k:=(PfCnbcubes mod Profondeur);
    hauteurtour[m+1][k+1]:=p_;
    for l=1 upto hauteurtour[m+1][k+1]:
    TotalObj:=incr TotalObj;
    TR:=(-Echelle*k,(m+1)*Echelle,Echelle*l-Echelle/2);
    ObjetDeplacement[TotalObj](0);
    endfor;
    PfCnbcubes:=incr PfCnbcubes;
    endfor;
    enddef;

    Initialisation(2500,Phi,20,50);
    Objetcube0("a="&decimal(Echelle));
    
    if Creation:
    CreationSolide(#2);
    else:
    for k=1 upto Profondeur:%4 profondeur
    hauteurtour[0][k]:=Hauteur;%5 hauteur totale
    endfor;
    for m=1 upto Largeur:%3 largeur
    for k=1 upto Profondeur:%4 profondeur
    if Trou:
    if m>1:
    hauteurtour[m][k]:=floor(uniformdeviate(hauteurtour[m-1][k]+1));%5 hauteur totale
    else:
    hauteurtour[m][k]:=1+floor(uniformdeviate(hauteurtour[m-1][k]));%5 hauteur totale
    fi;
    else:
    hauteurtour[m][k]:=1+floor(uniformdeviate(hauteurtour[m-1][k]));%5 hauteur totale
    fi;
    for l=1 upto hauteurtour[m][k]:
    TotalObj:=incr TotalObj;
    TR:=(-Echelle*(k-1),m*Echelle,Echelle*l-Echelle/2);
    ObjetDeplacement[TotalObj](0);
    endfor;
    endfor;
    endfor;
    fi;

    % Pour la fleche
    path Fleche;
    color A[];
    if FaceVue:
    A0=Echelle*(1,Largeur/2,0);
    A1-A0=0.25*(2,2,0);
    A2-A1=0.25*(0,-1,0);
    A3-A2=0.25*(2,0,0);
    A4-A3=0.25*(0,-2,0);
    A5-A4=A2-A3;
    A6-A5=A2-A1;
    Fleche=Projette(A0)--Projette(A1)--Projette(A2)--Projette(A3)--Projette(A4)--Projette(A5)--Projette(A6)--cycle;
    fill Fleche withcolor CouleurFleche;
    draw Fleche;
    fi;    
    
    nbobj:=TotalObj;
    DessineFusion;

    if Grille:
    % dessus
    color Ad[];
    Ad0=(0.5Echelle,0.5*Echelle,-0.5);
    Ad1-Ad0=(0,Largeur*Echelle,0);
    Ad2-Ad1=(-Profondeur*Echelle,0,0);
    Ad3-Ad2=Ad0-Ad1;
    draw Projette(Ad0) for k=1 upto 3: --Projette(Ad[k]) endfor --cycle;
    for k=1 upto Largeur-1:
    draw Projette((k/Largeur)[Ad0,Ad1])--Projette((k/Largeur)[Ad3,Ad2]);
    endfor;
    for k=1 upto Profondeur-1:
    draw Projette((k/Profondeur)[Ad0,Ad3])--Projette((k/Profondeur)[Ad1,Ad2]);
    endfor;
    % face
    color Af[];
    Af0=(-1-Profondeur*Echelle,0.5*Echelle,0);
    Af1-Af0=(0,Largeur*Echelle,0);
    Af2-Af1=(0,0,Hauteur*Echelle);
    Af3-Af2=Af0-Af1;
    draw Projette(Af0) for k=1 upto 3: --Projette(Af[k]) endfor --cycle;
    for k=1 upto Largeur-1:
    draw Projette((k/Largeur)[Af0,Af1])--Projette((k/Largeur)[Af3,Af2]);
    endfor;
    for k=1 upto Hauteur-1:
    draw Projette((k/Hauteur)[Af0,Af3])--Projette((k/Hauteur)[Af1,Af2]);
    endfor;
    % droite
    color Adg[];
    Adg0=(0.5Echelle,-Largeur*Echelle-1,0);
    Adg1-Adg0=(-Profondeur*Echelle,0,0);
    Adg2-Adg1=(0,0,Hauteur*Echelle);
    Adg3-Adg2=Adg0-Adg1;
    draw Projette(Adg0) for k=1 upto 3: --Projette(Adg[k]) endfor --cycle;
    for k=1 upto Profondeur-1:
    draw Projette((k/Profondeur)[Adg0,Adg1])--Projette((k/Profondeur)[Adg3,Adg2]);
    endfor;
    for k=1 upto Hauteur-1:
    draw Projette((k/Hauteur)[Adg0,Adg3])--Projette((k/Hauteur)[Adg1,Adg2]);
    endfor;
    fi;
    
    %draw (llcorner currentpicture)--(lrcorner currentpicture)--(urcorner currentpicture)--(ulcorner currentpicture)--cycle;
  \end{mplibcode}
  \ifboolKV[VueCubes]{Grilles}{}{%
    \hspace*{1.5cm}
    \begin{mplibcode}[\PfCVueCubeNom]
      input PfCSolid;
      
      intensite:=1.5;
      
      Ferme[0]:=false;
      outcolor:=\useKV[VueCubes]{CouleurCube};
      incolor:=white;
      nb:=1;subh:=1;
      creux:=true;
      
      Profondeur:=\useKV[VueCubes]{Profondeur};
      Largeur:=\useKV[VueCubes]{Largeur};
      Hauteur:=\useKV[VueCubes]{Hauteur};
      Phi:=#1;
      Echelle:=\useKV[VueCubes]{Echelle};
      
      color CouleurFleche;
      CouleurFleche:=\useKV[VueCubes]{CouleurFleche};
      
      TotalObj:=0;
      
      Initialisation(2500,Phi+90,30,50);
      Objetcube0("a="&decimal(Echelle));
      
      for m=1 upto Largeur:%3 largeur
      for k=1 upto Profondeur:%4 profondeur
      for l=1 upto hauteurtour[m][k]:
      TotalObj:=incr TotalObj;
      TR:=(-Echelle*(k-1),m*Echelle,Echelle*l-Echelle/2);%TR:=(-0.5*(k-1),m*0.5,l/2-0.25);
      ObjetDeplacement[TotalObj](0);
      endfor;
      endfor;
      endfor;
      
      if Grille:
      undraw Projette(Ad0) for k=1 upto 3: --Projette(Ad[k]) endfor --cycle;
      undraw Projette(Af0) for k=1 upto 3: --Projette(Af[k]) endfor --cycle;
      undraw Projette(Adg0) for k=1 upto 3: --Projette(Adg[k]) endfor --cycle;
      fi;
      
      path Fleche;
      if FaceVue:
      Fleche=Projette(A0)--Projette(A1)--Projette(A2)--Projette(A3)--Projette(A4)--Projette(A5)--Projette(A6)--cycle;
      fill Fleche withcolor CouleurFleche;
      draw Fleche;
      fi;
      
      nbobj:=TotalObj;
      DessineFusion;
    \end{mplibcode}
  }%
  \fi
}%

\NewDocumentCommand\BuildVueCubesSolution{}{%
  \ifluatex%
  \xdef\PfCVueCubeNom{\useKV[VueCubes]{Nom}}%
  \begin{NiceTabular}{ccc}%
    Vue de face&Vue de dessus&Vue de gauche\\
    {\begin{mplibcode}[\PfCVueCubeNom]
        input PfCSolid;
        
        intensite:=1.5;
        
        Ferme[0]:=false;
        outcolor:=\useKV[VueCubes]{CouleurCube};
        incolor:=white;
        nb:=1;subh:=1;
        creux:=true;
        
        Profondeur:=\useKV[VueCubes]{Profondeur};
        Largeur:=\useKV[VueCubes]{Largeur};
        Hauteur:=\useKV[VueCubes]{Hauteur};
        Phi:=0;
        Echelle:=\useKV[VueCubes]{Echelle};

        color CouleurFleche;
        CouleurFleche:=\useKV[VueCubes]{CouleurFleche};
        
        TotalObj:=0;
        
        Initialisation(2500,Phi,0,50);
        Objetcube0("a="&decimal(Echelle));
        
        for m=1 upto Largeur:%3 largeur
        for k=1 upto Profondeur:%4 profondeur
        for l=1 upto hauteurtour[m][k]:
        TotalObj:=incr TotalObj;
        TR:=(-Echelle*(k-1),m*Echelle,Echelle*l-Echelle/2);%TR:=(-0.5*(k-1),m*0.5,l/2-0.25);
        ObjetDeplacement[TotalObj](0);
        endfor;
        endfor;
        endfor;
        
        nbobj:=TotalObj;
        DessineFusion;
      \end{mplibcode}}&
    {\begin{mplibcode}[\PfCVueCubeNom]
    input PfCSolid;
    
    intensite:=1.5;
    
    Ferme[0]:=false;
    outcolor:=\useKV[VueCubes]{CouleurCube};
    incolor:=white;
    nb:=1;subh:=1;
    creux:=true;
    
    Profondeur:=\useKV[VueCubes]{Profondeur};
    Largeur:=\useKV[VueCubes]{Largeur};
    Hauteur:=\useKV[VueCubes]{Hauteur};
    Phi:=0;
    Echelle:=\useKV[VueCubes]{Echelle};

    color CouleurFleche;
    CouleurFleche:=\useKV[VueCubes]{CouleurFleche};
    
    TotalObj:=0;
    
    Initialisation(2500,Phi,90,50);
    Objetcube0("a="&decimal(Echelle));
    
    for m=1 upto Largeur:%3 largeur
    for k=1 upto Profondeur:%4 profondeur
    for l=1 upto hauteurtour[m][k]:
    TotalObj:=incr TotalObj;
    TR:=(-Echelle*(k-1),m*Echelle,Echelle*l-Echelle/2);%TR:=(-0.5*(k-1),m*0.5,l/2-0.25);
    ObjetDeplacement[TotalObj](0);
    endfor;
    endfor;
    endfor;

    nbobj:=TotalObj;
    DessineFusion;
  \end{mplibcode}}&{\begin{mplibcode}[\PfCVueCubeNom]
    input PfCSolid;
    
    intensite:=1.5;
    
    Ferme[0]:=false;
    outcolor:=\useKV[VueCubes]{CouleurCube};
    incolor:=white;
    nb:=1;subh:=1;
    creux:=true;
    
    Profondeur:=\useKV[VueCubes]{Profondeur};
    Largeur:=\useKV[VueCubes]{Largeur};
    Hauteur:=\useKV[VueCubes]{Hauteur};
    Phi:=-90;
    Echelle:=\useKV[VueCubes]{Echelle};

    color CouleurFleche;
    CouleurFleche:=\useKV[VueCubes]{CouleurFleche};
    
    TotalObj:=0;
    
    Initialisation(2500,Phi,0,50);
    Objetcube0("a="&decimal(Echelle));
    
    for m=1 upto Largeur:%3 largeur
    for k=1 upto Profondeur:%4 profondeur
    for l=1 upto hauteurtour[m][k]:
    TotalObj:=incr TotalObj;
    TR:=(-Echelle*(k-1),m*Echelle,Echelle*l-Echelle/2);%TR:=(-0.5*(k-1),m*0.5,l/2-0.25);
    ObjetDeplacement[TotalObj](0);
    endfor;
    endfor;
    endfor;

    nbobj:=TotalObj;
    DessineFusion;
  \end{mplibcode}}\\
  \end{NiceTabular}%
  \fi%
}%

%%%
% Codage RLE
%%%
\setKVdefault[RLE]{Largeur=10pt,Taille=5,Unite=1cm,Solution=false,Enonce=true}

\newtoks\toklisterle
\def\UpdatetoksRLE#1\nil{\addtotok\toklisterle{#1,}}%

%\newlength\PfCRLEHeight%
\NewDocumentCommand\CodageRLE{o m}{%
  \useKVdefault[RLE]%
  \setKV[RLE]{#1}%
  %\setlength{\PfCRLEHeight}{\useKV[RLE]{Largeur}}%
  \setsepchar{,}%
  \readlist*\PfCListeRLE{#2}%
  \toklisterle{}%
  \foreachitem\compteur\in\PfCListeRLE{\expandafter\UpdatetoksRLE\compteur\nil}%
  \BuildRLE{\the\toklisterle}%
}

\NewDocumentCommand\BuildRLE{m}{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    Taille:=\useKV[RLE]{Taille};
    u:=\useKV[RLE]{Unite};
    boolean Solution,Enonce;
    Solution:=\useKV[RLE]{Solution};
    Enonce:=\useKV[RLE]{Enonce};
    
    color RLEFill;
    RLEFill=white;

    numeric nbretenir[][];
    
    vardef NombreLigne(text t)=
    retiens:=0;
    nblignes:=0;
    for p_=t:
    retiens:=retiens+p_;
    if retiens=Taille:
    nblignes:=nblignes+1;
    retiens:=0;
    fi;
    endfor;
    enddef;

    path Square;
    Square=unitsquare scaled u;

    vardef RLE(text t)=
    nbcoups:=0;
    nbcases:=0;
    nbcaseslignes:=0;
    cptretiensnb:=0;
    cptretiensnblignes:=1;
    for p_=t:
    if p_=0:
    cptretiensnb:=cptretiensnb+1;
    nbretenir[cptretiensnblignes][cptretiensnb]=p_;
    RLEFill:=black;
    else:
    nbcoups:=nbcoups+1;
    for l=0 upto p_-1:
        if Solution: fill ((Square scaled 0.95) shifted(u*((nbcases mod Taille)+l,-(nbcases div Taille))+u*(0.025,0.025))) withcolor RLEFill; fi;
    trace (Square shifted(u*((nbcases mod Taille)+l,-(nbcases div Taille))));
    endfor;
    nbcaseslignes:=nbcaseslignes+p_;
    nbcases:=nbcases+p_;
    if (nbcaseslignes mod Taille)=0:
    RLEFill:=white;
    cptretiensnb:=cptretiensnb+1;
    nbretenir[cptretiensnblignes][cptretiensnb]=p_;
    cptretiensnblignes:=cptretiensnblignes+1;
    cptretiensnb:=0;
    else:
    if RLEFill=white: RLEFill:=black else: RLEFill:=white fi;
    cptretiensnb:=cptretiensnb+1;
    nbretenir[cptretiensnblignes][cptretiensnb]=p_;
    fi;
    fi;
    endfor;
    enddef;

    string Sequence[];

    boolean STOP;
    STOP:=false;
    
    vardef Affichage=
    for k=1 upto nblignes:
    Sequence[k]=decimal(nbretenir[k][1]);
    n:=1;
    forever:
    n:=n+1;
    if unknown nbretenir[k][n]:
    STOP:=true;
    else:
    Sequence[k]:=Sequence[k]&","&decimal(nbretenir[k][n]);
    fi;
    exitif STOP;
    endfor;
    label.rt(TEX(Sequence[k]),u*(Taille+1,-k+1+0.5));
    STOP:=false;
    endfor;
    enddef;
    
    NombreLigne(#1);
    RLE(#1);
    if Enonce:
    Affichage;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={%
    Taille:=\useKV[RLE]{Taille};
    u:=\useKV[RLE]{Unite};
    boolean Solution,Enonce;
    Solution:=\useKV[RLE]{Solution};
    Enonce:=\useKV[RLE]{Enonce};
    }]
    color RLEFill;
    RLEFill=white;

    numeric nbretenir[][];
    
    vardef NombreLigne(text t)=
    retiens:=0;
    nblignes:=0;
    for p_=t:
    retiens:=retiens+p_;
    if retiens=Taille:
    nblignes:=nblignes+1;
    retiens:=0;
    fi;
    endfor;
    enddef;

    path Square;
    Square=unitsquare scaled u;

    vardef RLE(text t)=
    nbcoups:=0;
    nbcases:=0;
    nbcaseslignes:=0;
    cptretiensnb:=0;
    cptretiensnblignes:=1;
    for p_=t:
    if p_=0:
    cptretiensnb:=cptretiensnb+1;
    nbretenir[cptretiensnblignes][cptretiensnb]=p_;
    RLEFill:=black;
    else:
    nbcoups:=nbcoups+1;
    for l=0 upto p_-1:
        if Solution: fill ((Square scaled 0.95) shifted(u*((nbcases mod Taille)+l,-(nbcases div Taille))+u*(0.025,0.025))) withcolor RLEFill; fi;
    trace (Square shifted(u*((nbcases mod Taille)+l,-(nbcases div Taille))));
    endfor;
    nbcaseslignes:=nbcaseslignes+p_;
    nbcases:=nbcases+p_;
    if (nbcaseslignes mod Taille)=0:
    RLEFill:=white;
    cptretiensnb:=cptretiensnb+1;
    nbretenir[cptretiensnblignes][cptretiensnb]=p_;
    cptretiensnblignes:=cptretiensnblignes+1;
    cptretiensnb:=0;
    else:
    if RLEFill=white: RLEFill:=black else: RLEFill:=white fi;
    cptretiensnb:=cptretiensnb+1;
    nbretenir[cptretiensnblignes][cptretiensnb]=p_;
    fi;
    fi;
    endfor;
    enddef;

    string Sequence[];

    boolean STOP;
    STOP:=false;
    
    vardef Affichage=
    for k=1 upto nblignes:
    Sequence[k]=decimal(nbretenir[k][1]);
    n:=1;
    forever:
    n:=n+1;
    if unknown nbretenir[k][n]:
    STOP:=true;
    else:
    Sequence[k]:=Sequence[k]&","&decimal(nbretenir[k][n]);
    fi;
    exitif STOP;
    endfor;
    label.rt(LATEX(Sequence[k]),u*(Taille+1,-k+1+0.5));
    STOP:=false;
    endfor;
    enddef;
    
    NombreLigne(#1);
    RLE(#1);
    if Enonce:
    Affichage;
    fi;    
  \end{mpost}
  \fi
}

%%%
% Engrenages
%%%
\newtoks\tokPfCEngrenages%
\def\UpdatetoksEngrenages#1/#2\nil{\addtotok\tokPfCEngrenages{#1,#2,}}%

\setKVdefault[Engrenages]{Couleur=LightSteelBlue,Unite=3mm}

\NewDocumentCommand\Engrenages{o m}{%
  \tokPfCEngrenages{}
  \useKVdefault[Engrenages]%
  \setKV[Engrenages]{#1}%
  \setsepchar[*]{,*/}%
  \ignoreemptyitems
  \readlist*\ListePfCEngrenages{#2}%
  \foreachitem\compteur\in\ListePfCEngrenages{\expandafter\UpdatetoksEngrenages\compteur\nil}%
  \BuildEngrenages{\the\tokPfCEngrenages}%
}%

\NewDocumentCommand\BuildEngrenages{m}{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCEngrenages;
    
    u:=\useKV[Engrenages]{Unite};
    CouleurEngrenage=\useKV[Engrenages]{Couleur};
    
    vardef LectureDonnees(text t)=
    n:=0;k=0;l=0;
    for p_=t:
    n:=n+1;
    if (n mod 2)=0:
    l:=l+1;
    Zz[l]=p_;
    else:
    k:=k+1;
    Mm[k]=p_;
    fi;
    endfor;
    enddef;
    
    LectureDonnees(#1);

    pair K;
    K=(0,0);

    trace Engrenage(Mm[1],Zz[1],(0,0));
    
    Signe=1;
    
    for w=2 upto (n div 2):
    K:=K+pointarc(cercles((0,0),u*Mm[w]*(Zz[w-1]+Zz[w])*0.5+0.04*u),0);
    AngleRot[w]:=360/(2*Zz[w]);
    if w=2:
    trace rotation(Engrenage(Mm[w],Zz[w],K),K,180-AngleRot[w]);
    if (Zz[w] mod 2)=0:
    Signe:=Signe*(-1);
    fi;
    else:
    if (Zz[w] mod 2)=1:
    if Signe=-1:
    trace rotation(Engrenage(Mm[w],Zz[w],K),K,180);
    else:
    trace rotation(Engrenage(Mm[w],Zz[w],K),K,180-AngleRot[w]);
    fi;
    else:
    Signe:=Signe*(-1);
    if Signe=1:
trace rotation(Engrenage(Mm[w],Zz[w],K),K,180);
    else:
trace rotation(Engrenage(Mm[w],Zz[w],K),K,180-AngleRot[w]);
    fi;
    fi;
    fi;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={input PfCEngrenages;u:=\useKV[Engrenages]{Unite};CouleurEngrenage=\useKV[Engrenages]{Couleur};}]
    vardef LectureDonnees(text t)=
    n:=0;k=0;l=0;
    for p_=t:
    n:=n+1;
    if (n mod 2)=0:
    l:=l+1;
    Zz[l]=p_;
    else:
    k:=k+1;
    Mm[k]=p_;
    fi;
    endfor;
    enddef;
    
    LectureDonnees(#1);

    pair K;
    K=(0,0);

    trace Engrenage(Mm[1],Zz[1],(0,0));
    
    Signe=1;
    
    for w=2 upto (n div 2):
    K:=K+pointarc(cercles((0,0),u*Mm[w]*(Zz[w-1]+Zz[w])*0.5+0.04*u),0);
    AngleRot[w]:=360/(2*Zz[w]);
    if w=2:
    trace rotation(Engrenage(Mm[w],Zz[w],K),K,180-AngleRot[w]);
    if (Zz[w] mod 2)=0:
    Signe:=Signe*(-1);
    fi;
    else:
    if (Zz[w] mod 2)=1:
    if Signe=-1:
    trace rotation(Engrenage(Mm[w],Zz[w],K),K,180);
    else:
    trace rotation(Engrenage(Mm[w],Zz[w],K),K,180-AngleRot[w]);
    fi;
    else:
    Signe:=Signe*(-1);
    if Signe=1:
trace rotation(Engrenage(Mm[w],Zz[w],K),K,180);
    else:
trace rotation(Engrenage(Mm[w],Zz[w],K),K,180-AngleRot[w]);
    fi;
    fi;
    fi;
    endfor;
  \end{mpost}
  \fi
}

%%%
% Tortue
%%%
\setKVdefault[Tortue]{%
  Pas=0.2mm,%Déplacement,
  Etapes=false,%Pour arrêter la construction à une étape particulière
  Nom=\jobname,%Pour la sauvegarde du fichier mp
  Grille=false,%Pour faire apparaître une grille
  LargeurG=10,%Largeur Grille
  HauteurG=10,%Hauteur Grille
  TortueD=false,%Affiche la tortue au départ
  TortueF=false,%Affiche la tortue à l'arrivée
  Epaisseur=1,%Epaisseur du tracé
  Angle=0,%Angle de départ de la tortue
  Debut=false,%Pour indiquer que rien n'est fait (utile ?)
  Depart={(0,0)},%Point de départ de la tortue
  Axes=false,%Affichage des axes ou pas
  Origine={(0,0)},%Origine des axes
  Cases=false,%Se déplace-t-on sur des cases ?
}
\defKV[Tortue]{Etape=\setKV[Tortue]{Etapes}}%choix de l'étape d'arrêt

\newcounter{PfCTortue}
\setcounter{PfCTortue}{0}

\makeatletter
\NewDocumentCommand\TortueCreationFichier{o m}{%
  \stepcounter{PfCTortue}%
  \useKVdefault[Tortue]%
  \setKV[Tortue]{#1}%
  \setKV[Tortue]{Nom=\jobname+t\thePfCTortue}%
  \setsepchar[*]{,* }%
  \readlist*\PfCListeCmdTortue{#2}%
  \setsepchar{,}%
  \xdef\PfCNbRep{0}%
  \savecomparemode%
  \newwrite\turtle@out%
  \immediate\openout\turtle@out \jobname+t\thePfCTortue.turtle%
  \immediate\write\turtle@out{%
    numeric ut;
    ut=\useKV[Tortue]{Pas};
    pair OrigineAxes;OrigineAxes=\useKV[Tortue]{Origine};
    Etapes=\useKV[Tortue]{Etapes};
    if Etapes:Total=\useKV[Tortue]{Etape};fi;
  }%
  \ifboolKV[Tortue]{Grille}{%
    \immediate\write\turtle@out{%
      larg=\useKV[Tortue]{LargeurG}; haut=\useKV[Tortue]{HauteurG};
      for k=-larg upto larg:
      draw 3*ut*(10k,-10haut)--3*ut*(10k,10haut) withcolor 0.75white;
      endfor;
      for k=-haut upto haut:
      draw 3*ut*(-10larg,10k)--3*ut*(10larg,10k) withcolor 0.75white;
      endfor;
      %dotlabel("",ut*OrigineAxes);
      if \useKV[Tortue]{Axes}:
      drawarrow (3*ut*(-10larg,0)--3*ut*(10larg,0)) shifted(ut*(0,ypart(OrigineAxes-(0,0))));
      drawarrow (3*ut*(0,-10haut)--3*ut*(0,10haut)) shifted(ut*(xpart(OrigineAxes-(0,0)),0));
      %label.llft(btex O etex,(0,0));
      dotlabel.lrt(btex 30 etex,(30*ut,0)+ut*(OrigineAxes-(0,0)));
      dotlabel.ulft(btex 30 etex,(0,30*ut)+ut*(OrigineAxes-(0,0)));
      fi;
      if \useKV[Tortue]{Cases}:
      string T[];
      T1="A";
      T2="B";
      T3="C";
      T4="D";
      T5="E";
      T6="F";
      T7="G";
      T8="H";
      T9="I";
      T10="J";
      T11="K";
      T12="L";
      T13="M";
      T14="N";
      T15="O";
      T16="P";
      T17="Q";
      T18="R";
      T19="S";
      T20="T";
      T21="U";
      T22="V";
      T23="W";
      T24="X";
      T25="Y";
      T26="Z";
      for k=-larg upto larg-1:
      label(TEX(T[k+larg+1]),3*ut*(10k+5,10haut+5));
      endfor;
      for k=haut downto -haut+1:
      label(TEX(decimal(haut-k+1)),3*ut*(-10larg-5,10k-5));
      endfor;
      fi;
      Epaisseur:=1.5;
    }%
  }{}%
  \ifboolKV[Tortue]{Debut}{}{%
    \foreachitem\compteur\in\PfCListeCmdTortue{%
      \comparestrict%
      \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{MP}[\PfCTestMP]%
      \xintifboolexpr{\PfCTestMP==0}{%
        \immediate\write\turtle@out{\PfCListeCmdTortue[\compteurcnt,2]}%
      }{%
        \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{[}[\PfCTestCrochetO]%
        \xintifboolexpr{\PfCTestCrochetO==0}{}{%
          \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{]}[\PfCTestCrochetF]%
          \xintifboolexpr{\PfCTestCrochetF==0}{%
            \immediate\write\turtle@out{TotalRemplis:=tt-1; remplis for l=1 upto TotalRemplis:B[l]--endfor cycle withcolor CouleurRemplis;}%
          }{%
            \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Remplis}[\PfCTestRemplis]%
            \xintifboolexpr{\PfCTestRemplis==0}{%
              \immediate\write\turtle@out{tt:=0;
                TotalRemplis:=0; CouleurRemplis:=\PfCListeCmdTortue[\compteurcnt,2];}%
            }{%
              \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Fin}[\PfCTestFinPour]%
              \xintifboolexpr{\PfCTestFinPour==0}{%
                \immediate\write\turtle@out{enddef;k:=0;}%
                \xdef\PfCNbRep{\fpeval{\PfCNbRep+1}}%
              }{%
                \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Pour}[\PfCTestPour]%
                \xintifboolexpr{\PfCTestPour==0}{%
                  \immediate\write\turtle@out{vardef \PfCListeCmdTortue[\compteurcnt,2](expr \PfCListeCmdTortue[\compteurcnt,3])=}%
                }{%
                  \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Rep}[\PfCTestRep]%
                  \xintifboolexpr{\PfCTestRep==0}{%
                    \xdef\PfCNbRep{\fpeval{\PfCNbRep+1}}%
                    \immediate\write\turtle@out{nb[\PfCNbRep]:=0;}%
                    \immediate\write\turtle@out{forever:}%
                    \immediate\write\turtle@out{nb[\PfCNbRep]:=nb[\PfCNbRep]+1;}%
                    % \immediate\write\turtle@out{nbcomp:=nbcomp+1;}
                  }{%
                    \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{)}[\PfCTestParaF]%
                    \xintifboolexpr{\PfCTestParaF==0}{%
                      \immediate\write\turtle@out{exitif nb[\PfCNbRep]=\PfCListeCmdTortue[\compteurcnt,2];}%
                      \immediate\write\turtle@out{endfor;}%
                      \xdef\PfCNbRep{\fpeval{\PfCNbRep-1}}%
                    }{%
                      \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{(}[\PfCTestParaO]%
                      \xintifboolexpr{\PfCTestParaO==0}{%
                      }{%
                        \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Bc}[\PfCTestBc]%
                        \xintifboolexpr{\PfCTestBc==0}{%
                          \immediate\write\turtle@out{Bc;}%
                        }{%
                          \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Lc}[\PfCTestLc]%
                          \xintifboolexpr{\PfCTestLc==0}{%
                            \immediate\write\turtle@out{Lc;}%
                          }{%
                            \StrCompare{\PfCListeCmdTortue[\compteurcnt,1]}{Tlp}[\PfCTestTlp]%
                            \xintifboolexpr{\PfCTestTlp==0}{%
                              \immediate\write\turtle@out{Teleporter(\PfCListeCmdTortue[\compteurcnt,2],\PfCListeCmdTortue[\compteurcnt,3]);}%
                            }{%
                              \immediate\write\turtle@out{\PfCListeCmdTortue[\compteurcnt,1](\PfCListeCmdTortue[\compteurcnt,2]);}%
                            }%
                          }%
                        }%
                      }%
                    }%
                  }%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
  % \immediate\write\turtle@out{Tortue:=currentpicture;Tortue enddef;}%
  % \immediate\write\turtle@out{draw Dessin;}%
  \ifboolKV[Tortue]{TortueD}{%
    \immediate\write\turtle@out{drawoptions(withcolor DarkGreen);label(btex \noexpand\Large\noexpand\ding{40} etex rotated RetiensAngle[0] scaled 1.5,A[0]);}%
  }{}%
  \ifboolKV[Tortue]{Etapes}{%
    \immediate\write\turtle@out{drawoptions(withcolor DarkGreen);label(btex \noexpand\Large\noexpand\ding{40} etex rotated RetiensAngle[Total] scaled 1.5,A[Total]);}%
  }{\ifboolKV[Tortue]{TortueF}{\immediate\write\turtle@out{drawoptions(withcolor DarkGreen);label(btex \noexpand\Large\noexpand\ding{40} etex rotated RetiensAngle[k] scaled 1.5,A[k]);}}{}}%
  \immediate\closeout\turtle@out%
  \restorecomparemode%
}%
\makeatother

\NewDocumentCommand\Tortue{o m}{%
  \useKVdefault[Tortue]%
  \setKV[Tortue]{#1}%
  \TortueCreationFichier[#1]{#2}%
  \TortueDessinFinal%
}

\NewDocumentCommand\TortueDessinFinal{}{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCTurtleTestRemplis.mp;

    pair Depart;
    Depart=\useKV[Tortue]{Depart} if \useKV[Tortue]{Cases}:+(15,15)fi;
    pair A[],B[];
    A[0]=\useKV[Tortue]{Pas}*(xpart(Depart),ypart(Depart));
    B[0]=A[0];
    Epaisseur:=\useKV[Tortue]{Epaisseur};
    Angle:=0;
    numeric RetiensAngle[];
    RetiensAngle[0]=\useKV[Tortue]{Angle};
    
    pair VecteurDpt;
    VecteurDpt=(1,0) rotated RetiensAngle[0];
    input \useKV[Tortue]{Nom}.turtle;
  \end{mplibcode}
  \else
  \fi
}%

%%%
% Le compte est bon
%%%
\setKVdefault[CompteBon]{NombreCalculs=5,NombrePlaques=4,Solution=false,Relatifs=false,Original=false,Graines=false,Plaques=6}
\defKV[CompteBon]{Graine=\setKV[CompteBon]{Graines}}%

\makeatletter

\newcommand\PfC@CreerListeCalculs[4]{%
  \xdef\PfC@ListeCalculs{%
    #1+#2+#3+#4,%
    #1+#2+#3*#4/#1+#3*#4+#2/#3*#4+#1+#2,%
    #1+#3+#2*#4/#1+#2*#4+#3/#2*#4+#1+#3,%
    #1+#4+#2*#3/#1+#2*#3+#4/#2*#3+#1+#4,%
    #2+#3+#1*#4/#2+#1*#4+#3/#1*#4+#2+#3,%
    #2+#4+#1*#3/#2+#1*#3+#4/#2+#4+#1*#3,%
    #3+#4+#1*#2/#3+#1*#2+#4/#3+#4+#1*#2,%
    #1*#2+#3*#4/#3*#4+#1*#2,%
    #1*#3+#2*#4/#2*#4+#1*#3,%
    #1*#4+#2*#3/#2*#3+#1*#4,%
    #1*#2*#3+#4/#4+#1*#2*#3,
    #1*#2*#4+#3/#3+#1*#2*#4,%
    #1*#3*#4+#2/#2+#1*#3*#4,%
    #2*#3*#4+#1/#1+#2*#3*#4,%
    #1*#2*#3*#4,%
    #1+(#2+#3)*#4/(#2+#3)*#4+#1/#1+#4*(#2+#3)/#4*(#2+#3)+#1,%
    #1+(#2+#4)*#3/(#2+#4)*#3+#1/#1+#3*(#2+#4)/#3*(#2+#4)+#1,%
    #1+(#3+#4)*#2/(#3+#4)*#2+#1/#1+#2*(#3+#4)/#2*(#3+#4)+#1,%
    #2+(#1+#3)*#4,%
    #2+(#1+#4)*#3,%
    #2+(#3+#4)*#1,%
    #3+(#1+#2)*#4,%
    #3+(#1+#4)*#2,%
    #3+(#2+#4)*#1,%
    #4+(#1+#2)*#3,%
    #4+(#1+#3)*#2,%
    #4+(#2+#3)*#1,%
    (#1+#2+#3)*#4,%
    (#1+#2+#4)*#3,%
    (#1+#3+#4)*#2,%
    (#2+#3+#4)*#1,%
    (#1+#2)*(#3+#4),%
    (#1+#3)*(#2+#4),%
    (#1+#4)*(#2+#3)%
  }%
  \ifboolKV[CompteBon]{Relatifs}{%
    \xdef\PfC@ListeCalculs{%
      \PfC@ListeCalculs,%
      #1-#2-#3-#4,%
      #1-#2-#3*#4/#1-#3*#4-#2/#3*#4-#1-#2,%
      #1-#3-#2*#4/#1-#2*#4-#3/#2*#4-#1-#3,%
      #1-#4-#2*#3/#1-#2*#3-#4/#2*#3-#1-#4,%
      #2-#3-#1*#4/#2-#1*#4-#3/#1*#4-#2-#3,%
      #2-#4-#1*#3/#2-#1*#3-#4/#2-#4-#1*#3,%
      #3-#4-#1*#2/#3-#1*#2-#4/#3-#4-#1*#2,%
      #1*#2-#3*#4/#3*#4-#1*#2,%
      #1*#3-#2*#4/#2*#4-#1*#3,%
      #1*#4-#2*#3/#2*#3-#1*#4,%
      #1*#2*#3-#4/#4-#1*#2*#3,
      #1*#2*#4-#3/#3-#1*#2*#4,%
      #1*#3*#4-#2/#2-#1*#3*#4,%
      #2*#3*#4-#1/#1-#2*#3*#4,%
      #1*#2*#3*#4,%
      #1-(#2-#3)*#4/(#2-#3)*#4-#1/#1-#4*(#2-#3)/#4*(#2-#3)-#1,%
      #1-(#2-#4)*#3/(#2-#4)*#3-#1/#1-#3*(#2-#4)/#3*(#2-#4)-#1,%
      #1-(#3-#4)*#2/(#3-#4)*#2-#1/#1-#2*(#3-#4)/#2*(#3-#4)-#1,%
      #2-(#1-#3)*#4,%
      #2-(#1-#4)*#3,%
      #2-(#3-#4)*#1,%
      #3-(#1-#2)*#4,%
      #3-(#1-#4)*#2,%
      #3-(#2-#4)*#1,%
      #4-(#1-#2)*#3,%
      #4-(#1-#3)*#2,%
      #4-(#2-#3)*#1,%
      (#1-#2-#3)*#4,%
      (#1-#2-#4)*#3,%
      (#1-#3-#4)*#2,%
      (#2-#3-#4)*#1,%
      (#1-#2)*(#3-#4),%
      (#1-#3)*(#2-#4),%
      (#1-#4)*(#2-#3)%
    }%
  }{}%
}%

\newtoks\tokPfCCBRappels
\def\UpdatetoksCB#1\nil{\addtotok\tokPfCCBRappels{#1,}}%

\NewDocumentCommand\PfCCompteBonOriginal{o}{%
  \useKVdefault[CompteBon]
  \setKV[CompteBon]{#1}%
  %On définit la liste des cartes
  \xdef\PfCCBListeCartes{1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,25,50,75,100}%
  \MelangeListe{\PfCCBListeCartes}{\useKV[CompteBon]{Plaques}}
  \readlist*\PfCCBListeTirage{\faa}
  \MelangeListe{\faa}{\useKV[CompteBon]{Plaques}}
  \readlist*\PfCCBListeTirageAffiche{\faa}
  %%Tirage ok
  \xdef\PfCCBResultatFinal{1001}%
  \whiledo{\PfCCBResultatFinal>1000}{%
    \xdef\PfCListeATrier{\PfCCBListeTirage[1]}%
    \xintFor* ##1 in{\xintSeq{2}{\useKV[CompteBon]{Plaques}}}\do{%
      \xdef\PfCListeATrier{\PfCListeATrier,\PfCCBListeTirage[##1]}%
    }%
    % 
    \tokPfCCBRappels{}%
    \xintFor* ##1 in{\xintSeq{1}{\fpeval{\useKV[CompteBon]{Plaques}-1}}}\do{%
      \MelangeListe{\PfCListeATrier}{2}
      \readlist*\PfCCBListeTirageIntermediaire{\faa}
      \xintifboolexpr{\PfCCBListeTirageIntermediaire[1]==1 || \PfCCBListeTirageIntermediaire[2]==1}{%
        % On ne fait pas de multiplication par 1
        \xdef\PfCCBAlea{\fpeval{randint(1,2)}}%
        \xintifboolexpr{\PfCCBAlea==1}{%
          \xdef\PfCCBTest{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]=\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}%
          \expandafter\UpdatetoksCB\PfCCBTest\nil%
          \xdef\PfCCBResultat{\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}
          \xintifboolexpr{\PfCCBResultat>10000}{\xintBreakFor\xdef\PfCCBResultat{10000}}{}%
        }{%
          \xintifboolexpr{\PfCCBListeTirageIntermediaire[1]==\PfCCBListeTirageIntermediaire[2]}{%
            \xdef\PfCCBTest{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]=\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}%
            \expandafter\UpdatetoksCB\PfCCBTest\nil%
            \xdef\PfCCBResultat{\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}
          }{%
            \xdef\PfCCBTest{\fpeval{max(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])}-\fpeval{min(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])}=\fpeval{max(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])-min(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])}}
            \expandafter\UpdatetoksCB\PfCCBTest\nil%
            \xdef\PfCCBResultat{\fpeval{abs(\PfCCBListeTirageIntermediaire[1]-\PfCCBListeTirageIntermediaire[2])}}
          }%
          \xintifboolexpr{\PfCCBResultat>10000}{\xintBreakFor\xdef\PfCCBResultat{10000}}{}%
        }%
        \xdef\PfCListeATrier{\fii,\PfCCBResultat}%
      }{%
        \xdef\PfCCBAlea{\fpeval{randint(1,3)}}%
        \xintifboolexpr{\PfCCBAlea==1}{%
          \xdef\PfCCBTest{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]=\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}%
          \expandafter\UpdatetoksCB\PfCCBTest\nil%
          \xdef\PfCCBResultat{\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}
          \xintifboolexpr{\PfCCBResultat>10000}{\xintBreakFor\xdef\PfCCBResultat{10000}}{}%
        }{%
          \xintifboolexpr{\PfCCBAlea==2}{%
            \xintifboolexpr{\PfCCBListeTirageIntermediaire[1]==\PfCCBListeTirageIntermediaire[2]}{%
              \xdef\PfCCBTest{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]=\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}%
              \expandafter\UpdatetoksCB\PfCCBTest\nil%
              \xdef\PfCCBResultat{\fpeval{\PfCCBListeTirageIntermediaire[1]+\PfCCBListeTirageIntermediaire[2]}}
            }{%
              \xdef\PfCCBTest{\fpeval{max(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])}-\fpeval{min(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])}=\fpeval{max(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])-min(\PfCCBListeTirageIntermediaire[1],\PfCCBListeTirageIntermediaire[2])}}
              \expandafter\UpdatetoksCB\PfCCBTest\nil%
              \xdef\PfCCBResultat{\fpeval{abs(\PfCCBListeTirageIntermediaire[1]-\PfCCBListeTirageIntermediaire[2])}}
            }%
            \xintifboolexpr{\PfCCBResultat>10000}{\xintBreakFor\xdef\PfCCBResultat{10000}}{}%
          }{%
            \xdef\PfCCBTest{\PfCCBListeTirageIntermediaire[1]*\PfCCBListeTirageIntermediaire[2]=\fpeval{\PfCCBListeTirageIntermediaire[1]*\PfCCBListeTirageIntermediaire[2]}}
            \expandafter\UpdatetoksCB\PfCCBTest\nil%
            \xdef\PfCCBResultat{\fpeval{\PfCCBListeTirageIntermediaire[1]*\PfCCBListeTirageIntermediaire[2]}}
            \xintifboolexpr{\PfCCBResultat>10000}{\xintBreakFor\xdef\PfCCBResultat{10000}}{}%
          }
        }%
        \xdef\PfCListeATrier{\fii,\PfCCBResultat}%
      }%
    }%
    \xintifboolexpr{\useKV[CompteBon]{Plaques}>5}{\xintifboolexpr{\PfCCBResultat<100}{\xdef\PfCCBResultat{1001}}{}}{}%
    \xdef\PfCCBResultatFinal{\PfCCBResultat}%
  }%
  \begin{center}
    \textbf{\PfCCBResultatFinal}
    
    \fbox{\PfCCBListeTirage[1]} \xintFor* ##1 in{\xintSeq{2}{\useKV[CompteBon]{Plaques}}}\do{\qquad \fbox{\PfCCBListeTirage[##1]}}%
  \end{center}
  \xdef\PfCCBListeRappels{\the\tokPfCCBRappels}
  \setsepchar[*]{,*=}\ignoreemptyitems
  \readlist*\PfCCBDecompositionEtapes{\PfCCBListeRappels}
  \reademptyitems
  \ifboolKV[CompteBon]{Solution}{%
    \begin{align*}
      \xintFor* ##1 in{\xintSeq{1}{\fpeval{\useKV[CompteBon]{Plaques}-1}}}\do{
      \StrSubstitute{\PfCCBDecompositionEtapes[##1,1]}{*}{\times}[\PfCCBAffiche]\PfCCBAffiche&=\PfCCBDecompositionEtapes[##1,2]\xintifForLast{\\}{}
      }
    \end{align*}
  }{}%
}%

\NewDocumentCommand\CompteBon{o}{%
  \useKVdefault[CompteBon]%
  \setKV[CompteBon]{#1}%
  \ifboolKV[CompteBon]{Graines}{\PfCGraineAlea{\useKV[CompteBon]{Graine}}}{}%
  \ifboolKV[CompteBon]{Original}{%
    \PfCCompteBonOriginal[#1]%
  }{%
    % on choisit NombrePlaques parmi la liste des nombres 1 à 9, 10/25/50/75/100, La moitié +1 devant appartenir à 1..9
    \xdef\PfCCBListeEntiers{2,3,4,5,6,7,8,9}%
    \xdef\PfCCBListeMultiples{10,25,50,75,100}%
    \xdef\PfCCBNbPlaqueEntiers{\fpeval{floor(\useKV[CompteBon]{NombrePlaques}/2)+1}}%
    \xdef\PfCCBNbPlaqueMultiples{\useKV[CompteBon]{NombrePlaques}-\PfCCBNbPlaqueEntiers}%
    \MelangeListe{\PfCCBListeEntiers}{\PfCCBNbPlaqueEntiers}%
    \setsepchar{,}%
    \ignoreemptyitems%
    \readlist*\PfCCBListeEntiersChoisis{\faa}%
    \MelangeListe{\PfCCBListeMultiples}{\PfCCBNbPlaqueMultiples}%
    \ignoreemptyitems%
    \readlist*\PfCCBListeMultiplesChoisis{\faa}%
    \reademptyitems%
    \xdef\PfCCBListeToutesCartes{}%
    \foreachitem\compteur\in\PfCCBListeEntiersChoisis{%
      \xdef\PfCCBListeToutesCartes{\PfCCBListeToutesCartes{},\PfCCBListeEntiersChoisis[\compteurcnt]}%
    }%
    \foreachitem\compteur\in\PfCCBListeMultiplesChoisis{%
      \xdef\PfCCBListeToutesCartes{\PfCCBListeToutesCartes{},\PfCCBListeMultiplesChoisis[\compteurcnt]}%
    }%
    \MelangeListe{\PfCCBListeToutesCartes}{4}%
    \readlist*\PfCCBListeFinaleCartes{\faa}%
    % Choix des calculs
    \xdef\PfC@CalculUn{\PfCCBListeFinaleCartes[1]}%
    \xdef\PfC@CalculDeux{\PfCCBListeFinaleCartes[2]}%
    \xdef\PfC@CalculTrois{\PfCCBListeFinaleCartes[3]}%
    \xdef\PfC@CalculQuatre{\PfCCBListeFinaleCartes[4]}%
    \PfC@CreerListeCalculs{\PfC@CalculUn}{\PfC@CalculDeux}{\PfC@CalculTrois}{\PfC@CalculQuatre}
    \MelangeListe{\PfC@ListeCalculs}{\useKV[CompteBon]{NombreCalculs}}%
    \setsepchar[*]{,*/}%
    \readlist*\PfC@ListeCalculsChoisis{\faa}%
    \begin{center}
      \setlength{\tabcolsep}{0.5\tabcolsep}
      % Le tableau des nombres
      \begin{NiceTabular}{m{20pt}m{10pt}m{20pt}m{10pt}m{20pt}m{10pt}m{20pt}}
        \Block[draw]{}{\PfCCBListeFinaleCartes[1]}&&\Block[draw]{}{\PfCCBListeFinaleCartes[2]}&&\Block[draw]{}{\PfCCBListeFinaleCartes[3]}&&\Block[draw]{}{\PfCCBListeFinaleCartes[4]}
      \end{NiceTabular}
      
      \bigskip
      
      % Le tableau des calculs%
      \begin{NiceTabular}{m{30pt}cccm{20pt}m{10pt}m{20pt}m{10pt}m{20pt}m{10pt}m{20pt}}
        \xintFor* ##1 in{\xintSeq{1}{\useKV[CompteBon]{NombreCalculs}}}\do{%
          \Block[draw]{}{\num{\fpeval{\PfC@ListeCalculsChoisis[##1,1]}}}&&$=$&&\Block[draw]{}{~}&\Block{}{~}&\Block[draw]{}{~}&\Block{}{~}&\Block[draw]{}{~}&\Block{}{~}&\Block[draw]{}{~}\\
          \ifboolKV[CompteBon]{Solution}{\Block{1-11}{\footnotesize Une solution : \StrSubstitute[0]{\PfC@ListeCalculsChoisis[##1,1]}{*}{\times}[\PfCEcritureCalcul]$\PfCEcritureCalcul$}}{}\\
        }%
      \end{NiceTabular}
    \end{center}
  }%
}%

%%%
% Nombre Astral
%%%
\setKVdefault[NombreAstral]{Solution=false,Graines=false,Echelle=1}
\defKV[NombreAstral]{Graine=\setKV[NombreAstral]{Graines}}%

\newtoks\toklisteNANombres%
\newtoks\toklisteNAMelange%
\def\UpdatetoksNANombres#1\nil{\addtotok\toklisteNANombres{"#1",}}%
\def\UpdatetoksNAMelange#1\nil{\addtotok\toklisteNAMelange{#1,}}%

\NewDocumentCommand\NombreAstral{o}{%
  \toklisteNANombres{}%
  \toklisteNAMelange{}%
  \useKVdefault[NombreAstral]%
  \setKV[NombreAstral]{#1}%
  \ifboolKV[NombreAstral]{Graines}{\PfCGraineAlea{\useKV[NombreAstral]{Graine}}}{}%
  \xdef\PfCNACible{\fpeval{2*randint(25,45)}}%
  \xdef\PfCNAListeNombres{}%
  \xintFor* ##1 in{\xintSeq{11}{\fpeval{floor(\PfCNACible/3)}}}\do{%
    \xdef\PfCNAListeNombres{\PfCNAListeNombres ##1,}%
  }%
  \MelangeListe{\PfCNAListeNombres}{5}%
  \setsepchar{,}\ignoreemptyitems%
  \readlist*\PfCNAListeNombresBase{\faa}%
  \reademptyitems
  \readlist*\PfCNAListeNombres{%
    \PfCNAListeNombresBase[1],%
    \PfCNAListeNombresBase[2],%
    \fpeval{0.5*\PfCNACible+\PfCNAListeNombresBase[5]-\PfCNAListeNombresBase[4]-\PfCNAListeNombresBase[3]},%
    \fpeval{0.5*\PfCNACible+\PfCNAListeNombresBase[4]-\PfCNAListeNombresBase[2]-\PfCNAListeNombresBase[5]},%
    \PfCNAListeNombresBase[3],%
    \fpeval{0.5*\PfCNACible+\PfCNAListeNombresBase[3]-\PfCNAListeNombresBase[5]-\PfCNAListeNombresBase[1]},%
    \fpeval{0.5*\PfCNACible+\PfCNAListeNombresBase[2]-\PfCNAListeNombresBase[4]-\PfCNAListeNombresBase[1]},%
    \fpeval{0.5*\PfCNACible+\PfCNAListeNombresBase[1]-\PfCNAListeNombresBase[2]-\PfCNAListeNombresBase[3]},%
    \PfCNAListeNombresBase[4],%
    \PfCNAListeNombresBase[5]%
  }%
  \foreachitem\compteur\in\PfCNAListeNombres{\expandafter\UpdatetoksNANombres\compteur\nil}%
  \xdef\PfCNAListeAEffacer{1,2,3,4,5,6,7,8,9,10}%
  \MelangeListe{\PfCNAListeAEffacer}{6}%
  \ignoreemptyitems%
  \readlist*\PfCNAListeMelange{\faa}%
  \reademptyitems%
  \foreachitem\compteur\in\PfCNAListeMelange{\expandafter\UpdatetoksNAMelange\compteur\nil}%
  \BuildNombreAstral{\the\toklisteNANombres}{\the\toklisteNAMelange}%
}%

\NewDocumentCommand\BuildNombreAstral{m m}{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    Cible=\PfCNACible;
    
    boolean Solution;
    Solution:=\useKV[NombreAstral]{Solution};

    Echelle:=\useKV[NombreAstral]{Echelle};
    
    string Rappel[];
    Rayon:=4cm;
    
    path cc,ca[];
    cc=cercles((0,0),Rayon);
    
    pair A[],C[],D[];
    for k=1 upto 5:
    C[k]=pointarc(cc,90+(k-1)*72);
    endfor;
    
    D1=C2+30*unitvector(C2-C4);
    D2=C2+30*unitvector(C2-C5);
    D3=C3+30*unitvector(C3-C1);
    D4=C4+30*unitvector(C4-C1);
    D5=C5+30*unitvector(C5-C3);
    
    drawarrow C2--D1;
    drawarrow C2--D2;
    drawarrow C3--D3;
    drawarrow C4--D4;
    drawarrow C5--D5;
    
    label.ulft(TEX("\bfseries\Large"&decimal(Cible)),D1);
    label.lft(TEX("\bfseries\Large"&decimal(Cible)),D2);
    label.llft(TEX("\bfseries\Large"&decimal(Cible)),D3);
    label.lrt(TEX("\bfseries\Large"&decimal(Cible)),D4);
    label.urt(TEX("\bfseries\Large"&decimal(Cible)),D5);
    
    trace polygone(C1,C3,C5,C2,C4) withpen (pencircle scaled 8);
    A1=C1;
    A2=C2;
    A9=C3;
    A10=C4;
    A5=C5;
    A3=segment(C1,C3) intersectionpoint segment(C2,C5);
    A4=segment(C1,C4) intersectionpoint segment(C2,C5);
    A6=segment(C1,C3) intersectionpoint segment(C2,C4);
    A7=segment(C1,C4) intersectionpoint segment(C3,C5);
    A8=segment(C2,C4) intersectionpoint segment(C3,C5);
    for k=1 upto 10:
    ca[k]=cercles(A[k],0.6u);
    fill ca[k] withcolor white;
    trace ca[k];
    endfor;
    vardef Affichage(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    Rappel[n]=p_;
    label(TEX("\Large"&p_),A[n]);
    endfor;
    enddef;
    
    vardef Suppression(text t)=
    k:=0;
    for p_=t:
    k:=k+1;
    fill ca[p_] withcolor white;
    trace ca[p_];
    label(TEX("\Large"&Rappel[p_]),u*(-7,5.6-1.5k));
    trace cercles(u*(-7,5.6-1.5k),0.6u);
    endfor;
    enddef;
    
    Affichage(#1);
    if Solution=false:
    Suppression(#2);
    fi;
    picture recap;%
    recap:=currentpicture scaled Echelle;%
    currentpicture:=nullpicture;%
    draw recap;%
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={%
      Echelle:=\useKV[NombreAstral]{Echelle};
      Cible=\PfCNACible;boolean Solution;Solution:=\useKV[NombreAstral]{Solution};
      string Rappel[];
      n:=0;
      for p_=#1:
      n:=n+1;
      Rappel[n]=p_;
      endfor;
    }]
    
    Rayon:=4cm;
    
    path cc,ca[];
    cc=cercles((0,0),Rayon);
    
    pair A[],C[],D[];
    for k=1 upto 5:
    C[k]=pointarc(cc,90+(k-1)*72);
    endfor;
    
    D1=C2+30*unitvector(C2-C4);
    D2=C2+30*unitvector(C2-C5);
    D3=C3+30*unitvector(C3-C1);
    D4=C4+30*unitvector(C4-C1);
    D5=C5+30*unitvector(C5-C3);
    
    drawarrow C2--D1;
    drawarrow C2--D2;
    drawarrow C3--D3;
    drawarrow C4--D4;
    drawarrow C5--D5;
    
    label.ulft(LATEX("\noexpand\bfseries\noexpand\Large"&decimal(Cible)&""),D1);
    label.lft(LATEX("\noexpand\bfseries\noexpand\Large"&decimal(Cible)),D2);
    label.llft(LATEX("\noexpand\bfseries\noexpand\Large"&decimal(Cible)),D3);
    label.lrt(LATEX("\noexpand\bfseries\noexpand\Large"&decimal(Cible)),D4);
    label.urt(LATEX("\noexpand\bfseries\noexpand\Large"&decimal(Cible)),D5);
    
    trace polygone(C1,C3,C5,C2,C4) withpen (pencircle scaled 8);
    A1=C1;
    A2=C2;
    A9=C3;
    A10=C4;
    A5=C5;
    A3=segment(C1,C3) intersectionpoint segment(C2,C5);
    A4=segment(C1,C4) intersectionpoint segment(C2,C5);
    A6=segment(C1,C3) intersectionpoint segment(C2,C4);
    A7=segment(C1,C4) intersectionpoint segment(C3,C5);
    A8=segment(C2,C4) intersectionpoint segment(C3,C5);
    for k=1 upto 10:
    ca[k]=cercles(A[k],0.6u);
    fill ca[k] withcolor white;
    trace ca[k];
    endfor;
    vardef Affichage(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    label(LATEX("\noexpand\Large"&Rappel[n]),A[n]);
    endfor;
    enddef;
    
    vardef Suppression(text t)=
    k:=0;
    for p_=t:
    k:=k+1;
    fill ca[p_] withcolor white;
    trace ca[p_];
    label(LATEX("\noexpand\Large"&Rappel[p_]),u*(-7,5.6-1.5k));
    trace cercles(u*(-7,5.6-1.5k),0.6u);
    endfor;
    enddef;

    Affichage(#1);
    if Solution=false:
    Suppression(#2);
    fi;

    picture recap;%
    recap:=currentpicture scaled Echelle;%
    currentpicture:=nullpicture;%
    draw recap;%
  \end{mpost}
  \fi
}%

%%%
% Mentalo
%%%
\NewDocumentCommand\PfCNum{m}{%
  \xintifboolexpr{#1<0}{(\num{#1})}{\num{#1}}%
}%

\setKVdefault[Mentalo]{Questions=10,ValeurMin=1,ValeurMax=15}

\NewDocumentCommand\Mentalo{o m}{%
  \useKVdefault[Mentalo]%
  \setKV[Mentalo]{#1}%
  \xdef\PfCMentaloEtages{\fpeval{\useKV[Mentalo]{Questions}+1}}
  \setsepchar{,}\ignoreemptyitems%
  \readlist*\PfCMentaloListeOperations{#2}%
  \reademptyitems%
  \setlength{\tabcolsep}{0.25\tabcolsep}
  \renewcommand{\arraystretch}{1.5}
  \begin{NiceTabular}{*{\fpeval{\PfCMentaloEtages}}{m{5pt}}m{20pt}cm{20pt}cl*{\fpeval{\PfCMentaloEtages}}{m{5pt}}*{5}{m{15pt}}*{1}{m{10pt}}}
    \Block{1-\fpeval{\PfCMentaloEtages}}{~}\xintFor* ##2 in{\xintSeq{1}{\fpeval{\PfCMentaloEtages}}}\do{&}%
    \Block[draw,fill=gray!15]{1-5}{Arrivée}&&&&&\Block{1-\fpeval{\PfCMentaloEtages}}{~}\xintFor* ##2 in{\xintSeq{1}{\fpeval{\PfCMentaloEtages}}}\do{&}\\
    \xintFor* ##1 in{\xintSeq{1}{\fpeval{\PfCMentaloEtages-1}}}\do{%
      \Block{1-\fpeval{\PfCMentaloEtages-##1}}{~}\xintFor* ##2 in{\xintSeq{1}{\fpeval{\PfCMentaloEtages-##1}}}\do{&}%
      \Block[borders={top,left,bottom}]{1-\fpeval{##1}}{~}\xintFor* ##2 in{\xintSeq{1}{\fpeval{##1}}}\do{&}%
      \Block[borders={top,bottom}]{1-1}{%
        \xdef\PfCMentaloPremierTerme{\fpeval{randint(\useKV[Mentalo]{ValeurMin},\useKV[Mentalo]{ValeurMax})}}%
        \num{\PfCMentaloPremierTerme}}&\Block[borders={top,bottom}]{1-1}{%
        \xintifboolexpr{\PfCMentaloListeOperationslen==1}{%
          \StrSubstitute{\PfCMentaloListeOperations[1]}{*}{\times}[\PfCCBAffiche]$\PfCCBAffiche$%
        }{%
          \StrSubstitute{\PfCMentaloListeOperations[##1]}{*}{\times}[\PfCCBAffiche]$\PfCCBAffiche$%
        }%
      }&%
      \Block[borders={top,bottom}]{1-1}{\xdef\PfCMentaloDeuxiemeTerme{\fpeval{randint(\useKV[Mentalo]{ValeurMin},\useKV[Mentalo]{ValeurMax})}}%
        \PfCNum{\PfCMentaloDeuxiemeTerme}}&\Block[borders={top,bottom}]{1-1}{$=$}&\Block[borders={top,bottom}]{1-1}{\pointilles[20pt]}&%
      \Block[borders={top,right,bottom}]{1-\fpeval{##1}}{~}\xintFor* ##2 in{\xintSeq{1}{\fpeval{##1}}}\do{&}%
      \Block{1-\fpeval{\PfCMentaloEtages-##1}}{~}\xintFor* ##2 in{\xintSeq{1}{\fpeval{\PfCMentaloEtages-##1}}}\do{&}%
      &&&&\Block{1-2}{%
        \xintifboolexpr{\PfCMentaloListeOperationslen==1}{%
          \num{\fpeval{\PfCMentaloPremierTerme\PfCMentaloListeOperations[1]\PfCMentaloDeuxiemeTerme}}
        }{%
          \num{\fpeval{\PfCMentaloPremierTerme\PfCMentaloListeOperations[##1]\PfCMentaloDeuxiemeTerme}}
        }%
      }&\\
    }%
    \Block[draw,fill=gray!15]{1-\fpeval{2*\PfCMentaloEtages+5}}{Départ}\xintFor* ##2 in{\xintSeq{1}{\fpeval{2*\PfCMentaloEtages+5}}}\do{&}\\%
    \CodeAfter
    \tikz\draw[dashed] (1-|\fpeval{5+5+2+2*\PfCMentaloEtages-2})--(last-|\fpeval{5+5+2+2*\PfCMentaloEtages-2});
  \end{NiceTabular}
}%

%%%
% Calculs Croises
%%%
\setKVdefault[CalculsCroises]{Largeur=20pt,Solution=false,Inverse=false,Creation=false,Graines=false,Vide=false,Couleur=LightGray,Negatifs=false,Aide=false}
\defKV[CalculsCroises]{Graine=\setKV[CalculsCroises]{Graines}}%
\defKV[CalculsCroises]{ListeNombres=\setKV[CalculsCroises]{Aide}}%

\newlength\PfCCalculsCroises%
\NewDocumentCommand\CalculsCroises{o m}{%
  \useKVdefault[CalculsCroises]%
  \savecomparemode%
  \comparestrict%
  \setKV[CalculsCroises]{#1}%
  \colorlet{PfCCouleurCC}{\useKV[CalculsCroises]{Couleur}}%
  \setlength{\PfCCalculsCroises}{\useKV[CalculsCroises]{Largeur}+\tabcolsep}%
  \ifboolKV[CalculsCroises]{Inverse}{\setKV[CalculsCroises]{Solution}}{}%
  \ifboolKV[CalculsCroises]{Creation}{%
    \ifboolKV[CalculsCroises]{Graines}{\PfCGraineAlea{\useKV[CalculsCroises]{Graine}}}{}%
    \ifboolKV[CalculsCroises]{Negatifs}{%
      \xdef\PfCCCFoo{-1,-2,-3,-4,-5,-6,-7,-8,-9}%
    }{%
      \xdef\PfCCCFoo{1,2,3,4,5,6,7,8,9}%
    }%
    \MelangeListe{\PfCCCFoo}{9}%
    \setsepchar{,}%
    \readlist*\PfCListeCCNb{\faa}%
    \readlist*\PfCListeCCOp{#2}%
    \xdef\PfCCCfoo{\useKV[CalculsCroises]{ListeNombres}}%
    \readlist*\PfCListeCCAide{\PfCCCfoo}%
    \begin{NiceTabular}{*{6}{m{\useKV[CalculsCroises]{Largeur}}}}
      \rule{0pt}{\PfCCalculsCroises}\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[1]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[1]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[1]}}{}%
            }%
          }{}%
        }}&\StrCompare{\PfCListeCCOp[1]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[1]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[2]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[2]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[2]}}{}%
            }%
          }{}%
        }}&\StrCompare{\PfCListeCCOp[2]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[2]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[3]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[3]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[3]}}{}%
            }%
          }{}%
        }}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCNb[1]\PfCListeCCOp[1]\PfCListeCCNb[2]\PfCListeCCOp[2]\PfCListeCCNb[3]}}}}\\
      \rule{0pt}{\PfCCalculsCroises}\StrCompare{\PfCListeCCOp[3]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[3]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[4]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[4]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[5]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[5]$}}\\
      \rule{0pt}{\PfCCalculsCroises}\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[4]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[4]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[4]}}{}%
            }%
          }{}%
        }}&\StrCompare{\PfCListeCCOp[6]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[6]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[5]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[5]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[5]}}{}%
            }%
          }{}%
        }}&\StrCompare{\PfCListeCCOp[7]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[7]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[6]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[6]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[6]}}{}%
            }%
          }{}%
        }}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCNb[4]\PfCListeCCOp[6]\PfCListeCCNb[5]\PfCListeCCOp[7]\PfCListeCCNb[6]}}}}\\
      \rule{0pt}{\PfCCalculsCroises}\StrCompare{\PfCListeCCOp[8]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[8]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[9]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[9]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[10]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[10]$}}\\
      \rule{0pt}{\PfCCalculsCroises}\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[7]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[7]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[7]}}{}%
            }%
          }{}%
        }}&\StrCompare{\PfCListeCCOp[11]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[11]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[8]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[8]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[8]}}{}%
            }%
          }{}%
        }}&\StrCompare{\PfCListeCCOp[12]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[12]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCNb[9]}}{%
          \ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCNb[9]==\PfCListeCCAide[##1]}{\num{\PfCListeCCNb[9]}}{}%
            }%
          }{}%
        }}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCNb[7]\PfCListeCCOp[11]\PfCListeCCNb[8]\PfCListeCCOp[12]\PfCListeCCNb[9]}}}}\\
      \rule{0pt}{\PfCCalculsCroises}\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCNb[1]\PfCListeCCOp[3]\PfCListeCCNb[4]\PfCListeCCOp[8]\PfCListeCCNb[7]}}}}&&\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCNb[2]\PfCListeCCOp[4]\PfCListeCCNb[5]\PfCListeCCOp[9]\PfCListeCCNb[8]}}}}&&\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCNb[3]\PfCListeCCOp[5]\PfCListeCCNb[6]\PfCListeCCOp[10]\PfCListeCCNb[9]}}}}\\
      \CodeAfter
      \tikz\draw (1-|1) rectangle (6-|6);
      \xintFor* ##1 in{\xintSeq{2}{5}}\do{%
        \tikz\draw (1-|##1) -- (6-|##1);
      }%
      \xintFor* ##1 in{\xintSeq{2}{5}}\do{%
        \tikz\draw (##1-|1) -- (##1-|6);
      }%
    \end{NiceTabular}
  }{%
    \ifboolKV[CalculsCroises]{Vide}{%
      \begin{NiceTabular}{*{6}{m{\useKV[CalculsCroises]{Largeur}}}}
        \rule{0pt}{\PfCCalculsCroises}\Block{}{}&\Block{}{}&\Block{}{}&\Block{}{}&\Block{}{}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{}\\
        \rule{0pt}{\PfCCalculsCroises}\Block{}{}&\Block[fill=black]{}{}&\Block{}{}&\Block[fill=black]{}{}&\Block{}{}\\
        \rule{0pt}{\PfCCalculsCroises}\Block{}{}&\Block{}{}&\Block{}{}&\Block{}{}&\Block{}{}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{}\\
        \rule{0pt}{\PfCCalculsCroises}\Block{}{}&\Block[fill=black]{}{}&\Block{}{}&\Block[fill=black]{}{}&\Block{}{}\\
        \rule{0pt}{\PfCCalculsCroises}\Block{}{}&\Block{}{}&\Block{}{}&\Block{}{}&\Block{}{}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{}\\
        \rule{0pt}{\PfCCalculsCroises}\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{}&&\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{}&&\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{}\\
        \CodeAfter
        \tikz\draw (1-|1) rectangle (6-|6);
        \xintFor* ##1 in{\xintSeq{2}{5}}\do{%
          \tikz\draw (1-|##1) -- (6-|##1);
        }%
        \xintFor* ##1 in{\xintSeq{2}{5}}\do{%
          \tikz\draw (##1-|1) -- (##1-|6);
        }%
      \end{NiceTabular}        
    }{%
      \readlist*\PfCListeCCOp{#2}%
      \xdef\PfCCCfoo{\useKV[CalculsCroises]{ListeNombres}}%
      \readlist*\PfCListeCCAide{\PfCCCfoo}%
      \begin{NiceTabular}{*{6}{m{\useKV[CalculsCroises]{Largeur}}}}
        \rule{0pt}{\PfCCalculsCroises}\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[1]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[1]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[1]}}{}%
            }%
          }{}%
}}&\StrCompare{\PfCListeCCOp[2]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[2]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[3]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[3]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[3]}}{}%
            }%
          }{}%
}}&\StrCompare{\PfCListeCCOp[4]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[4]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[5]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[5]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[5]}}{}%
            }%
          }{}%
}}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCOp[1]\PfCListeCCOp[2]\PfCListeCCOp[3]\PfCListeCCOp[4]\PfCListeCCOp[5]}}}}\\
        \rule{0pt}{\PfCCalculsCroises}\StrCompare{\PfCListeCCOp[6]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[6]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[7]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[7]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[8]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[8]$}}\\
        \rule{0pt}{\PfCCalculsCroises}\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[9]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[9]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[9]}}{}%
            }%
          }{}%
}}&\StrCompare{\PfCListeCCOp[10]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[10]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[11]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[11]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[11]}}{}%
            }%
          }{}%
}}&\StrCompare{\PfCListeCCOp[12]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[12]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[13]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[13]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[13]}}{}%
            }%
          }{}%
}}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCOp[9]\PfCListeCCOp[10]\PfCListeCCOp[11]\PfCListeCCOp[12]\PfCListeCCOp[13]}}}}\\
        \rule{0pt}{\PfCCalculsCroises}\StrCompare{\PfCListeCCOp[14]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[14]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[15]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[15]$}}&\Block[fill=black]{}{~}&\StrCompare{\PfCListeCCOp[16]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[16]$}}\\
        \rule{0pt}{\PfCCalculsCroises}\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[17]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[17]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[17]}}{}%
            }%
          }{}%
}}&\StrCompare{\PfCListeCCOp[18]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[18]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[19]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[19]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[19]}}{}%
            }%
          }{}%
}}&\StrCompare{\PfCListeCCOp[20]}{*}[\PfCTestEtoile]\Block{}{\xintifboolexpr{\PfCTestEtoile==0}{$\times$}{$\PfCListeCCOp[20]$}}&\Block{}{\ifboolKV[CalculsCroises]{Solution}{\num{\PfCListeCCOp[21]}}{\ifboolKV[CalculsCroises]{Aide}{%
            \xintFor* ##1 in{\xintSeq{1}{\PfCListeCCAidelen}}\do{%
              \xintifboolexpr{\PfCListeCCOp[21]==\PfCListeCCAide[##1]}{\num{\PfCListeCCOp[21]}}{}%
            }%
          }{}%
}}&\Block[borders={bottom,right,top},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCOp[17]\PfCListeCCOp[18]\PfCListeCCOp[19]\PfCListeCCOp[20]\PfCListeCCOp[21]}}}}\\
        \rule{0pt}{\PfCCalculsCroises}\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCOp[1]\PfCListeCCOp[6]\PfCListeCCOp[9]\PfCListeCCOp[14]\PfCListeCCOp[17]}}}}&&\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCOp[3]\PfCListeCCOp[7]\PfCListeCCOp[11]\PfCListeCCOp[15]\PfCListeCCOp[19]}}}}&&\Block[borders={left,bottom,right},fill=PfCCouleurCC]{}{\ifboolKV[CalculsCroises]{Inverse}{}{\num{\fpeval{\PfCListeCCOp[5]\PfCListeCCOp[8]\PfCListeCCOp[13]\PfCListeCCOp[16]\PfCListeCCOp[21]}}}}\\
        \CodeAfter
        \tikz\draw (1-|1) rectangle (6-|6);
        \xintFor* ##1 in{\xintSeq{2}{5}}\do{%
          \tikz\draw (1-|##1) -- (6-|##1);
        }%
        \xintFor* ##1 in{\xintSeq{2}{5}}\do{%
          \tikz\draw (##1-|1) -- (##1-|6);
        }%
      \end{NiceTabular}
    }%
  }%
  \restorecomparemode%
}%

%%%
% Shikaku
%%%
\newcounter{PfCShikakuNom}
\setcounter{PfCShikakuNom}{0}

\setKVdefault[Shikaku]{Couleur=Purple,Taille=4,Largeur=2em,Solution=false,CodeAfter={},Creation=false,TailleHor=10,TailleVer=10,TailleHorMax=5,TailleVerMax=5,Nom=Shikaku\PfCShikakuNom}

\newlength\PfCShikakuh
\newlength\PfCShikakuv

\NewDocumentCommand\Shikaku{o m}{%
  \stepcounter{PfCShikakuNom}%
  \useKVdefault[Shikaku]%
  \setKV[Shikaku]{#1}%
  \ifboolKV[Shikaku]{Creation}{%
    \ifluatex\else\PackageWarning{ProfCollege}{La création automatique de Shikaku n'est disponible qu'avec LuaLaTeX.}\fi%
    \ifboolKV[Shikaku]{Solution}{%
      \ShikakuCreationSolution%
    }{%
      \ShikakuCreation%
    }%
  }{%
    \setlength{\PfCShikakuv}{\useKV[Shikaku]{Largeur}+\tabcolsep}%
    \setlength{\PfCShikakuh}{\useKV[Shikaku]{Largeur}}%
    \colorlet{PfCCouleurShikaku}{\useKV[Shikaku]{Couleur}}%
    \setsepchar[*]{,*/}%
    \readlist*\ListeCasesSKK{#2}%
    \savecomparemode%
    \comparestrict%
    \begin{NiceTabular}{*{\useKV[Shikaku]{Taille}}{m{\PfCShikakuh}}}[hvlines]
      \xintFor* ##1 in {\xintSeq{0}{\fpeval{\useKV[Shikaku]{Taille}-1}}}\do{%
        \xintFor* ##2 in {\xintSeq{1}{\useKV[Shikaku]{Taille}}}\do{%
          \rule{0pt}{\PfCShikakuv}%
          \StrCompare{\ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},1]}{b}[\PfCTestb]%
          \StrCompare{\ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},1]}{l}[\PfCTestl]%
          \StrCompare{\ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},1]}{lb}[\PfCTestlb]%
          \xintifboolexpr{\PfCTestb==0}{%
            \ifboolKV[Shikaku]{Solution}{%
              \Block[borders={bottom,tikz=PfCCouleurShikaku},line-width=2pt]{1-1}{%
                \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
              }%
            }{%
              \Block[]{1-1}{%
                \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
              }%
            }%
          }{% Testl
            \xintifboolexpr{\PfCTestl==0}{%
              \ifboolKV[Shikaku]{Solution}{%
                \Block[borders={left,tikz=PfCCouleurShikaku},line-width=2pt]{1-1}{%
                  \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
                }%
              }{%
                \Block[]{1-1}{%
                  \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
                }%
              }%
            }{% Testlb
              \xintifboolexpr{\PfCTestlb==0}{%
                \ifboolKV[Shikaku]{Solution}{%
                  \Block[borders={left,bottom,tikz=PfCCouleurShikaku},line-width=2pt]{1-1}{%
                    \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
                  }%
                }{%
                  \Block[]{1-1}{%
                    \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
                  }%
                }%
              }{%
                \Block[]{1-1}{%
                  \ListeCasesSKK[\fpeval{\useKV[Shikaku]{Taille}*##1+##2},2]%
                }%
              }%
            }%
          }%
          \xintifForLast{\\}{&}%
        }%
      }%
      \CodeAfter%
      \useKV[Shikaku]{CodeAfter}%
      \ifboolKV[Shikaku]{Solution}{%
        \tikz\draw[line width=2pt,PfCCouleurShikaku] (1-|1) rectangle (last-|last);%
      }{}%
    \end{NiceTabular}%
    \restorecomparemode%
  }%
}%

\NewDocumentCommand\ShikakuCreation{}{%
  \ifluatex%
  \mplibforcehmode
  \xdef\PfCNomShikaku{\useKV[Shikaku]{Nom}}%
  \begin{mplibcode}[\PfCNomShikaku]%
    Taillehor=\useKV[Shikaku]{TailleHor};
    Taillever=\useKV[Shikaku]{TailleVer};
    
    TailleMaxh=\useKV[Shikaku]{TailleHorMax};
    TailleMaxv=\useKV[Shikaku]{TailleVerMax};

    u:=5mm;
    
    path R[],S[],RIso[],SIso[];
    numeric RAire[],SAire[];
    numeric RHor[],RVer[],SHor[],SVer[],RAngle[],SAngle[];
    
    vardef RetiensLesInfosGenerales(expr depart,Lhor,Lver)=
    R[k]:=polygone(depart,depart+u*(Lhor,0),depart+u*(Lhor,-Lver),depart+u*(0,-Lver));
    RIso[k]=iso(depart,depart+u*(Lhor,0),depart+u*(Lhor,-Lver),depart+u*(0,-Lver));
    RHor[k]=Lhor;
    RVer[k]=Lver;
    RAire[k]=Lhor*Lver;
    RAngle[k]=ANGLE;
    enddef;
    
    vardef RetiensLesInfosPourLaSuite(expr depart,Lhor,Lver)=
    if Lver>0:
    S[k]=polygone(depart,depart+u*(Lhor,0),depart+u*(Lhor,-Lver),depart+u*(0,-Lver));
    SIso[k]=iso(depart,depart+u*(Lhor,0),depart+u*(Lhor,-Lver),depart+u*(0,-Lver));
    SHor[k]=Lhor;
    SVer[k]=Lver;
    SAire[k]=Lhor*Lver;
    SAngle[k]=ANGLE;
    fi;
    enddef;
    
    vardef RectangleAuto(expr aa,bb)=
    save $;
    path $;
    $=polygone(aa,aa+(xpart(bb-aa),0),bb,bb-(xpart(bb-aa),0));
    $
    enddef;

    pair T[];
    
    pair A[],B[];
  
    A1=u*(0,Taillever);
    A2-A1=u*(Taillehor,0);
    A4=(0,0);
    A3-A4=A2-A1;
    
    nbh=Taillehor div TailleMaxh;
    nbv=Taillever div TailleMaxv;
    
    p:=0;
    for l=0 upto nbv:
    for k=0 upto nbh:
    p:=p+1;
    T[p]=A1+u*(k*TailleMaxh,-l*TailleMaxv);
    if k<nbh:
    Hor[p]=TailleMaxh;
    else:
    Hor[p]=Taillehor mod TailleMaxh;
    fi;
    if l<nbv:
    Ver[p]=TailleMaxv;
    else:
    Ver[p]=Taillever mod TailleMaxv;
    fi;
    endfor;
    endfor;
    
    Total:=p;
    
    vardef DecomposeUnRectangle(expr BASEA,THOR,TVER)=
    TMAXV:=TVER;
    pair BBASEA;
    BTHOR:=THOR;
    BTVER:=TVER;
    BBASEA:=BASEA;
    forever:
    k:=k+1;
    hor:=floor(1+uniformdeviate(BTHOR));
    ver:=floor(1+uniformdeviate(BTVER));
    RetiensLesInfosGenerales(BBASEA,hor,ver);
    RetiensLesInfosPourLaSuite(BBASEA+u*(0,-ver),hor,TMAXV-ver);
    BTHOR:=BTHOR-hor;
    BTVER:=ver;
    BBASEA:=BBASEA+u*(hor,0);
    exitif BTHOR<1;
    endfor;
    enddef;
    
    k=0;
    for l=1 upto Total:
    if uniformdeviate(1)>0.5:
    Angle[l]=180;
    ANGLE:=Angle[l];
    else:
    Angle[l]=0;
    ANGLE:=Angle[l];
    fi;
    DecomposeUnRectangle(T[l],Hor[l],Ver[l]);
    endfor;
    Totalk=k;

    picture RTEXT[],STEXT[];
    
    drawoptions(withpen pencircle scaled 2);
    for n=1 upto Totalk:
    trace R[n] withcolor white;
    RTEXT[n]=image(
    label(decimal(RAire[n]),(0,0));
    );
    RTEXT[n]:=image(
    trace rotation(RTEXT[n],center RTEXT[n],RAngle[n]) shifted ((point(0) of R[n]) shifted(u*(0.5+floor(uniformdeviate(RHor[n])),-0.5-floor(uniformdeviate(RVer[n])))));
    );
    trace RTEXT[n];
    endfor;
    for n=1 upto Totalk:
    if unknown S[n]:
    else:
    trace S[n] withcolor white;
    STEXT[n]=image(
    label(decimal(SAire[n]),(0,0));
    );
    STEXT[n]:=image(
    trace rotation(STEXT[n],center STEXT[n],SAngle[n]) shifted ((point(0) of S[n]) shifted(u*(0.5+floor(uniformdeviate(SHor[n])),-0.5-floor(uniformdeviate(SVer[n])))));
    );
    trace STEXT[n];
    fi;
    endfor;
    clip currentpicture to polygone(A1,A2,A3,A4);
    
    picture CasesAvant[],CasesApres[];
    CasesAvant[0]=currentpicture;
    
    currentpicture:=nullpicture;

    drawoptions(withpen pencircle scaled 2);
    for n=1 upto Totalk:
    trace R[n];
    trace RTEXT[n];
    endfor;
    for n=1 upto Totalk:
    if unknown S[n]:
    else:
    trace S[n];
    trace STEXT[n];
    fi;
    endfor;
    clip currentpicture to polygone(A1,A2,A3,A4);
    CasesApres[0]:=currentpicture;
    
    currentpicture:=nullpicture;
        
    for l=1 upto Total:
    CasesAvant[l]=image(%
    trace CasesAvant[0];
    clip currentpicture to polygone(T[l],T[l]+u*(Hor[l],0),T[l]+u*(Hor[l],-Ver[l]),T[l]+u*(0,-Ver[l]));
    );
    currentpicture:=nullpicture;
    CasesApres[l]=image(
    trace CasesApres[0];
    clip currentpicture to polygone(T[l],T[l]+u*(Hor[l],0),T[l]+u*(Hor[l],-Ver[l]),T[l]+u*(0,-Ver[l]));
    );
    currentpicture:=nullpicture;
    endfor;
    
    for l=1 upto Total:
    trace rotation(CasesAvant[l],center CasesAvant[l],Angle[l]);
    endfor;
    
    drawoptions(withpen pencircle scaled 2);
    trace RectangleAuto(A1,A3);
    drawoptions();
    for k=1 upto Taillehor-1:
    trace (k/Taillehor)[A4,A3]--(k/Taillehor)[A1,A2];
    endfor;
    
    for k=1 upto Taillever-1:
    trace (k/Taillever)[A4,A1]--(k/Taillever)[A3,A2];
    endfor;
  \end{mplibcode}
  \fi%
}%

\NewDocumentCommand\ShikakuCreationSolution{}{%
  \ifluatex%
  \mplibforcehmode
  \xdef\PfCNomShikaku{\useKV[Shikaku]{Nom}}%
  \begin{mplibcode}[\PfCNomShikaku]%
    for l=1 upto Total:
    trace rotation(CasesApres[l],center CasesApres[l],Angle[l]);
    endfor;
    drawoptions(withpen pencircle scaled 2);
    trace RectangleAuto(A1,A3);
    drawoptions();
    for k=1 upto Taillehor-1:
    trace (k/Taillehor)[A4,A3]--(k/Taillehor)[A1,A2];
    endfor;
    
    for k=1 upto Taillever-1:
    trace (k/Taillever)[A4,A1]--(k/Taillever)[A3,A2];
    endfor;
  \end{mplibcode}
  \fi%
}%

%%%
% Kakuro
%%%
\setKVdefault[Kakuro]{CouleurCase=LightGray,TLargeur=5,THauteur=5,Solution=false,Largeur=2em,Aide=false,CouleurSolution=Black,Tailles=false}%,Taille=5
\defKV[Kakuro]{ListeNombres=\setKV[Kakuro]{Aide}}%
\defKV[Kakuro]{Taille=\setKV[Kakuro]{Tailles}}%

\newlength\PfCKakuro%

\NewDocumentCommand\Kakuro{o m}{%
  \useKVdefault[Kakuro]%
  \setKV[Kakuro]{#1}%
  \ifboolKV[Kakuro]{Tailles}{%
    \setKV[Kakuro]{THauteur=\useKV[Kakuro]{Taille}}%
    \setKV[Kakuro]{TLargeur=\useKV[Kakuro]{Taille}}%
  }{}%
  \setlength{\PfCKakuro}{\useKV[Kakuro]{Largeur}+\tabcolsep}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeCasesKK{#2}%
  \setsepchar{,}%
  \xdef\ListeAvantNombres{\useKV[Kakuro]{ListeNombres}}%
  \readlist*\ListeKakuroNombres{\ListeAvantNombres}%
  \savecomparemode%
  \comparestrict%
  \begin{NiceTabular}{*{\useKV[Kakuro]{TLargeur}}{m{\useKV[Kakuro]{Largeur}}}}[hvlines]
    \xintFor* ##1 in {\xintSeq{0}{\fpeval{\useKV[Kakuro]{THauteur}-1}}}\do{%
      \xintFor* ##2 in {\xintSeq{1}{\useKV[Kakuro]{TLargeur}}}\do{%
        \rule{0pt}{\PfCKakuro}%
        \StrCompare{\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2},1]}{*}[\PfCTestBlack]
        \xintifboolexpr{\PfCTestBlack==0}{%
          \Block[fill=black]{1-1}{}%
        }{%
          \xintifboolexpr{\listlen\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2}]==2}{
            \Block[fill=\useKV[Kakuro]{CouleurCase}]{1-1}{\diagbox{\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2},1]}{\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2},2]}}%
          }{%
            \Block{1-1}{\ifboolKV[Kakuro]{Solution}{\Large\color{\useKV[Kakuro]{CouleurSolution}}\num{\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2},1]}}{%
                \ifboolKV[Kakuro]{Aide}{%
                  \xintFor* ##3 in{\xintSeq{1}{\ListeKakuroNombreslen}}\do{%
                    \Block{1-1}{\xintifboolexpr{\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2},1]==\ListeKakuroNombres[##3]}{\Large\color{\useKV[Kakuro]{CouleurSolution}}\num{\ListeCasesKK[\fpeval{\useKV[Kakuro]{TLargeur}*##1+##2},1]}}{}}%
                  }%
                }{}%
              }%
            }%
          }%
        }%
        \xintifForLast{\\}{&}%
      }%
    }%
  \end{NiceTabular}
  \restorecomparemode%
}%

%%%
% KenKen
%%%
\setKVdefault[ClesKK]{Solution=false,Taille=3,Largeur=2em,Aide=false}%
\defKV[ClesKK]{Nombre=\setKV[ClesKK]{Aide}}%

\newlength\PfCKenKen

\NewDocumentCommand\KenKen{o m}{%
  \useKVdefault[ClesKK]%
  \setKV[ClesKK]{#1}%
  \setlength{\PfCKenKen}{\useKV[ClesKK]{Largeur}+\tabcolsep}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeCasesKK{#2}%
  \savecomparemode%
  \comparestrict%
  \begin{NiceTabular}{*{\useKV[ClesKK]{Taille}}{m{\useKV[ClesKK]{Largeur}}}}%
    \CodeBefore
    \xintFor* ##1 in {\xintSeq{2}{\fpeval{\useKV[ClesKK]{Taille}}}}\do{%
      \tikz\draw[gray] (##1-|1) -- (##1-|last);%
      \tikz\draw[gray] (1-|##1) -- (last-|##1);%
    }%
    \Body
    \xintFor* ##1 in {\xintSeq{0}{\fpeval{\useKV[ClesKK]{Taille}-1}}}\do{%
      \xintFor* ##2 in {\xintSeq{1}{\useKV[ClesKK]{Taille}}}\do{%
        \rule{0pt}{\PfCKenKen}%
        \StrCompare{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},1]}{b}[\PfCTestb]%\PfCTestb
        \StrCompare{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},1]}{l}[\PfCTestl]%\PfCTestr
        \StrCompare{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},1]}{lb}[\PfCTestlb]%\PfCTestbr
        \xintifboolexpr{\PfCTestb==0}{%
          \Block[borders={bottom},line-width=2pt]{1-1}{%
            \ifboolKV[ClesKK]{Solution}{%
              \Large\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]%
            }{%
              \ifboolKV[ClesKK]{Aide}{%
                \xintifboolexpr{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]==\useKV[ClesKK]{Nombre}}{%
                  \cellcolor{LightGray}\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]%
                }{}%
              }{}%
            }%
          }%
        }{%
          \xintifboolexpr{\PfCTestl==0}{%
            \Block[borders={left},line-width=2pt]{1-1}{\ifboolKV[ClesKK]{Solution}{\Large\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]}{%
                \ifboolKV[ClesKK]{Aide}{%
                  \xintifboolexpr{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]==\useKV[ClesKK]{Nombre}}{%
                    \cellcolor{LightGray}\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]%
                  }{}%
                }{}%
              }%
            }%
          }{%
            \xintifboolexpr{\PfCTestlb==0}{%
              \Block[borders={bottom,left},line-width=2pt]{1-1}{\ifboolKV[ClesKK]{Solution}{\Large\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]}{%
                  \ifboolKV[ClesKK]{Aide}{%
                    \xintifboolexpr{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]==\useKV[ClesKK]{Nombre}}{%
                      \cellcolor{LightGray}\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]%
                    }{}%
                  }{}%
                }%
              }%
            }{%
              \Block{1-1}{\ifboolKV[ClesKK]{Solution}{\Large\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]}{%
                  \ifboolKV[ClesKK]{Aide}{%
                    \xintifboolexpr{\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]==\useKV[ClesKK]{Nombre}}{%
                      \cellcolor{LightGray}\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*##1+##2},3]%
                    }{}%
                  }{}%
                }%
              }%
            }%
          }%
        }%
        \xintifForLast{\\}{&}%
      }%
    }%
    \CodeAfter%
    \tikz\draw[line width=2pt] (1-|1) rectangle (last-|last);%
    \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[ClesKK]{Taille}}}}\do{%
      \xintFor* ##2 in {\xintSeq{1}{\useKV[ClesKK]{Taille}}}\do{%
        \tikz\node[anchor=west,inner sep=0pt,xshift=1mm,yshift=-0.2\PfCKenKen] at (##1 -|##2) {\scriptsize$\ListeCasesKK[\fpeval{\useKV[ClesKK]{Taille}*(##1-1)+##2},2]$};%
      }%
    }%
  \end{NiceTabular}
  \restorecomparemode%
}%

%%%
% PixelArt
%%%
\newtoks\toklistePANombre%
\def\UpdatetoksPANombre#1\nil{\addtotok\toklistePANombre{"#1",}}%

\setKVdefault[ClesPixelArt]{Largeur=29,Hauteur=29,Solution=false,Lettres=ABCDEFGHIJK,Nombres=false,ListeCouleurs={Orange,Red,LightGray,Maroon,Purple,black,black,Plum,Orange,White,White},Unite=5mm}
\defKV[ClesPixelArt]{ListeNombres=\setKV[ClesPixelArt]{Nombres}}

\NewDocumentCommand\PixelArt{o m}{%
  \toklistePANombre{}%
  \useKVdefault[ClesPixelArt]%
  \setKV[ClesPixelArt]{#1}%
  \xdef\ListeAvantCouleurs{\useKV[ClesPixelArt]{ListeCouleurs}}%
  \xdef\ListeAvantNombres{\useKV[ClesPixelArt]{ListeNombres}}%
  \setsepchar{,}%
  \readlist*\ListePANombre{\ListeAvantNombres}%
  \foreachitem\compteur\in\ListePANombre{\expandafter\UpdatetoksPANombre\compteur\nil}%
  \BuildPixelArt{#2}{\useKV[ClesPixelArt]{Lettres}}{\ListeAvantCouleurs}{\the\toklistePANombre}%
}%

\NewDocumentCommand\BuildPixelArt{m m m m}{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    largeur:=\useKV[ClesPixelArt]{Largeur};
    hauteur:=\useKV[ClesPixelArt]{Hauteur};
    Unite:=\useKV[ClesPixelArt]{Unite};
    boolean Solution,Nombres;
    Solution:=\useKV[ClesPixelArt]{Solution};
    Nombres:=\useKV[ClesPixelArt]{Nombres};
    string BaseLettres;
    BaseLettres=str #2;

    color ColorEntier[],ColFond;
    n:=0;
    for p_=#3:
    n:=n+1;
    ColorEntier[n]:=p_;
    endfor;

    string RetiensNombres[];
    if Nombres:
    n:=0;
    for p_=#4:
    n:=n+1;
    RetiensNombres[n]=p_;
    endfor;
    fi;
        
    vardef Lecturecsv(expr nomfichier)=
    for h=hauteur downto 1:
    string p_;
    p_=readfrom nomfichier;
    l:=0;
    for p=0 step 2 until 2*largeur-2:
    l:=l+1;
    if (substring(p,p+1) of p_)="-":
    else:
    if Nombres:
    for m=0 upto (length BaseLettres-1):
    if (substring(p,p+1) of p_)=substring(m,m+1) of BaseLettres:
    label(TEX(RetiensNombres[m+1]),((l-1)*Unite,(h-1)*Unite));
    fi;
    endfor;
    else:
    label(TEX(substring(p,p+1) of p_),((l-1)*Unite,(h-1)*Unite));
    fi;
    if Solution:
    for m=0 upto (length BaseLettres-1):
    if (substring(p,p+1) of p_)=substring(m,m+1) of BaseLettres:
    ColFond:=ColorEntier[m+1];
    fi;
    endfor;
    if unknown ColFond: else: fill (unitsquare scaled Unite) shifted ((l-1)*Unite-0.5*Unite,(h-1)*Unite-0.5*Unite) withcolor ColFond fi;
    fi;
    trace (unitsquare scaled Unite) shifted ((l-1)*Unite-0.5*Unite,(h-1)*Unite-0.5*Unite);
   fi;
    endfor;
    endfor;
    closefrom nomfichier;
    enddef;
    
    Lecturecsv("#1");
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={largeur:=\useKV[ClesPixelArt]{Largeur}; hauteur:=\useKV[ClesPixelArt]{Hauteur}; Unite:=\useKV[ClesPixelArt]{Unite}; boolean Solution,Nombres; Solution:=\useKV[ClesPixelArt]{Solution}; Nombres:=\useKV[ClesPixelArt]{Nombres};}]
    string BaseLettres;
    BaseLettres=str #2;

    color ColorEntier[],ColFond;
    n:=0;
    for p_=#3:
    n:=n+1;
    ColorEntier[n]:=p_;
    endfor;

    string RetiensNombres[];
    if Nombres:
    n:=0;
    for p_=#4:
    n:=n+1;
    RetiensNombres[n]=p_;
    endfor;
    fi;
        
    vardef Lecturecsv(expr nomfichier)=
    for h=hauteur downto 1:
    string p_;
    p_=readfrom nomfichier;
    l:=0;
    for p=0 step 2 until 2*largeur-2:
    l:=l+1;
    if (substring(p,p+1) of p_)="-":
    else:
    if Nombres:
    for m=0 upto (length BaseLettres-1):
    if (substring(p,p+1) of p_)=substring(m,m+1) of BaseLettres:
    label(LATEX(RetiensNombres[m+1]),((l-1)*Unite,(h-1)*Unite));
    fi;
    endfor;
    else:
    label(LATEX(substring(p,p+1) of p_),((l-1)*Unite,(h-1)*Unite));
    fi;
    if Solution:
    for m=0 upto (length BaseLettres-1):
    if (substring(p,p+1) of p_)=substring(m,m+1) of BaseLettres:
    ColFond:=ColorEntier[m+1];
    fi;
    endfor;
    if unknown ColFond: else: fill (unitsquare scaled Unite) shifted ((l-1)*Unite-0.5*Unite,(h-1)*Unite-0.5*Unite) withcolor ColFond fi;
    fi;
    trace (unitsquare scaled Unite) shifted ((l-1)*Unite-0.5*Unite,(h-1)*Unite-0.5*Unite);
   fi;
    endfor;
    endfor;
    closefrom nomfichier;
    enddef;
    
    Lecturecsv("#1");
  \end{mpost}
  \fi
}

%%%
% Yohaku
%%%
\setKVdefault[Yohaku]{Taille=2,Largeur=1cm,Hauteur=1cm,Addition,Multiplication=false,Perso=false,Limite=50,Relatif=false,Negatif=false,Pair=false,Impair=false,Premier=false,Solution=false,Visible=false,Bordure=false,CouleurResultat=gray!15,Ligne=0,Colonne=0,PasL=0,PasC=0,CouleurZone=gray!25}%
\defKV[Yohaku]{Case=\setKV[Yohaku]{Visible}}%

\newlength\PfCYohaku%

\xdef\PfCYHKpremier{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47}%

\NewDocumentCommand\Yohaku{o m}{%
  \useKVdefault[Yohaku]%
  \setKV[Yohaku]{#1}%
  \xdef\PfCYHKlast{\fpeval{\useKV[Yohaku]{Taille}+1}}%
  \xdef\PfCYHKnombre{1}%
  \xdef\PfCYHKpair{2}%
  \xdef\PfCYHKimpair{1}%
  \xdef\PfCYHKnegatif{}%
  \xintFor* ##1 in{\xintSeq{2}{\fpeval{\useKV[Yohaku]{Limite}}}}\do{%
    \xdef\PfCYHKnegatif{\PfCYHKnegatif -##1,}%
  }%
  \xintFor* ##1 in{\xintSeq{2}{\fpeval{\useKV[Yohaku]{Limite}}}}\do{%
    \xdef\PfCYHKnombre{\PfCYHKnombre,##1}%
  }%
  \xintFor* ##1 in{\xintSeq{2}{\fpeval{\useKV[Yohaku]{Limite}}}}\do{%
    \xdef\PfCYHKpair{\PfCYHKpair,\fpeval{##1*2}}%
  }%
  \xintFor* ##1 in{\xintSeq{1}{\fpeval{\useKV[Yohaku]{Limite}}}}\do{%
    \xdef\PfCYHKimpair{\PfCYHKimpair,\fpeval{##1*2+1}}%
  }%
  %
  \ifboolKV[Yohaku]{Perso}{%
    \setsepchar[*]{,*/}\ignoreemptyitems%
    \readlist*\PfCYHKListe{#2}%
    \setsepchar{,}%
    \xdef\PfCYHKListeFoo{}%
    \foreachitem\compteur\in\PfCYHKListe[1]{%
      \xdef\PfCYHKListeFoo{\PfCYHKListeFoo \PfCYHKListe[1,\compteurcnt],}%
    }%
    \ignoreemptyitems\readlist*\PfCYHKListeNA{\PfCYHKListeFoo}%
    \xdef\PfCYHKListeFoo{}%
    \foreachitem\compteur\in\PfCYHKListe[2]{%
      \xdef\PfCYHKListeFoo{\PfCYHKListeFoo \PfCYHKListe[2,\compteurcnt],}%
    }%
    \ignoreemptyitems\readlist*\PfCYHKListeP{\PfCYHKListeFoo}%
  }{%
    \ifboolKV[Yohaku]{Negatif}{%
      \xdef\PfCYHKListe{\PfCYHKnegatif}%
    }{%
      \ifboolKV[Yohaku]{Premier}{%
        \xdef\PfCYHKListe{\PfCYHKpremier}%
      }{%
        \ifboolKV[Yohaku]{Impair}{%
          \xdef\PfCYHKListe{\PfCYHKimpair}%
        }{%
          \ifboolKV[Yohaku]{Pair}{%
            \xdef\PfCYHKListe{\PfCYHKpair}%
          }{%
            \xdef\PfCYHKListe{\PfCYHKnombre}%
          }%
        }%
      }%
    }%
    \ifboolKV[Yohaku]{Relatif}{%
      \xdef\PfCMoitieCase{\fpeval{floor((\useKV[Yohaku]{Taille}**2)/2)}}%
      \xdef\PfCAutreMoitieCase{\fpeval{\useKV[Yohaku]{Taille}**2-\PfCMoitieCase}}%
      \xdef\PfCFooRelatifYohaku{}%
      \xdef\PfCYohakuAlea{\fpeval{randint(1,2)}}%
      \xintifboolexpr{\PfCYohakuAlea==1}{% on choisit M1 négatifs, M2 positifs
        \MelangeListe{\PfCYHKnegatif}{\PfCMoitieCase}%
        \xdef\PfCYohakuInter{\faa}%
        \MelangeListe{\PfCYHKnombre}{\PfCAutreMoitieCase}%
        \xdef\PfCYohakuInter{\PfCYohakuInter,\faa}%
      }{% on choisit M1 positifs, M2 négatifs
        \MelangeListe{\PfCYHKnombre}{\PfCMoitieCase}%
        \xdef\PfCYohakuInter{\faa}%
        \MelangeListe{\PfCYHKnegatif}{\PfCAutreMoitieCase}%
        \xdef\PfCYohakuInter{\PfCYohakuInter,\faa}%
      }%
      \MelangeListe{\PfCYohakuInter}{\fpeval{\useKV[Yohaku]{Taille}**2}}%
    }{%
      \MelangeListe{\PfCYHKListe}{\fpeval{\useKV[Yohaku]{Taille}**2}}%
    }%
    \ignoreemptyitems\readlist*\PfCYHKListeNA{\faa}%
    %Sommes/Produits
    \xdef\PfCYHKListeProduit{}%
    %verticaux
    \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
      \ifboolKV[Yohaku]{Multiplication}{%
        \xdef\PfCYHKTampon{1}%
        \xintFor* ##1 in {\xintSeq{0}{\fpeval{\useKV[Yohaku]{Taille}-1}}}\do{%
          \xdef\PfCYHKTampon{\fpeval{\PfCYHKTampon*\PfCYHKListeNA[\fpeval{##2+##1*\useKV[Yohaku]{Taille}}]}}%
        }%
      }{%
        \xdef\PfCYHKTampon{0}%
        \xintFor* ##1 in {\xintSeq{0}{\fpeval{\useKV[Yohaku]{Taille}-1}}}\do{%
          \xdef\PfCYHKTampon{\fpeval{\PfCYHKTampon+\PfCYHKListeNA[\fpeval{##2+##1*\useKV[Yohaku]{Taille}}]}}%
        }%
      }%
      \xdef\PfCYHKListeProduit{\PfCYHKListeProduit,\PfCYHKTampon}%
    }%
    % horizontaux
    \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
      \ifboolKV[Yohaku]{Multiplication}{%
        \xdef\PfCYHKTampon{1}%
        \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
          \xdef\PfCYHKTampon{\fpeval{\PfCYHKTampon*\PfCYHKListeNA[\fpeval{(\useKV[Yohaku]{Taille}-##2)*\useKV[Yohaku]{Taille}+##1}]}}%
        }%
      }{%
        \xdef\PfCYHKTampon{0}%
        \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
          \xdef\PfCYHKTampon{\fpeval{\PfCYHKTampon+\PfCYHKListeNA[\fpeval{(\useKV[Yohaku]{Taille}-##2)*\useKV[Yohaku]{Taille}+##1}]}}%
        }%
      }%
      \xdef\PfCYHKListeProduit{\PfCYHKListeProduit,\PfCYHKTampon}%
    }%
    \readlist*\PfCYHKListeP{\PfCYHKListeProduit}%
  }%
  \setlength{\PfCYohaku}{\useKV[Yohaku]{Largeur}-\tabcolsep}%
  \colorlet{PfCFondYohaku}{\useKV[Yohaku]{CouleurResultat}}%
  \colorlet{PfCZoneYohaku}{\useKV[Yohaku]{CouleurZone}}%
  \begin{NiceTabular}{*{\fpeval{\useKV[Yohaku]{Taille}+1}}{m{\PfCYohaku}}}[hvlines-except-borders]
    \CodeBefore
    \xintifboolexpr{\useKV[Yohaku]{Ligne}==0 || \useKV[Yohaku]{Colonne}==0}{}{%
      \tikz\draw[fill=PfCZoneYohaku](row-\fpeval{\useKV[Yohaku]{Ligne}}-|col-\fpeval{\useKV[Yohaku]{Colonne}}) rectangle (row-\fpeval{\useKV[Yohaku]{Ligne}+\useKV[Yohaku]{PasL}}-|col-\fpeval{\useKV[Yohaku]{Colonne}+\useKV[Yohaku]{PasC}});%
    }%
    \ifboolKV[Yohaku]{Bordure}{%
      \tikz\fill[PfCFondYohaku] (last-|1)--(last-|last)--(1-|last)--(1-|\fpeval{\useKV[Yohaku]{Taille}+1})--(\fpeval{\useKV[Yohaku]{Taille}+1}-|\fpeval{\useKV[Yohaku]{Taille}+1})--(\fpeval{\useKV[Yohaku]{Taille}+1}-|1)--cycle;
    }{}
    \Body
    \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}+1}}}\do{%
      \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}+1}}}\do{%
        \xintifForFirst{\rule{0pt}{\useKV[Yohaku]{Hauteur}}}{&}
      }\\%
    }%
    \CodeAfter
    \ifboolKV[Yohaku]{Bordure}{%
      \tikz\draw (last-|1)--(last-|last)--(1-|last);
    }{}%
    \tikz\draw (1-|1)--(1-|last);
    \tikz\draw (1-|1)--(last-|1);
    \tikz\draw[line width=2pt] (1-|1)--(\fpeval{\useKV[Yohaku]{Taille}+1}-|1)--(\fpeval{\useKV[Yohaku]{Taille}+1}-|\fpeval{\useKV[Yohaku]{Taille}+1})--(1-|\fpeval{\useKV[Yohaku]{Taille}+1})--cycle;
    \tikz\node at (\fpeval{\PfCYHKlast+0.5}-|\fpeval{\PfCYHKlast+0.5}) {\Huge\ifboolKV[Yohaku]{Multiplication}{$\times$}{$+$}};
    % Affichage des termes/facteurs
    \ifboolKV[Yohaku]{Solution}{%
      \ifboolKV[Yohaku]{Perso}{%
        \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
          \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
            \tikz\node at (\fpeval{##2+0.5}-|\fpeval{##1+0.5}) {\PfCYHKListeNA[\fpeval{(##2-1)*\useKV[Yohaku]{Taille}+##1}]};
          }%
        }%
      }{%
        \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{
          \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{
            \tikz\node at (\fpeval{##2+0.5}-|\fpeval{##1+0.5}) {\num{\PfCYHKListeNA[\fpeval{(##2-1)*\useKV[Yohaku]{Taille}+##1}]}};
          }%
        }%
      }%
    }{}%
    % Affichage d'un terme/facteur
    \ifboolKV[Yohaku]{Visible}{%
      \xdef\PfCYohakuCaseAFL{\fpeval{floor((\useKV[Yohaku]{Case}-1)/\useKV[Yohaku]{Taille})}}%
      \xdef\PfCYohakuCaseAFC{\fpeval{\useKV[Yohaku]{Case}-\useKV[Yohaku]{Taille}*\PfCYohakuCaseAFL}}%
      \ifboolKV[Yohaku]{Perso}{%
        \tikz\node at (\fpeval{\PfCYohakuCaseAFL+1+0.5}-|\fpeval{\PfCYohakuCaseAFC+0.5}) {\PfCYHKListeNA[\fpeval{\useKV[Yohaku]{Case}}]};
      }{%
        \tikz\node at (\fpeval{\PfCYohakuCaseAFL+1+0.5}-|\fpeval{\PfCYohakuCaseAFC+0.5}) {\num{\PfCYHKListeNA[\fpeval{\useKV[Yohaku]{Case}}]}};
      }%
    }{}%
    %% Affichage des sommes/produits horizontalement
    \ifboolKV[Yohaku]{Perso}{%
      \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
        \tikz\node at (\fpeval{\PfCYHKlast+0.5}-|\fpeval{##2+0.5}) {\PfCYHKListeP[##2]};
      }%
      \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
        \tikz\node at (\fpeval{\useKV[Yohaku]{Taille}+1-##2+0.5}-|\fpeval{\PfCYHKlast+0.5}) {\PfCYHKListeP[\fpeval{\useKV[Yohaku]{Taille}+##2}]};
      }%
    }{%
      \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
        \tikz\node at (\fpeval{\PfCYHKlast+0.5}-|\fpeval{##2+0.5}) {\num{\PfCYHKListeP[##2]}};
      }%
      \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[Yohaku]{Taille}}}}\do{%
        \tikz\node at (\fpeval{\useKV[Yohaku]{Taille}+1-##2+0.5}-|\fpeval{\PfCYHKlast+0.5}) {\num{\PfCYHKListeP[\fpeval{\useKV[Yohaku]{Taille}+##2}]}};
      }%
    }%
  \end{NiceTabular}
}%

%%%
% Rose
%%%
\setKVdefault[ClesRose]{Vide=false,Couleur=white,Produits=false,Solution=false,Rayon=2cm,Petales=7,Aide=false,FacteurMin=2,FacteurMax=10,ProduitVide=false,CaseVide=false,Polygone=false,Nom=Rose1}%

\NewDocumentCommand\RoseMul{o}{%
  \useKVdefault[ClesRose]%
  \setKV[ClesRose]{#1}%
  \ifluatex%
  \ifboolKV[ClesRose]{Solution}{%
    \DessineRoseMulSol%
  }{%
    \DessineRoseMul%
  }%
  \else%
  \DessineRoseMul%
  \fi%
}%

\newcommand\DessineRoseMulSol{%
  \ifluatex%
  \mplibforcehmode%
  \xdef\PfCNomRose{\useKV[ClesRose]{Nom}}%
  \begin{mplibcode}[\PfCNomRose]
    boolean Aide,Produits,Solution,Vide,ProduitVide,CaseVide,Polygone;
    Aide:=\useKV[ClesRose]{Aide};
    Vide:=\useKV[ClesRose]{Vide};
    Solution:=\useKV[ClesRose]{Solution};
    Produits:=\useKV[ClesRose]{Produits};
    ProduitVide:=\useKV[ClesRose]{ProduitVide};
    CaseVide:=\useKV[ClesRose]{CaseVide};
    if ProduitVide:Solution:=true fi;
    if CaseVide:Solution:=true fi;
    % on labelise
    if Vide=false:
    if Produits:
    else:
    for k=0 upto Petales-1:
    label(TEX("\num{"&decimal(Facteur[k])&"}"),(0.5[O,A[k]]-center BoiteRec));
    endfor;
    fi;
    if Produits or Solution:
    for k=0 upto Petales-1:
    label(TEX("\num{"&decimal(Produit[k])&"}"),(B[k]+0.5*Rayon*unitvector(B[k])));
    endfor;
    fi;
    fi;
    % On trace et on affiche...éventuellement :)
    if Aide:
    for k=0 upto Petales-1:
    drawarrow (0.5[O,A[k]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    drawarrow (0.5[O,A[k+1]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    endfor;
    fi;
    if ProduitVide:
    %choix=floor(uniformdeviate(Petales-1));
    fill (BoiteRec shifted (1.75[O,B[choix]]-center BoiteRec)) withcolor Fond;
    fill rotation(polygone(O,B0,A1,B1),O,(choix-1)*(360/Petales)) withcolor Fond;
    fill rotation(polygone(O,B0,A1,B1),O,choix*(360/Petales)) withcolor Fond;
    fi;
    if CaseVide:
    %choix:=floor(uniformdeviate(Petales-1));
    for k=0 upto Petales-1:
    if k<>choix:
    fill rotation(polygone(O,B0,A1,B1),O,k*(360/Petales)) withcolor Fond;
    fi;
    endfor;
    fi;
    trace A0 for k=1 upto Petales:--A[k] endfor --cycle;
    for k=0 upto Petales-1:
    trace segment(O,B[k]) dashed withdots scaled 0.25;
    draw BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    endfor;
  \end{mplibcode}
  \fi
}
\newcommand\DessineRoseMul{%
  \ifluatex%
  \mplibforcehmode%
  \xdef\PfCNomRose{\useKV[ClesRose]{Nom}}%
  \begin{mplibcode}[\PfCNomRose]
    vardef ExtraireListe(expr nbmin,nbmax,nbfacteurs)=
    numeric ElementE[],ElementS[];
    %% éléments d'entrée
    nbe:=1;
    for k=nbmin upto nbmax:
    ElementE[nbe]=k;
    nbe:=nbe+1;
    endfor;
    totalE:=(nbmax-nbmin)+1;
    numeric rec;
    for k=1 upto nbfacteurs:
    rec:=ceiling(uniformdeviate(totalE+1-k));
    ElementS[k]=ElementE[rec];
    numeric ElementI[];
    p:=0;
    for l=1 upto totalE+1-k:
    if l<>rec:
    p:=p+1;
    ElementI[p]=ElementE[l];
    fi;
    endfor;
    numeric ElementE[];
    for l=1 upto p:
    ElementE[l]=ElementI[l];
    endfor;
    endfor;
    enddef;
    pair A[],B[],O;
    Rayon:=\useKV[ClesRose]{Rayon};
    boolean Aide,Produits,Solution,Vide,ProduitVide,CaseVide,Polygone;
    Aide:=\useKV[ClesRose]{Aide};
    Vide:=\useKV[ClesRose]{Vide};
    Solution:=\useKV[ClesRose]{Solution};
    Produits:=\useKV[ClesRose]{Produits};
    ProduitVide:=\useKV[ClesRose]{ProduitVide};
    CaseVide:=\useKV[ClesRose]{CaseVide};
    if ProduitVide:Solution:=true fi;
    if CaseVide:Solution:=true fi;
    Polygone:=\useKV[ClesRose]{Polygone};
    Petales:=\useKV[ClesRose]{Petales};
    FacteurMin:=\useKV[ClesRose]{FacteurMin};
    FacteurMax:=\useKV[ClesRose]{FacteurMax};
    color Fond;
    Fond:=\useKV[ClesRose]{Couleur};
    O=(0,0);
    ExtraireListe(FacteurMin,FacteurMax,Petales);
    path cc;
    cc=cercles(O,Rayon);
    for k=0 upto Petales:
    A[k]=pointarc(cc,(360/Petales)*k);
    endfor;
    for k=0 upto Petales-1:
    B[k]=iso(A[k],A[k+1]);
    endfor;
    path BoiteRec;
    if Polygone:
    BoiteRec=(pointarc(fullcircle,0) for k=1 upto Petales:--pointarc(fullcircle,k*(360/Petales)) endfor --cycle) scaled 1u;
    else:
    BoiteRec=((-0.4,-0.5)--(0.4,-0.5){dir0}..{dir90}(0.5,-0.4)--(0.5,0.4){dir90}..{dir180}(0.4,0.5)--(-0.4,0.5){dir180}..{dir-90}(-0.5,0.4)--(-0.5,-0.4){dir-90}..cycle) scaled 1u;
    fi;    
    %On détermine les facteurs et produits
    for k=0 upto Petales-1:
    Facteur[k]:=ElementS[k+1];
    endfor;
    Facteur[Petales]:=Facteur[0];
    for k=0 upto Petales-1:
    Produit[k]:=Facteur[k]*Facteur[k+1];
    endfor;
    %on labelise
    if Vide=false:
    if Produits:
    else:
    for k=0 upto Petales-1:
    label(TEX("\num{"&decimal(Facteur[k])&"}"),(0.5[O,A[k]]-center BoiteRec));
    endfor;
    fi;
    if Produits or Solution:
    for k=0 upto Petales-1:
    label(TEX("\num{"&decimal(Produit[k])&"}"),(B[k]+0.5*Rayon*unitvector(B[k])));
    endfor;
    fi;
    fi;
    % On trace et on affiche...éventuellement :)
    if Aide:
    for k=0 upto Petales-1:
    drawarrow (0.5[O,A[k]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    drawarrow (0.5[O,A[k+1]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    endfor;
    fi;
    if ProduitVide:
    choix:=floor(uniformdeviate(Petales-1));
    fill (BoiteRec shifted (1.75[O,B[choix]]-center BoiteRec)) withcolor Fond;
    fill rotation(polygone(O,B0,A1,B1),O,(choix-1)*(360/Petales)) withcolor Fond;
    fill rotation(polygone(O,B0,A1,B1),O,choix*(360/Petales)) withcolor Fond;
    fi;
    if CaseVide:
    choix:=floor(uniformdeviate(Petales-1));
    for k=0 upto Petales-1:
    if k<>choix:
    fill rotation(polygone(O,B0,A1,B1),O,k*(360/Petales)) withcolor Fond;
    fi;
    endfor;
    fi;
    trace A0 for k=1 upto Petales:--A[k] endfor --cycle;
    for k=0 upto Petales-1:
    trace segment(O,B[k]) dashed withdots scaled 0.25;
    draw BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={Rayon:=\useKV[ClesRose]{Rayon};
    boolean Aide,Produits,Solution,Vide,ProduitVide,CaseVide,Polygone;
    Aide:=\useKV[ClesRose]{Aide};
    Vide:=\useKV[ClesRose]{Vide};
    Solution:=\useKV[ClesRose]{Solution};
    Produits:=\useKV[ClesRose]{Produits};
    ProduitVide:=\useKV[ClesRose]{ProduitVide};
    CaseVide:=\useKV[ClesRose]{CaseVide};
    if ProduitVide:Solution:=true fi;
    if CaseVide:Solution:=true fi;
    Polygone:=\useKV[ClesRose]{Polygone};
    Petales:=\useKV[ClesRose]{Petales};
    FacteurMin:=\useKV[ClesRose]{FacteurMin};
    FacteurMax:=\useKV[ClesRose]{FacteurMax};
    color Fond;
    Fond:=\useKV[ClesRose]{Couleur};}]
    vardef ExtraireListe(expr nbmin,nbmax,nbfacteurs)=
    numeric ElementE[],ElementS[];
    %% éléments d'entrée
    nbe=1;
    for k=nbmin upto nbmax:
    ElementE[nbe]=k;
    nbe:=nbe+1;
    endfor;
    totalE=(nbmax-nbmin)+1;
    numeric rec;
    for k=1 upto nbfacteurs:
    rec:=ceiling(uniformdeviate(totalE+1-k));
    ElementS[k]=ElementE[rec];
    numeric ElementI[];
    p:=0;
    for l=1 upto totalE+1-k:
    if l<>rec:
    p:=p+1;
    ElementI[p]=ElementE[l];
    fi;
    endfor;
    numeric ElementE[];
    for l=1 upto p:
    ElementE[l]=ElementI[l];
    endfor;
    endfor;
    enddef;
    pair A[],B[],O;
    O=(0,0);
    ExtraireListe(FacteurMin,FacteurMax,Petales);
    path cc;
    cc=cercles(O,Rayon);
    for k=0 upto Petales:
    A[k]=pointarc(cc,(360/Petales)*k);
    endfor;
    for k=0 upto Petales-1:
    B[k]=iso(A[k],A[k+1]);
    endfor;
    path BoiteRec;
    if Polygone:
    BoiteRec=(pointarc(fullcircle,0) for k=1 upto Petales:--pointarc(fullcircle,k*(360/Petales)) endfor --cycle) scaled 1u;
    else:
    BoiteRec=((-0.4,-0.5)--(0.4,-0.5){dir0}..{dir90}(0.5,-0.4)--(0.5,0.4){dir90}..{dir180}(0.4,0.5)--(-0.4,0.5){dir180}..{dir-90}(-0.5,0.4)--(-0.5,-0.4){dir-90}..cycle) scaled 1u;
    fi;    
    %On détermine les facteurs et produits
    for k=0 upto Petales-1:
    Facteur[k]=ElementS[k+1];
    endfor;
    Facteur[Petales]=Facteur[0];
    for k=0 upto Petales-1:
    Produit[k]=Facteur[k]*Facteur[k+1];
    endfor;
    %on labelise
    if Vide=false:
    if Produits:
    else:
    for k=0 upto Petales-1:
    label(LATEX("\num{"&decimal(Facteur[k])&"}"),(0.5[O,A[k]]-center BoiteRec));
    endfor;
    fi;
    if Produits or Solution:
    for k=0 upto Petales-1:
    label(LATEX("\num{"&decimal(Produit[k])&"}"),(B[k]+0.5*Rayon*unitvector(B[k])));
    endfor;
    fi;
    fi;
    % On trace et on affiche...éventuellement :)
    if Aide:
    for k=0 upto Petales-1:
    drawarrow (0.5[O,A[k]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    drawarrow (0.5[O,A[k+1]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    endfor;
    fi;
    if ProduitVide:
    choix=floor(uniformdeviate(Petales-1));
    fill (BoiteRec shifted (1.75[O,B[choix]]-center BoiteRec)) withcolor Fond;
    fill rotation(polygone(O,B0,A1,B1),O,(choix-1)*(360/Petales)) withcolor Fond;
    fill rotation(polygone(O,B0,A1,B1),O,choix*(360/Petales)) withcolor Fond;
    fi;
    if CaseVide:
    choix:=floor(uniformdeviate(Petales-1));
    for k=0 upto Petales-1:
    if k<>choix:
    fill rotation(polygone(O,B0,A1,B1),O,k*(360/Petales)) withcolor Fond;
    fi;
    endfor;
    fi;
    trace A0 for k=1 upto Petales:--A[k] endfor --cycle;
    for k=0 upto Petales-1:
    trace segment(O,B[k]) dashed withdots scaled 0.25;
    draw BoiteRec shifted (B[k]+0.5*Rayon*unitvector(B[k])) dashed evenly scaled 0.5;
    endfor;
  \end{mpost}
  \fi
}%

%%%
% Puissances 4
%%%
\setKVdefault[ClesPQuatre]{Couleur=Gray,Largeur=2cm,LargeurUn=2cm,Multiplication,Entier,Nombre,Exposant=false,Libre=false,Texte=false,Echelle=2}%
\defKV[ClesPQuatre]{Addition=\setKV[ClesPQuatre]{Multiplication=false}}%
\defKV[ClesPQuatre]{Relatif=\setKV[ClesPQuatre]{Entier=false}}%
\defKV[ClesPQuatre]{Puissance=\setKV[ClesPQuatre]{Exposant}}%
\defKV[ClesPQuatre]{Autre=\setKV[ClesPQuatre]{Nombre=false}\setKV[ClesPQuatre]{Libre}}%
\defKV[ClesPQuatre]{Consignes=\setKV[ClesPQuatre]{Texte}}%

\newtoks\toklistePQuatreh%
\newtoks\toklistePQuatrev%
\def\UpdatetoksPQuatreh#1\nil{\addtotok\toklistePQuatreh{"#1",}}%
\def\UpdatetoksPQuatrev#1\nil{\addtotok\toklistePQuatrev{"#1",}}%

\NewDocumentCommand\PQuatre{o +m}{%
  \useKVdefault[ClesPQuatre]%
  \toklistePQuatreh{}%
  \toklistePQuatrev{}%
  \setKV[ClesPQuatre]{#1}%
  \ifboolKV[ClesPQuatre]{Nombre}{%
    \ifboolKV[ClesPQuatre]{Exposant}{%
      \def\PQuatreListe{$10^{-10}$,$10^{-9}$,$10^{-8}$,$10^{-7}$,$10^{-6}$,$10^{-5}$,$10^{-4}$,$10^{-3}$,$10^{-2}$,$10^{2}$,$10^{3}$,$10^{4}$,$10^{5}$,$10^{6}$,$10^{7}$,$10^{8}$,$10^{9}$,$10^{10}$}%
      \MelangeListe{\PQuatreListe}{7}%
      \readlist*\PQuatreListeH{\faa}%
      \MelangeListe{\PQuatreListe}{7}%
      \readlist*\PQuatreListeV{\faa}%
      \foreachitem\compteur\in\PQuatreListeH{\expandafter\UpdatetoksPQuatreh\compteur\nil}%
      \foreachitem\compteur\in\PQuatreListeV{\expandafter\UpdatetoksPQuatrev\compteur\nil}%
    }{%
      \ifboolKV[ClesPQuatre]{Entier}{%
        % On choisit aléatoirement les listes de nombres de 2 à 10 en faisant deux listes : horizontale et verticale
        \def\PQuatreListe{2,3,4,5,6,7,8,9,10}%
        \MelangeListe{\PQuatreListe}{7}%
        \readlist*\PQuatreListeH{\faa}%
        \MelangeListe{\PQuatreListe}{7}%
        \readlist*\PQuatreListeV{\faa}%
        \foreachitem\compteur\in\PQuatreListeH{\expandafter\UpdatetoksPQuatreh\compteur\nil}%
        \foreachitem\compteur\in\PQuatreListeV{\expandafter\UpdatetoksPQuatrev\compteur\nil}%
      }{%
        % On choisit aléatoirement les listes de nombres de -10 à -2 union 2 à 10 en faisant deux listes : horizontale et verticale
        \def\PQuatreListe{$-10$,$-9$,$-8$,$-7$,$-6$,$-5$,$-4$,$-3$,$-2$,2,3,4,5,6,7,8,9,10}%
        \MelangeListe{\PQuatreListe}{7}%
        \readlist*\PQuatreListeH{\faa}%
        \MelangeListe{\PQuatreListe}{7}%
        \readlist*\PQuatreListeV{\faa}%
        \foreachitem\compteur\in\PQuatreListeH{\expandafter\UpdatetoksPQuatreh\compteur\nil}%
        \foreachitem\compteur\in\PQuatreListeV{\expandafter\UpdatetoksPQuatrev\compteur\nil}%
      }%
    }%
  }{%
    % on lit la liste des données fournies par l'utilisateur
    \setsepchar[*]{,*/}%
    \readlist\PQuatreListes{#2}%
    \setsepchar{,}%
    \foreachitem\compteur\in\PQuatreListes[1]{\expandafter\UpdatetoksPQuatrev\compteur\nil}%
    \foreachitem\compteur\in\PQuatreListes[2]{\expandafter\UpdatetoksPQuatreh\compteur\nil}%
  }%
  % Une fois les listes construites, on dessine et on place les listes.
  \PQuatreGrille{\the\toklistePQuatrev}{\the\toklistePQuatreh}%
}%

\NewDocumentCommand\PQuatreGrille{m m}{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}
    Largeur=\useKV[ClesPQuatre]{Largeur};
    LargeurUn=\useKV[ClesPQuatre]{LargeurUn};
    Echelle=\useKV[ClesPQuatre]{Echelle};
    color fond;
    fond=\useKV[ClesPQuatre]{Couleur};
    boolean Libre,Multiplication,Texte;
    Libre:=\useKV[ClesPQuatre]{Libre};
    Multiplication=\useKV[ClesPQuatre]{Multiplication};
    Texte:=\useKV[ClesPQuatre]{Texte};

    if Texte:
    string Consignes;
    Consignes=\useKV[ClesPQuatre]{Consignes};
    fi;
    
    % On calcule le nombre de cases
    nchauteur:=0;
    for p_=#1:
    nchauteur:=incr nchauteur;
    endfor;
    nclargeur:=0;
    for p_=#2:
    nclargeur:=incr nclargeur;
    endfor;
    if Libre=false:
    nchauteur:=7;
    nclargeur:=7;
    fi;
    %On affiche
    pair A,B,C,D,H[],V[],M[][];
    A=(0,0);
    B-A=Largeur*(nclargeur,0);
    C-B=Largeur*(0,nchauteur);
    D-C=A-B;
    fill polygone(A,B,C,D) withcolor fond;
    trace polygone(A,B,C,D);
    for k=0 upto (nclargeur-1):
    for l=0 upto (nchauteur-1):
    M[k][l]=A+0.5*(Largeur,Largeur)+k*(Largeur,0)+l*(0,Largeur);
    fill cercles(M[k][l],0.4*Largeur) withcolor blanc;
    trace cercles(M[k][l],0.4*Largeur);
    endfor;
    endfor;
    labeloffset:=labeloffset*2;
    if Libre:
    if Texte:
    label.llft(TEX("\begin{minipage}{"&decimal(LargeurUn)&"pt}"&Consignes&"\end{minipage}") scaled Echelle,A);
    fi;
    else:
    if Multiplication:
    label.llft(btex $\times$ etex scaled Echelle,A);
    else:
    label.llft(btex $+$ etex scaled Echelle,A);
    fi;
    fi;
    labeloffset:=labeloffset/2;
    vardef Vertical(text t)=
    n:=0;
    for p_=t:
    label.lft(TEX(p_) scaled Echelle,A+(0,n*Largeur+Largeur/2));
    n:=n+1;
    endfor;
    enddef;
    vardef Horizontal(text t)=
    n:=0;
    for p_=t:
    label.bot(TEX(p_) scaled Echelle,A+(n*Largeur+Largeur/2,0));
    n:=n+1;
    endfor;
    enddef;
    labeloffset:=labeloffset*4;
    Vertical(#1);
    Horizontal(#2);
  \end{mplibcode}
  \else%
  \begin{mpost}[mpsettings={Largeur=\useKV[ClesPQuatre]{Largeur};Largeur=\useKV[ClesPQuatre]{Largeur};LargeurUn=\useKV[ClesPQuatre]{LargeurUn};Echelle=\useKV[ClesPQuatre]{Echelle};color fond;fond=\useKV[ClesPQuatre]{Couleur};boolean Libre,Multiplication,Texte;Libre:=\useKV[ClesPQuatre]{Libre};Multiplication=\useKV[ClesPQuatre]{Multiplication};Texte:=\useKV[ClesPQuatre]{Texte};if Texte:string Consignes;Consignes=\useKV[ClesPQuatre]{Consignes};fi;}]
    % On calcule le nombre de cases
    nchauteur:=0;
    for p_=#1:
    nchauteur:=incr nchauteur;
    endfor;
    nclargeur:=0;
    for p_=#2:
    nclargeur:=incr nclargeur;
    endfor;
    if Libre=false:
    nchauteur:=7;
    nclargeur:=7;
    fi;
    %On affiche
    pair A,B,C,D,H[],V[],M[][];
    A=(0,0);
    B-A=Largeur*(nclargeur,0);
    C-B=Largeur*(0,nchauteur);
    D-C=A-B;
    fill polygone(A,B,C,D) withcolor fond;
    trace polygone(A,B,C,D);
    for k=0 upto (nclargeur-1):
    for l=0 upto (nchauteur-1):
    M[k][l]=A+0.5*(Largeur,Largeur)+k*(Largeur,0)+l*(0,Largeur);
    fill cercles(M[k][l],0.4*Largeur) withcolor blanc;
    trace cercles(M[k][l],0.4*Largeur);
    endfor;
    endfor;
    labeloffset:=labeloffset*2;
    if Libre:
    if Texte:
    label.llft(LATEX("\begin{minipage}{"&decimal(LargeurUn)&"pt}"&Consignes&"\end{minipage}") scaled Echelle,A);
    fi;
    else:
    if Multiplication:
    label.llft(btex $\times$ etex scaled Echelle,A);
    else:
    label.llft(btex $+$ etex scaled Echelle,A);
    fi;
    fi;
    labeloffset:=labeloffset/2;
    vardef Vertical(text t)=
    n:=0;
    for p_=t:
    label.lft(LATEX(p_) scaled Echelle,A+(0,n*Largeur+Largeur/2));
    n:=n+1;
    endfor;
    enddef;
    vardef Horizontal(text t)=
    n:=0;
    for p_=t:
    label.bot(LATEX(p_) scaled Echelle,A+(n*Largeur+Largeur/2,0));
    n:=n+1;
    endfor;
    enddef;
    labeloffset:=labeloffset*4;
    Vertical(#1);
    Horizontal(#2);
  \end{mpost}
  \fi%
}%

%%%
% Billard
%%%
\setKVdefault[ClesBillard]{Longueur=8cm,Largeur=5cm,Solution=false,Angle=70,Depart=0.5,Vrai=false}

\NewDocumentCommand\Billard{o m}{%
  \useKVdefault[ClesBillard]%
  \setKV[ClesBillard]{#1}%
  \ifboolKV[ClesBillard]{Solution}{%
    \MPBillardSolution{#2}{\useKV[ClesBillard]{Depart}}{\useKV[ClesBillard]{Angle}}%
    }{%
      \MPBillard{#2}{\useKV[ClesBillard]{Depart}}{\useKV[ClesBillard]{Angle}}%
    }%
}%

\def\MPBillard#1#2#3{%
  \mplibcodeinherit{disable}%
  \begin{Geometrie}[CoinHD={(\useKV[ClesBillard]{Longueur}+2cm,\useKV[ClesBillard]{Largeur}+3cm)}]
    boolean Vrai;
    Vrai:=\useKV[ClesBillard]{Vrai};
    % On définit la liste des 25 lettres alphabétiques dans laquelle on choisit autant de lettres que la longueur du mot
    % On a retiré la lettre Q pour des questions d'alignements esthétiques.
    vardef ChoixLettre=
    save Lettre,choixalea;
    string Lettre;
    choixalea=floor(uniformdeviate(26)+1);
    if choixalea=1:
    Lettre="A";
    elseif choixalea=2:
    Lettre="B";
    elseif choixalea=3:
    Lettre="C";
    elseif choixalea=4:
    Lettre="D";
    elseif choixalea=5:
    Lettre="E";
    elseif choixalea=6:
    Lettre="F";
    elseif choixalea=7:
    Lettre="G";
    elseif choixalea=8:
    Lettre="H";
    elseif choixalea=9:
    Lettre="I";
    elseif choixalea=10:
    Lettre="J";
    elseif choixalea=11:
    Lettre="K";
    elseif choixalea=12:
    Lettre="L";
    elseif choixalea=13:
    Lettre="M";
    elseif choixalea=14:
    Lettre="N";
    elseif choixalea=15:
    Lettre="O";
    elseif choixalea=16:
    Lettre="P";
    elseif choixalea=17:
    Lettre="O";
    elseif choixalea=18:
    Lettre="R";
    elseif choixalea=19:
    Lettre="S";
    elseif choixalea=20:
    Lettre="T";
    elseif choixalea=21:
    Lettre="U";
    elseif choixalea=22:
    Lettre="V";
    elseif choixalea=23:
    Lettre="W";
    elseif choixalea=24:
    Lettre="X";
    elseif choixalea=25:
    Lettre="Y";
    elseif choixalea=26:
    Lettre="Z";
    fi;
    Lettre
    enddef;
    % On crée un Quick Sort
    def QS(expr ndeb,nfin)=
    begingroup
    save v,m,x;
    if ndeb<nfin:
      v:=l[cpt[ndeb]];
      m:=ndeb;
      for i=(ndeb+1) upto nfin:
	if l[cpt[i]]<v:
	  m:=m+1;
	  x:=cpt[m];cpt[m]:=cpt[i];cpt[i]:=x;
	fi
      endfor;
      x:=cpt[m];cpt[m]:=cpt[ndeb];cpt[ndeb]:=x;
      QS(ndeb,m-1);
      QS(m+1,nfin);
    fi
    endgroup
    enddef;
    % On définit le rectangle
    pair M[],Co,Intermed;
    M1=u*(1,2);
    M2-M1=(\useKV[ClesBillard]{Longueur},0);
    M3-M2=(0,\useKV[ClesBillard]{Largeur});
    M4-M3=M1-M2;
    Co=iso(M1,M3);
    path rec,cote[];
    rec=polygone(M1,M2,M3,M4);
    cote1=segment(M1,M2);
    cote2=segment(M2,M3);
    cote3=segment(M3,M4);
    cote4=segment(M4,M1);
    trace rec;
    pair Pt[],FauxPt[];
    nbfaux=0;
    l1=#2;
    Pt[1]=point(l1) of rec;
    angleref=#3;
    if l1>3:
    angledepart=90+angleref;
    Pt[2]=demidroite(Pt[1],rotation(M1,Pt1,angledepart)) intersectionpoint (subpath(0,3) of rec);
    dotlabel.lft(TEX(substring(0,1) of #1),Pt[1]);
    elseif l1>2:
    angledepart=180+angleref;
    Pt[2]=demidroite(Pt[1],rotation(M4,Pt1,angledepart)) intersectionpoint ((subpath(3,4) of rec)--(subpath(0,2) of rec));
    dotlabel.top(TEX(substring(0,1) of #1),Pt[1]);
    elseif l1>1:
    angledepart=angleref-90;
    Pt[2]=demidroite(Pt[1],rotation(M3,Pt1,angledepart)) intersectionpoint ((subpath(2,4) of rec)--(subpath(0,1) of rec));
    dotlabel.rt(TEX(substring(0,1) of #1),Pt[1]);
    else:
    angledepart=angleref;
    Pt[2]=demidroite(Pt[1],rotation(M2,Pt1,angledepart)) intersectionpoint (subpath(1,4) of rec);
    dotlabel.bot(TEX(substring(0,1) of #1),Pt[1]);
    fi;
    tourne=90;
    numeric Blong;
    BLong:=length #1;
    % Détermination des points.
    if Vrai:
    for k=3 upto BLong:
    Intermed:=symetrie(Pt[k-2],Pt[k-1],Pt[k-1]+M2-M3);
    if (demidroite(1/1000[Pt[k-1],Intermed],Intermed) intersectiontimes rec)<>(-1,-1):
    Pt[k]:=demidroite(1/1000[Pt[k-1],Intermed],Intermed) intersectionpoint rec;
    else:
    Intermed:=symetrie(Pt[k-2],Pt[k-1],Pt[k-1]+M1-M2);
    Pt[k]:=demidroite(1/1000[Pt[k-1],Intermed],Intermed) intersectionpoint rec;
    fi;
    endfor;
    else:
    for k=3 upto BLong:
    Intermed:=rotation(Pt[k-2],Pt[k-1],tourne);
    if (demidroite(1/1000[Pt[k-1],Intermed],Intermed) intersectiontimes rec)<>(-1,-1):
    Pt[k]:=demidroite(1/1000[Pt[k-1],Intermed],Intermed) intersectionpoint rec;
    else:
    Intermed:=rotation(Pt[k-2],Pt[k-1],-tourne);
    Pt[k]:=demidroite(1/1000[Pt[k-1],Intermed],Intermed) intersectionpoint rec;
    fi;
    endfor;
    fi;
    % Ajout des faux points
    path SPath[];
    cpt[1]:=1;
    cpt[BLong+1]:=BLong+1;
    l[BLong+1]:=4;
    for k=2 upto BLong:
    SPath[k]=rec cutafter demidroite(Co,Pt[k]);
    l[k]=arclength SPath[k];
    l[k]:=arctime l[k] of rec;
    cpt[k]:=k;
    endfor;
    QS(1,BLong+1);
    for k=2 upto BLong+1:
    if l[cpt[k]]-l[cpt[k-1]]>0.3:
    nbfaux:=nbfaux+1;
    FauxPt[nbfaux]=point(l[cpt[k-1]]+0.1) of rec;
    nbfaux:=nbfaux+1;
    FauxPt[nbfaux]=point(l[cpt[k]]-0.1) of rec;
    fi;
    endfor;
    drawoptions();
    % Tracés
    drawarrow Pt[1]--(Pt[1]+1.5cm*unitvector(Pt[2]-Pt[1])) withpen pencircle scaled 1.25;
    % Labelisation
    for k=2 upto BLong:
    if (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[1])<>(-1,-1):
    dotlabel.bot(TEX(substring(k-1,k) of #1),Pt[k]);
    elseif (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[2])<>(-1,-1):
    dotlabel.rt(TEX(substring(k-1,k) of #1),Pt[k]);
    elseif (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[3])<>(-1,-1):
    dotlabel.top(TEX(substring(k-1,k) of #1),Pt[k]);
    elseif (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[4])<>(-1,-1):
    dotlabel.lft(TEX(substring(k-1,k) of #1),Pt[k]);
    fi;
    endfor;
    for k=1 upto nbfaux:
    if (demidroite(Co,FauxPt[k]) intersectiontimes cote[1])<>(-1,-1):
    dotlabel.bot(TEX(ChoixLettre),FauxPt[k]);
    elseif (demidroite(Co,FauxPt[k]) intersectiontimes cote[2])<>(-1,-1):
    dotlabel.rt(TEX(ChoixLettre),FauxPt[k]);
    elseif (demidroite(Co,FauxPt[k]) intersectiontimes cote[3])<>(-1,-1):
    dotlabel.top(TEX(ChoixLettre),FauxPt[k]);
    elseif (demidroite(Co,FauxPt[k]) intersectiontimes cote[4])<>(-1,-1):
    dotlabel.lft(TEX(ChoixLettre),FauxPt[k]);
    fi;
    endfor;
    picture Reponse;
    Reponse=image(
    trace segment((0,0),(7*BLong*mm-2mm,0)) dashed dashpattern(on5mm off2mm);
    );
    trace Reponse shifted((xpart(Co),5mm)-center Reponse);    
  \end{Geometrie}%
}%

\def\MPBillardSolution#1#2#3{%
  \mplibcodeinherit{enable}%
  \begin{mplibcode}%
    Figure(0,0,\useKV[ClesBillard]{Longueur}+2cm,\useKV[ClesBillard]{Largeur}+3cm);
    trace rec;
    % Tracés
    drawarrow Pt[1]--(Pt[1]+1.5cm*unitvector(Pt[2]-Pt[1])) withpen pencircle scaled 1.25;
    for k=1 upto BLong-1:
    trace segment(Pt[k],Pt[k+1]);
    endfor;
    if Vrai=false:
    for k=2 upto BLong-1:
    trace codeperp(Pt[k-1],Pt[k],Pt[k+1],5);
    endfor;
    fi;
    % Labelisation
    if l1>3:
    dotlabel.lft(TEX(substring(0,1) of #1),Pt[1]);
    elseif l1>2:
    dotlabel.top(TEX(substring(0,1) of #1),Pt[1]);
    elseif l1>1:
    dotlabel.rt(TEX(substring(0,1) of #1),Pt[1]);
    else:
    dotlabel.bot(TEX(substring(0,1) of #1),Pt[1]);
    fi;
    for k=2 upto BLong:
    if (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[1])<>(-1,-1):
    dotlabel.bot(TEX(substring(k-1,k) of #1),Pt[k]);
    elseif (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[2])<>(-1,-1):
    dotlabel.rt(TEX(substring(k-1,k) of #1),Pt[k]);
    elseif (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[3])<>(-1,-1):
    dotlabel.top(TEX(substring(k-1,k) of #1),Pt[k]);
    elseif (demidroite(1/1000[Pt[k-1],Pt[k]],Pt[k]) intersectiontimes cote[4])<>(-1,-1):
    dotlabel.lft(TEX(substring(k-1,k) of #1),Pt[k]);
    fi;
    endfor;
    trace Reponse shifted((xpart(Co),5mm)-center Reponse);
    % On affiche les lettres de la réponse.
    for k=1 upto BLong:
    label.top(TEX(substring(k-1,k) of #1),((xpart(Co),5mm)-center Reponse)+(k-1)*(7mm,0)+(2.5mm,0));
    endfor;
  \end{mplibcode}%
  \mplibcodeinherit{disable}%
}%

%%%
% Représenter un entier
%%%
\setKVdefault[ClesREntier]{Echelle=1,Unite=false,Compact=false,Impression=false,ListeCouleurs={Tomato,LightSteelBlue,LightGreen,Cornsilk}}%

\newcommand\RepresenterEntier[2][]{%
  \useKVdefault[ClesREntier]%
  \setKV[ClesREntier]{#1}%
  \ifboolKV[ClesREntier]{Unite}{%
    \begin{Geometrie}[TypeTrace="Espace",CoinBG={u*(-10,-10)}]
      Echelle=\useKV[ClesREntier]{Echelle};
      Initialisation(5,30,15,50*Echelle);
      color A,B,C,D,E,F,G,H;
      pointilles:="non";
      trace Pave(A,B,C,D,E,F,G,H)(0.1,0.1,0.1);
    \end{Geometrie}
  }{%
    % On décompose le nombre
    \StrLen{#2}[\LongueurNombreEntier]%
    \xdef\FooListeEntier{}
    \xintFor* ##1 in{\xintSeq{1}{\LongueurNombreEntier}}\do{%
      \StrChar{#2}{##1}[\ChiffreAAjouter]
      \xdef\FooListeEntier{\FooListeEntier \ChiffreAAjouter,}
    }
    \setsepchar{,}\ignoreemptyitems
    \readlist*\ListeDesChiffres{\FooListeEntier}%
    \xdef\ListeAvantCouleurs{\useKV[ClesREntier]{ListeCouleurs}}%
    \readlist*\ListeCouleurEntier{\ListeAvantCouleurs}%
    \xintifboolexpr{\LongueurNombreEntier==4}{%
      \xdef\NombreMilliers{\ListeDesChiffres[1]}%
      \xdef\NombreCentaines{\ListeDesChiffres[2]}%
      \xdef\NombreDizaines{\ListeDesChiffres[3]}%
      \xdef\NombreUnites{\ListeDesChiffres[4]}%
    }{%
      \xintifboolexpr{\LongueurNombreEntier==3}{%
        \xdef\NombreMilliers{0}%
        \xdef\NombreCentaines{\ListeDesChiffres[1]}%
        \xdef\NombreDizaines{\ListeDesChiffres[2]}%
        \xdef\NombreUnites{\ListeDesChiffres[3]}%
      }{%
        \xintifboolexpr{\LongueurNombreEntier==2}{%
          \xdef\NombreMilliers{0}%
          \xdef\NombreCentaines{0}%
          \xdef\NombreDizaines{\ListeDesChiffres[1]}%
          \xdef\NombreUnites{\ListeDesChiffres[2]}%
        }{%
          \xdef\NombreMilliers{0}%
          \xdef\NombreCentaines{0}%
          \xdef\NombreDizaines{0}%
          \xdef\NombreUnites{\ListeDesChiffres[1]}%
        }%
      }%
    }%
    \begin{Geometrie}[TypeTrace="Espace",CoinBG={u*(-10,-10)},CoinHD={u*(20,20)}]
      Echelle=\useKV[ClesREntier]{Echelle};
      NM=\NombreMilliers;
      NC=\NombreCentaines;
      ND=\NombreDizaines;
      NU=\NombreUnites;
      color ColorEntier[];
      ColorEntier1=\ListeCouleurEntier[1];
      ColorEntier2=\ListeCouleurEntier[2];
      ColorEntier3=\ListeCouleurEntier[3];
      ColorEntier4=\ListeCouleurEntier[4];
      boolean Compact,Print;
      Compact=\useKV[ClesREntier]{Compact};
      Print=\useKV[ClesREntier]{Impression};
      Initialisation(5,30,15,50*Echelle);
      color A,B,C,D,E,F,G,H;
      picture TypePave[];
      TypePave0=image(
      trace Pave(A,B,C,D,E,F,G,H)(1,1,1);
      currentpicture:=nullpicture;
      remplis polygone(A,B,C,H,E,F) withcolor if Print : blanc else: ColorEntier1 fi;
      for k=0 upto 10:
      trace chemin((k/10)[A,B],(k/10)[F,G],(k/10)[E,H]);
      endfor;
      for k=0 upto 10:
      trace chemin((k/10)[B,C],(k/10)[G,H],(k/10)[F,E]);
      endfor;
      for k=0 upto 10:
      trace chemin((k/10)[A,F],(k/10)[B,G],(k/10)[C,H]);
      endfor;
      );
      color A,B,C,D,E,F,G,H;
      TypePave1=image(
      trace Pave(A,B,C,D,E,F,G,H)(0.1,1,1);
      currentpicture:=nullpicture;
      remplis polygone(A,B,C,H,E,F) withcolor if Print : blanc else: ColorEntier2 fi;
      trace chemin(C,H,E);
      for k=0 upto 10:
      trace chemin((k/10)[A,B],(k/10)[F,G],(k/10)[E,H]);
      endfor;
      for k=0 upto 10:
      trace chemin((k/10)[A,F],(k/10)[B,G],(k/10)[C,H]);
      endfor;
      );
      color A,B,C,D,E,F,G,H;
      TypePave2=image(
      trace Pave(A,B,C,D,E,F,G,H)(0.1,0.1,1);
      currentpicture:=nullpicture;
      remplis polygone(A,B,C,H,E,F) withcolor if Print : blanc else: ColorEntier3 fi;
      trace chemin(C,H,E);
      trace chemin(A,F,E);
      trace chemin(B,G,F);
      for k=0 upto 10:
      trace chemin((k/10)[A,F],(k/10)[B,G],(k/10)[C,H]);
      endfor;
      );
      color A,B,C,D,E,F,G,H;
      TypePave3=image(
      trace Pave(A,B,C,D,E,F,G,H)(0.1,0.1,0.1);
      currentpicture:=nullpicture;
      remplis polygone(A,B,C,H,E,F) withcolor if Print : blanc else: ColorEntier4 fi;
      trace chemin(C,H,E);
      trace chemin(A,F,E);
      trace chemin(A,B,C);
      trace chemin(F,G,H);
      trace chemin(B,G);
      );
      if Compact:
      for k=0 upto (\NombreMilliers-1):
      trace TypePave0 shifted ((Projette((k,0,0))-Projette((0,0,0))));
      endfor;
      for k=0 upto (\NombreCentaines-1):
      trace TypePave1 shifted ((Projette((0.1*k,1.5,0))-Projette((0,0,0))));
      endfor;
      for k=0 upto (\NombreDizaines-1):
      trace TypePave2 shifted ((Projette((0.1*k,3,0))-Projette((0,0,0))));
      endfor;
      for k=0 upto (\NombreUnites-1):
      trace TypePave3 shifted ((Projette((0,3.6,0.1*k))-Projette((0,0,0))));
      endfor;
      else:
      for k=0 upto (\NombreMilliers-1):
      trace TypePave0 shifted ((Projette((0,1.1*(k-1),0))-Projette((0,0,0))));
      endfor;
      for k=0 upto (\NombreCentaines-1):
      trace TypePave1 shifted ((Projette((0,1.1*\NombreMilliers+1.1*(k-1),0))-Projette((0,0,0))));
      endfor;
      for k=0 upto (\NombreDizaines-1):
      trace TypePave2 shifted ((Projette((0,1.1*\NombreMilliers+1.1*(\NombreCentaines-1)+0.2+0.2*(k-1),0))-Projette((0,0,0))));
      endfor;
      for k=0 upto (\NombreUnites-1):
      trace TypePave3 shifted ((Projette((0,1.1*\NombreMilliers+1.1*(\NombreCentaines-1)+0.2+0.2*(\NombreDizaines-1),0.2*(k)))-Projette((0,0,0))));
      endfor;
      fi;
    \end{Geometrie}
  }
}

% Gestion de l'aléatoire (pour la CAN)
\newcommand\ChoixAlea[4][]{%
  \ifx\bla#1\bla%
  \xdef#4{\fpeval{randint(#2,#3)}}%
  \else%
  \xdef#4{\fpeval{round(randint(#2,#3)+rand(),#1)}}%
  \fi%
}%

\def\VariableAlea#1#2{%
  \xdef#1{\fpeval{#2}}%
}%

% On bloque la graine de fabrication des nombres aléatoires.
\ExplSyntaxOn
\cs_new_eq:NN \PfCGraineAlea \sys_gset_rand_seed:n
\ExplSyntaxOff

%%%
% Course aux nombres
%%%
\RequirePackage{longtable}
% https://tex.stackexchange.com/questions/642775/when-displaying-a-datatool-database-with-dtldisplaylongdb-how-to-obtain-a-hor
% Patch éventuel à ajouter
%\makeatletter
%\expandafter\patchcmd\expandafter{\csname\string\DTLdisplaylongdb\endcsname}%
%         {\@dtl@resetdoamp\dtldisplaystarttab}%
%         {\dtldisplaystarttab\@dtl@resetdoamp}%
%         {\message{Patching succeeded.}}%
%         {\message{Patching failed.}}%
%\makeatother

\setKVdefault[ClesMathAlea]{NbQ=5,ChoixTables=2-9,ValeurMax=20,Classique,Trou=false,Melange=false,Multiple=2,Theme=false}%
\defKV[ClesMathAlea]{Trous=\setKV[ClesMathAlea]{Classique=false}\setKV[ClesMathAlea]{Trou}}%
\defKV[ClesMathAlea]{Melanges=\setKV[ClesMathAlea]{Classique=false}\setKV[ClesMathAlea]{Melange}}%

\newcommand\MathAlea[2][]{%
  \useKVdefault[ClesMathAlea]%
  \setKV[ClesMathAlea]{#1}%
  \input{#2}%
}%

\newcommand\CourseNombreTotalQuestions[1]{%
  \setKV[ClesCN]{TotalQ=#1}%
  \xdef\CNfoo{}%
  \xintFor* ##1 in{\xintSeq{1}{#1}}\do{%
    \xdef\CNfoo{\CNfoo ##1,}%
  }%
}%

\setKVdefault[ClesCN]{%
  Stretch=2.5,%Elasticité du tableau
  NbQ=5,%Nb de questions à poser
  RAZ=false,%Pour remettre à zéro le compteur des questions
  Ordre=false,%Pour mettre toutes les questions dans l'ordre des numéros
  Exercice=false,%Pour utiliser l'aléatoire des questions mais sans habillage particulier, autre que des \item
  Perso=false,%Pour utiliser un choix personnel des questions
  Lecture=false,%Pour différencier avec une lecture automatisée sur les numéros de fichiers
  Maitre=false,%Pour indiquer qu'on prend en compte ou pas les sous-dossiers
  Nom=false,%Pour afficher le nom des fichiers utilisés.
  Theme=false,%Pour afficher le theme travaillé dans les fichiers utilisés (à retravailler).
  AMC=false,%
  Multi=false,%
  CAN=false,%Pour compléter la case réponse.
  CoefQ=0.4,%Coefficient multiplication de \linewidth pour la colonne question
  CoefR=0.35,%Coefficient multiplication de \linewidth pour la colonne réponse
  CoefJ=0.15,%Coefficient multiplication de \linewidth pour la colonne jury
}%
\defKV[ClesCN]{Liste=\setKV[ClesCN]{Perso=true}\setKV[ClesCN]{Lecture}}%
\defKV[ClesCN]{Dossier=\setKV[ClesCN]{Lecture}}%
\defKV[ClesCN]{Debut=\setKV[ClesCN]{RAZ}}%
\setsepchar[*]{,*/}%
\readlist*\ListeMotsCAN{La moitié de /2,Le double de /1,Le triple de /1, Le tiers de /3,Le nombre dix fois plus grand que /1,Le nombre cent fois plus grand que /1,Le nombre mille fois plus grand que /1,Le nombre dix fois plus petit que /10,Le nombre cent fois plus petit que /100,Le nombre mille fois plus petit que /1000}%
\readlist*\ListeMulAstucieuxCAN{50/2,25/4,20/5}%
\readlist*\ListeLieuxObjetsCAN{boulangerie/pains au chocolat/un pain au chocolat,boulangerie/cookies/un cookie,boulangerie/brioches/une brioche,piscine/entrées/une entrée,boucherie/saucisses/une saucisse,boucherie/cuisses de poulet/une cuisse de poulet}%
\readlist*\ListeNomsCAN{Aude/Elle/d'Aude,Bernard/Il/de Bernard,Céline/Elle/de Céline,Daniel/Il/de Daniel,\'Elise/Elle/d'\'Elise,Fabien/Il/de Fabien,Gérard/Il/de Gérard,Hélène/Elle/d'Hélène,Ilies/Il/d'Ilies,Jasmine/Elle/de Jasmine,Kylian/Il/de Kylian,Laurent/Il/de Laurent,Mathilde/Elle/de Mathilde,Nina/Elle/de Nina,Octave/Il/d'Octave,Philippe/Il/de Philippe,Joachim/Il/de Joachim,Thérèse/Elle/de Thérèse,Nawel/Elle/de Nawel,Alexandre/Il/d'Alexandre,Maxence/Il/de Maxence,Sophie/Elle/de Sophie,Christophe/Il/de Christophe,Myriam/Elle/de Myriam,Nathalie/Elle/de Nathalie}%
\readlist*\ListeComposantStatCAN{voitures/un garage/Cross-over/Utilitaires/Berlines,fruits/une corbeille/Pommes/Oranges/Bananes,vêtements/une armoire/Pulls/T-shirts/Chemises,couverts/un tiroir/Fourchettes/Couteaux/Cuillères}%
\readlist*\ListeObjetsSymbolesCAN{fleurs/96,ciseaux/36,crayons/47,enveloppes/41}%uniquement avec pifont
\setsepchar{,}%
\readlist*\ListeObjetsCAN{bonbons,billes,jouets,fruits,biscuits,gâteaux,pommes,poires,pains au chocolat,cookies,croissants,muffins,brioches,saucisses,cuisses de poulet}%
\readlist*\ListePetitsObjetsCAN{bonbons,billes,biscuits,gommes,clous,vis}
\readlist*\ListeFruitsCAN{pommes,poires,abricots,cerises,fraises,framboises,noix,pêches,nectarines,myrtilles}
\readlist*\ListeSommetsCAN{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z}

\newcommand\ExtraitPetitsObjets[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListePetitsObjetsCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListePetitsObjetsCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \readlist*\PetitsObjetsMelanges{\faa}%
}%

\newcommand\ExtraitObjets[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListeObjetsCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListeObjetsCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \readlist*\ObjetsMelanges{\faa}%
}%

\newcommand\ExtraitSymboles[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListeObjetsSymbolesCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListeObjetsSymbolesCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\SymbolesMelanges{\faa}%
  \setsepchar{,}%
}%

\newcommand\ExtraitSommet[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListeSommetsCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListeSommetsCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \readlist*\SommetsMelanges{\faa}%
  \readlist*\PtAlea{\faa}%
}%

\newcommand\ExtraitFruit[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListeFruitsCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListeFruitsCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \readlist*\FruitsMelanges{\faa}%
}%

\newcommand\ExtraitNom[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListeNomsCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListeNomsCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\NomsMelanges{\faa}%
  \setsepchar{,}%
}%

\newcommand\ExtraitElements[1]{%
  \xdef\CANSGFoo{}%
  \foreachitem\compteur\in\ListeComposantStatCAN{%
    \xdef\CANSGFoo{\CANSGFoo \ListeComposantStatCAN[\compteurcnt],}%
  }%
  \MelangeListe{\CANSGFoo}{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\ElementsMelanges{\faa}%
  \setsepchar{,}%
}%

\newcounter{CNNumQ}%
\setcounter{CNNumQ}{1}%

\newcommand\CANNew{%
  \textcolor{Crimson}{\faCopy}%
}%

\newread\RecupNbFichiers
\newread\RecupSSDossiers
\newread\zzz
\def\zzpar{\par}%

\makeatletter
\def\app@exe{\write18}
% Recuperer les sous-dossiers
\def\RecupererSousDossiers#1{%#1 est le dossier contenant les fichiers can classés en sous-dossier
  \app@exe{rm -f RecapSSDossier.tmp ; ls -1 -I "*.tex" #1 > RecapSSDossier.tmp}%
  \immediate\openin\zzz=RecapSSDossier.tmp
  \loop%
  \read\zzz to \tmp%
  \ifx\tmp\zzpar\else%
  \xdef\CNFOOSSDossiers{\CNFOOSSDossiers \expandafter\detokenize\expandafter{\tmp},}%
  \fi%
  \ifeof\zzz\else%
  \repeat%
  \setsepchar{,}\ignoreemptyitems
  \readlist*\ListeSSDossiers{\CNFOOSSDossiers}
}

\def\RecupererFichierTeXSSDossier#1#2{%
  \openin\zzz="|ls #1/#2/*.tex"%
  \loop%
  \read\zzz to \tmp%
  \ifx\tmp\zzpar\else%
  \xdef\CNFOO{\CNFOO \expandafter\detokenize\expandafter{\tmp},}%
  \fi%
  \ifeof\zzz\else%
  \repeat%
}

\def\RecupererFichierTeXDossier#1{%
  \xdef\CNFOO{}%
  \openin\zzz="|ls #1/*.tex"
  \loop%
  \read\zzz to \tmp%
  \ifx\tmp\zzpar\else%
  \xdef\CNFOO{\CNFOO \expandafter\detokenize\expandafter{\tmp},}%
  \fi%
  \ifeof\zzz\else%
  \repeat%
}

\def\DefinirListeFichiers{%
  \setsepchar{,}\ignoreemptyitems%
  \readlist*\ListeFichiers{\CNFOO}%
}

\def\RecupererFichierTeXAllSSDossier#1{%
  \RecupererSousDossiers{#1}%
  \foreachitem\compteur\in\ListeSSDossiers{\RecupererFichierTeXSSDossier{#1}{\ListeSSDossiers[\compteurcnt]}}%
  \DefinirListeFichiers%
}

\def\RecupererFichierTeXAllDossier#1{%
  \RecupererFichierTeXDossier{#1}%
  \DefinirListeFichiers%
}

\def\RecupererFichierTeXComplet#1{%
  \RecupererFichierTeXDossier{#1}%
  \RecupererSousDossiers{#1}%
  \foreachitem\compteur\in\ListeSSDossiers{\RecupererFichierTeXSSDossier{#1}{\ListeSSDossiers[\compteurcnt]}}%
  \DefinirListeFichiers%
}

\def\RecupererFichierTeXSSDossierPerso#1{%
  \openin\zzz="|ls #1/*.tex"
  \loop%
  \read\zzz to \tmp%
  \ifx\tmp\zzpar\else%
  \xdef\CNFOO{\CNFOO \expandafter\detokenize\expandafter{\tmp},}%
  \fi%
  \ifeof\zzz\else%
  \repeat%
}

\makeatother

\newcommand\CNTheme[1]{}%
\newcommand\CNReponse{}%

\newlength{\PfCLargeurQuestion}%
\newlength{\PfCLargeurReponse}%
\newlength{\PfCLargeurJury}%

\NewDocumentCommand\CourseNombre{o m}{%
  \useKVdefault[ClesCN]%
  \setKV[ClesCN]{#1}%
  \ifboolKV[ClesCN]{Theme}{\renewcommand\CNTheme[1]{{\ttfamily Thème : ##1}\par}}{}%
  \ifboolKV[ClesCN]{RAZ}{%
    \setcounter{CNNumQ}{\useKV[ClesCN]{Debut}}%
  }{}%
  \setKV[ClesMathAlea]{NbQ=1}%
  \xdef\CNFOOSSDossiers{}%
  \xdef\CNFOO{}%
  \ifboolKV[ClesCN]{Lecture}{%
    \ifboolKV[ClesCN]{Perso}{%
      %      % Ici \useKV[ClesCN]{Liste}
      \xdef\CNFOOListePerso{\useKV[ClesCN]{Liste}}%
      %      % OK -> Là, normalement, c'est la liste des dossiers choisis par l'utilisateur : \CNFOOListePerso
      \setsepchar{,}%
      \readlist*\ListeDesSSDossiersPerso{\CNFOOListePerso}%
      %      % \par OK -> Là, normalement, c'est la liste des dossiers perso sous forme de liste : \showitems\ListeDesSSDossiersPerso[]%
      \foreachitem\compteur\in\ListeDesSSDossiersPerso{\RecupererFichierTeXSSDossierPerso{\ListeDesSSDossiersPerso[\compteurcnt]}}%
      \DefinirListeFichiers%
      %      % \par OK -> Là, enfin, normalement, c'est la liste des fichiers contenus dans les dossiers perso :
      %      % \showitems\ListeFichiers[]
    }{%
      \ifboolKV[ClesCN]{Maitre}{%
        %        % On récupère tous les fichiers can dans les sous-dossiers
        %        % et on construit une liste \ListeFichiers contenant les chemins des fichiers considérés.
        \RecupererFichierTeXComplet{\useKV[ClesCN]{Dossier}}%
      }{%
        %        % Là
        %        % On récupère seulement les fichiers can de ce dossier
        %        % et on consruit une liste \ListeFichiers contenant les chemins des fichiers considérés.
        \RecupererFichierTeXAllDossier{\useKV[ClesCN]{Dossier}}%
      }%
    }%
    %    % On crée la liste du nombre total de questions
    \xdef\CNfooListe{}%
    \xintFor* ##1 in{\xintSeq{1}{\ListeFichierslen}}\do{%
      \xdef\CNfooListe{\CNfooListe ##1,}%
    }%
    %    % \par OK -> normalement, on a la liste du nombre de questions : \CNfooListe
    % On règle maintenant les dimensions nécessaires.
    % \ifboolKV[ClesCN]{CAN}{
    \setlength{\PfCLargeurQuestion}{\useKV[ClesCN]{CoefQ}\linewidth}\setlength{\PfCLargeurReponse}{\useKV[ClesCN]{CoefR}\linewidth}\setlength{\PfCLargeurJury}{\useKV[ClesCN]{CoefJ}\linewidth}%
    %    % On affiche les questions :
    \ifboolKV[ClesCN]{Ordre}{%
      %        % soit dans un exercice
      \ifboolKV[ClesCN]{Exercice}{%
        %          % Attention le style de l'environnement est à choisir par l'utilisateur
        \xintFor* ##1 in {\xintSeq{1}{\ListeFichierslen}}\do{%
        \item\input{\ListeFichiers[##1]}%
        }%
      }{% Soit toutes les questions au format course
        \renewcommand{\arraystretch}{\useKV[ClesCN]{Stretch}}%
        \begin{longtable}{|c|p{\PfCLargeurQuestion}|>{\centering\arraybackslash}p{\PfCLargeurReponse}|p{\PfCLargeurJury}|}%
          \hhline{~---}%
          \multicolumn{1}{c|}{}&\cellcolor{gray!15}\centering\'Enoncé&\cellcolor{gray!15}\centering Réponse&\cellcolor{gray!15}\centering\arraybackslash Jury\\%
          \hline%
          \endhead%
          \xintFor* ##1 in {\xintSeq{1}{\ListeFichierslen}}\do{%
            \ttfamily{\theCNNumQ}\stepcounter{CNNumQ}&\xdef\CNReponse{}\input{\ListeFichiers[##1]}\ifboolKV[ClesCN]{Nom}{\par\hfill\footnotesize\ttfamily\ListeFichiers[##1]}{}&\ifboolKV[ClesCN]{CAN}{\CNReponse}{}&\\%
            \hline%
          }%
        \end{longtable}%
        \renewcommand{\arraystretch}{1}%
      }%
    }{%
      % On prévient l'utilisateur si le nb de questions est inférieur à NbQ
      \xintifboolexpr{\ListeFichierslen<\useKV[ClesCN]{NbQ}}{%
        \faExclamationCircle~Le nombre maximal de questions disponibles est inférieur au nombre de questions à afficher. Modifier la clé {\ttfamily NbQ} ou ajouter des questions dans le(s) répertoire(s).%
      }{%%On choisit NbQ questions parmi la liste de fichiers
        \MelangeListe{\CNfooListe}{\useKV[ClesCN]{NbQ}}%
        \setsepchar{,}\ignoreemptyitems%
        \readlist*\ListeCNQuestions{\faa}
        \ifboolKV[ClesCN]{Exercice}{%
          \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesCN]{NbQ}}}\do{%
          \item\xdef\Numerodelaquestionaposer{\ListeCNQuestions[##1]}\input{\ListeFichiers[\Numerodelaquestionaposer]}%
          }%
        }{% On les affiche
          \renewcommand{\arraystretch}{\useKV[ClesCN]{Stretch}}%
          \begin{longtable}{|c|p{\PfCLargeurQuestion}|>{\centering\arraybackslash}p{\PfCLargeurReponse}|p{\PfCLargeurJury}|}%
            \hhline{~---}%
            \multicolumn{1}{c|}{}&\cellcolor{gray!15}\centering\'Enoncé&\cellcolor{gray!15}\centering Réponse&\cellcolor{gray!15}\centering\arraybackslash Jury\\%
            \hline%
            \endhead%
            \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesCN]{NbQ}}}\do{%
              \ttfamily{\theCNNumQ}\stepcounter{CNNumQ}&\xdef\CNReponse{}\xdef\Numerodelaquestionaposer{\ListeCNQuestions[##1]}\input{\ListeFichiers[\Numerodelaquestionaposer]}\ifboolKV[ClesCN]{Nom}{\par\hfill\footnotesize\ttfamily\ListeFichiers[##1]}{}&\ifboolKV[ClesCN]{CAN}{\CNReponse}{}&\\
              \hline
            }%
          \end{longtable}%
          \renewcommand{\arraystretch}{1}%
        }%
      }%
    }%
  }{%
    \input{#2}
  }%
}%
% fin course aux nombres

%%%
% Frise temporelle
%%%
\setKVdefault[ClesFrise]{Longueur=8cm,Fleches=false,Ecart=5mm,Sup=false}%

\newtoks\toklistefrise%
\def\UpdatetoksFrise#1/#2/#3\nil{\addtotok\toklistefrise{"#1","#2","#3",}}%

\newcommand\Frise[2][]{%
  \useKVdefault[ClesFrise]%
  \setKV[ClesFrise]{#1}%
  \setsepchar[*]{,*/}\ignoreemptyitems%
  \readlist*\ListeTempo{#2}%
  \toklistefrise{}%
  \foreachitem\compteur\in\ListeTempo{\expandafter\UpdatetoksFrise\compteur\nil}
  \MPDessineFrise{\the\toklistefrise}%
}

\newcommand\MPDessineFrise[1]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    Longueur:=\useKV[ClesFrise]{Longueur};
    Ecart:=\useKV[ClesFrise]{Ecart};
    boolean Fleches;
    Fleches=\useKV[ClesFrise]{Fleches};
    boolean Sup;
    Sup=\useKV[ClesFrise]{Sup};
    pair A[],B;
    A0=(0,0);
    B-A0=(Longueur,0);
    n=0;
    for p_=#1:
    n:=n+1;
    endfor;
    for k=1 upto ((n div 3)-2):
    A[k]=(k/((n div 3)-1))[A0,B];
    endfor;
    A[(n div 3)-1]=B;
    if Sup:
      for k=0 upto ((n div 3)-1):
      trace (u*(0,-0.1)--u*(0,0.1)) shifted A[k];
      endfor;
      % on définit les points milieu des fleches
      path Fleche[];
      pair C[];
      for k=0 upto ((n div 3)-3):
      Fleche[k]=(A[k]{dir-30}..{dir30}A[k+1]) shifted((0,-Ecart));
      C[k]=point (0.5*length Fleche[k]) of Fleche[k];
      endfor;
      Fleche[(n div 3)-2]=%(A[(n div 3)-3]{dir-30}..{dir30}A[(n div 3)-1]) shifted((0,-Ecart));
      chemin(A[(n div 3)-3]+(0,-Ecart),A[(n div 3)-3]+(0,-4*Ecart),A[(n div 3)-1]+(0,-4*Ecart),A[(n div 3)-1]+(0,-Ecart));
      C[(n div 3)-1]=point (0.5*length Fleche[(n div 3)-2]) of Fleche[(n div 3)-2];
      Fleche[(n div 3)-1]=(A[(n div 3)-1]{dir-150}..{dir150}A[(n div 3)-2]) shifted((0,-Ecart));
      C[(n div 3)-2]=point (0.5*length Fleche[(n div 3)-1]) of Fleche[(n div 3)-1];
      % 
      maxx:=n;
      trace segment(A0,A[(n div 3)-2]);
      trace segment(A[(n div 3)-2],A[(n div 3)-1]) dashed evenly;
      n:=0;
      labeloffset:=labeloffset*2;
      for p_=#1:
      n:=n+1;
      if n<maxx+1:
      if (n mod 3)=1:
      label.top(TEX(""&p_&""),A[n div 3]);
      elseif (n mod 3)=2:
      label.top(TEX(""&p_&""),C[n div 3]);%
      elseif (n mod 3)=0:
      label.bot(TEX(""&p_&""),C[(n div 3)-1]);
      fi;
      fi;
      endfor;
      drawoptions();
      labeloffset:=labeloffset/2;
      if Fleches:
      for k=0 upto ((n div 3)-4):
      drawarrow Fleche[k];
      endfor;
      drawarrow Fleche[(n div 3)-1];
      drawarrow Fleche[(n div 3)-2];
      drawarrow (A[(n div 3)-1]{dir-150}..{dir150}A[(n div 3)-2]) shifted((0,-Ecart));
      for k=0 upto ((n div 3)-2):
      draw segment(A[k],A[k]+(0,-Ecart)) dashed evenly;
      endfor;
      draw segment(A[(n div 3)-1],A[(n div 3)-1]+(0,-Ecart)) dashed evenly;
      fi;
    %fin Sup
    else:
      for k=0 upto ((n div 3)-1):
      trace (u*(0,-0.1)--u*(0,0.1)) shifted A[k];
      endfor;
      % on définit les points milieu des fleches
      path Fleche[];
      pair C[];
      for k=0 upto ((n div 3)-2):
      Fleche[k]=(A[k]{dir-30}..{dir30}A[k+1]) shifted((0,-Ecart));
      C[k]=point (0.5*length Fleche[k]) of Fleche[k];
      endfor;
      maxx:=n;
      trace segment(A0,A[(n div 3)-1]);
      n:=0;
      labeloffset:=labeloffset*2;
      for p_=#1:
      n:=n+1;
      if n<maxx:
      if (n mod 3)=1:
      label.top(TEX(""&p_&""),A[n div 3]);
      elseif (n mod 3)=2:
      if (n div 3)<((maxx div 3)-1):label.top(TEX(""&p_&""),C[n div 3]);fi;
      elseif (n mod 3)=0:
      label.bot(TEX(""&p_&""),C[(n div 3)-1]);
      fi;
      fi;
      endfor;
      labeloffset:=labeloffset/2;
      if Fleches:
      for k=0 upto ((n div 3)-2):
      draw segment(A[k],A[k]+(0,-Ecart)) dashed evenly;
      drawarrow Fleche[k];
      endfor;
      draw segment(A[(n div 3)-1],A[(n div 3)-1]+(0,-Ecart)) dashed evenly;
      fi;
    fi;
  \end{mplibcode}
  \else
    \begin{mpost}[mpsettings={%
    Longueur:=\useKV[ClesFrise]{Longueur};
    Ecart:=\useKV[ClesFrise]{Ecart};
    boolean Fleches;
    Fleches=\useKV[ClesFrise]{Fleches};
    boolean Sup;
    Sup=\useKV[ClesFrise]{Sup};
    }]
    pair A[],B;
    A0=(0,0);
    B-A0=(Longueur,0);
    n=0;
    for p_=#1:
    n:=n+1;
    endfor;
    for k=1 upto ((n div 3)-2):
    A[k]=(k/((n div 3)-1))[A0,B];
    endfor;
    A[(n div 3)-1]=B;
    if Sup:
      for k=0 upto ((n div 3)-1):
      trace (u*(0,-0.1)--u*(0,0.1)) shifted A[k];
      endfor;
      % on définit les points milieu des fleches
      path Fleche[];
      pair C[];
      for k=0 upto ((n div 3)-3):
      Fleche[k]=(A[k]{dir-30}..{dir30}A[k+1]) shifted((0,-Ecart));
      C[k]=point (0.5*length Fleche[k]) of Fleche[k];
      endfor;
      Fleche[(n div 3)-2]=%(A[(n div 3)-3]{dir-30}..{dir30}A[(n div 3)-1]) shifted((0,-Ecart));
      chemin(A[(n div 3)-3]+(0,-Ecart),A[(n div 3)-3]+(0,-4*Ecart),A[(n div 3)-1]+(0,-4*Ecart),A[(n div 3)-1]+(0,-Ecart));
      C[(n div 3)-1]=point (0.5*length Fleche[(n div 3)-2]) of Fleche[(n div 3)-2];
      Fleche[(n div 3)-1]=(A[(n div 3)-1]{dir-150}..{dir150}A[(n div 3)-2]) shifted((0,-Ecart));
      C[(n div 3)-2]=point (0.5*length Fleche[(n div 3)-1]) of Fleche[(n div 3)-1];
      % 
      maxx:=n;
      trace segment(A0,A[(n div 3)-2]);
      trace segment(A[(n div 3)-2],A[(n div 3)-1]) dashed evenly;
      n:=0;
      labeloffset:=labeloffset*2;
      for p_=#1:
      n:=n+1;
      if n<maxx+1:
      if (n mod 3)=1:
      label.top(LATEX(""&p_&""),A[n div 3]);
      elseif (n mod 3)=2:
      label.top(LATEX(""&p_&""),C[n div 3]);%
      elseif (n mod 3)=0:
      label.bot(LATEX(""&p_&""),C[(n div 3)-1]);
      fi;
      fi;
      endfor;
      drawoptions();
      labeloffset:=labeloffset/2;
      if Fleches:
      for k=0 upto ((n div 3)-4):
      drawarrow Fleche[k];
      endfor;
      drawarrow Fleche[(n div 3)-1];
      drawarrow Fleche[(n div 3)-2];
      drawarrow (A[(n div 3)-1]{dir-150}..{dir150}A[(n div 3)-2]) shifted((0,-Ecart));
      for k=0 upto ((n div 3)-2):
      draw segment(A[k],A[k]+(0,-Ecart)) dashed evenly;
      endfor;
      draw segment(A[(n div 3)-1],A[(n div 3)-1]+(0,-Ecart)) dashed evenly;
      fi;
    %fin Sup
    else:
      for k=0 upto ((n div 3)-1):
      trace (u*(0,-0.1)--u*(0,0.1)) shifted A[k];
      endfor;
      % on définit les points milieu des fleches
      path Fleche[];
      pair C[];
      for k=0 upto ((n div 3)-2):
      Fleche[k]=(A[k]{dir-30}..{dir30}A[k+1]) shifted((0,-Ecart));
      C[k]=point (0.5*length Fleche[k]) of Fleche[k];
      endfor;
      maxx:=n;
      trace segment(A0,A[(n div 3)-1]);
      n:=0;
      labeloffset:=labeloffset*2;
      for p_=#1:
      n:=n+1;
      if n<maxx:
      if (n mod 3)=1:
      label.top(LATEX(""&p_&""),A[n div 3]);
      elseif (n mod 3)=2:
      if (n div 3)<((maxx div 3)-1):label.top(LATEX(""&p_&""),C[n div 3]);fi;
      elseif (n mod 3)=0:
      label.bot(LATEX(""&p_&""),C[(n div 3)-1]);
      fi;
      fi;
      endfor;
      labeloffset:=labeloffset/2;
      if Fleches:
      for k=0 upto ((n div 3)-2):
      draw segment(A[k],A[k]+(0,-Ecart)) dashed evenly;
      drawarrow Fleche[k];
      endfor;
      draw segment(A[(n div 3)-1],A[(n div 3)-1]+(0,-Ecart)) dashed evenly;
      fi;
    fi;
  \end{mpost}
  \fi
}

%%%
% Geometrie
%%%
\setKVdefault[Geometrie]{CoinBG={(0,0)},CoinHD={(10u,10u)},TypeTrace="Instruments"}%

\ifluatex
\NewDocumentEnvironment{Geometrie}{o +b}{%
  \useKVdefault[Geometrie]%
  \setKV[Geometrie]{#1}%
  \mplibforcehmode
  \begin{mplibcode}
    % input PfCMPFr;
    pair Coinbg,Coinhd;
    Coinbg=\useKV[Geometrie]{CoinBG};
    Coinhd=\useKV[Geometrie]{CoinHD};
    if \useKV[Geometrie]{TypeTrace}="Instruments":
    typetrace:="normal";
    elseif \useKV[Geometrie]{TypeTrace}="MainLevee":
    typetrace:="mainlevee";
    elseif \useKV[Geometrie]{TypeTrace}="Espace":
    typetrace:="3D";
    typerepre:="persp";
    fi;
    xa=xpart(Coinbg);
    xb=xpart(Coinhd);
    ya=ypart(Coinbg);
    yb=ypart(Coinhd);
    feuille(xa,ya,xb,yb);
    _tfig:=if (xb-xa)>(yb-ya): (xb-xa) else: (yb-ya) fi;
    _tfig:=2*_tfig;
    #2%
  \end{mplibcode}
}{}
\else
\NewDocumentEnvironment{Geometrie}{o +b}{%
  \useKVdefault[Geometrie]%
  \setKV[Geometrie]{#1}%
  \begin{mpost}[mpsettings={
      pair Coinbg,Coinhd;
      Coinbg=\useKV[Geometrie]{CoinBG};
      Coinhd=\useKV[Geometrie]{CoinHD};
      if \useKV[Geometrie]{TypeTrace}="Instruments":
      typetrace:="normal";
      elseif \useKV[Geometrie]{TypeTrace}="MainLevee":
      typetrace:="mainlevee";
      elseif \useKV[Geometrie]{TypeTrace}="Espace":
      typetrace:="3D";
      typerepre:="persp";
      fi;}
    ]%
    xa=xpart(Coinbg);
    xb=xpart(Coinhd);;
    ya=ypart(Coinbg);
    yb=ypart(Coinhd);
    feuille(xa,ya,xb,yb);
    _tfig:=if (xb-xa)>(yb-ya): (xb-xa) else: (yb-ya) fi;
    _tfig:=2*_tfig;
    #2%
  \end{mpost}
}{}
\fi%

%%%
% Smiley
%%% https://tex.stackexchange.com/questions/3695/smileys-in-latex/227226
\tikzset{face/.style={shape=circle,minimum size=4ex,shading=radial,outer sep=0pt, inner color=white!50!yellow,outer color= yellow!70!orange}}

\newcommand\emoticon[2][]{%
\scalebox{.5}{\begin{tikzpicture}
\node[face,#1,draw,thick] (emoticon) {};
%% The eyes are fixed.
\draw[fill=white] (-1ex,0ex) ..controls (-0.5ex,0.2ex)and(0.5ex,0.2ex)..(1ex,0.0ex) ..controls ( 1.5ex,1.5ex)and( 0.2ex,1.7ex)..(0ex,0.4ex) ..controls (-0.2ex,1.7ex)and(-1.5ex,1.5ex)..(-1ex,0ex)--cycle;
#2%
\end{tikzpicture}}%
}

\newcommand\pupils{
%% standard pupils
\fill[shift={(0.5ex,0.5ex)},rotate=80] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.5ex,0.5ex)},rotate=100] (0,0) ellipse (0.3ex and 0.15ex);}

\def\RKsmallsmile{%
\emoticon{%
\pupils
%% mouth
\draw[thick] (-0.5ex,-1ex)..controls (-0.25ex,-1.25ex)and(0.25ex,-1.25ex)..(0.5ex,-1ex);
}%\emoticon
}

\def\RKsmile{%
\emoticon{%
\pupils
\draw[thick] (-1ex,-1ex)..controls (-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKbigsmile{%
\emoticon{%
\pupils
%% mouth
\draw[thick] (-1.5ex,-0.5ex)..controls (-0.7ex,-1.7ex)and(0.7ex,-1.7ex)..(1.5ex,-0.5ex);
}%\emoticon
}

\def\RKsad{%
\emoticon{%
%% pupils
\fill[shift={( 0.5ex,0.5ex)},rotate=90] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.5ex,0.5ex)},rotate=90] (0,0) ellipse (0.3ex and 0.15ex);
%% mouth
\draw[thick] (-1ex,-1ex)..controls(-0.5ex,-0.5ex)and(0.5ex,-0.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKneutral{%
\emoticon{%
%% pupils
\fill[shift={( 0.5ex,0.5ex)},rotate=90] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.5ex,0.5ex)},rotate=90] (0,0) ellipse (0.3ex and 0.15ex);
%% mouth
\draw[thick] (-0.5ex,-1ex)--(0.5ex,-1ex);
}%\emoticon
}

\def\RKconfused{%
\emoticon{%
\pupils
%% mouth
\draw[thick] (-1ex,-0.75ex)--(1ex,-1.25ex);
}%\emoticon
}

\def\RKsexy{%
\emoticon{%
\pupils
%% mouth
\draw[very thick,red,line cap=round] (-1ex,-1ex)..controls (-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
%% eyelashes
\draw (0.60ex,1.20ex)--(0.60ex,1.60ex)
  (0.85ex,1.25ex)--(0.95ex,1.45ex)
  (1.00ex,1.00ex)--(1.20ex,1.10ex)
  (0.35ex,1.15ex)--(0.25ex,1.35ex)
  (-0.60ex,1.20ex)--(-0.60ex,1.60ex)
  (-0.85ex,1.25ex)--(-0.95ex,1.45ex)
  (-1.00ex,1.00ex)--(-1.20ex,1.10ex)
  (-0.35ex,1.15ex)--(-0.25ex,1.35ex);
}%\emoticon
}

\def\RKangry{%
\emoticon{%
%% pupils
\fill[shift={( 0.5ex,0.5ex)},rotate=90] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.5ex,0.5ex)},rotate=90] (0,0) ellipse (0.3ex and 0.15ex);
%% mouth
\draw[thick] (-1ex,-1ex)..controls(-0.5ex,-0.5ex)and(0.5ex,-0.5ex)..(1ex,-1ex);
%% eyebrows
\draw[thick] (0.2ex,1.15ex)--(0.5ex,1.6ex)(-0.2ex,1.15ex)--(-0.5ex,1.6ex);
}%\emoticon
}

\def\RKlookup{%
\emoticon{%
%% pupils
\fill[shift={( 0.5ex,1.05ex)},rotate= 80] (0,0) ellipse (0.2ex and 0.2ex);
\fill[shift={(-0.5ex,1.05ex)},rotate=100] (0,0) ellipse (0.2ex and 0.2ex);
%% mouth
\draw[thick] (-1ex,-1ex)..controls(-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKlookdown{%
\emoticon{%
%% pupils
\fill[shift={( 0.5ex,0.3ex)},rotate= 80] (0,0) ellipse (0.2ex and 0.2ex);
\fill[shift={(-0.5ex,0.3ex)},rotate=100] (0,0) ellipse (0.2ex and 0.2ex);
%% mouth
\draw[thick] (-1ex,-1ex)..controls(-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKlookleft{%
\emoticon{%
%% pupils
\fill[shift={( 0.25ex,0.5ex)},rotate=100] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.95ex,0.5ex)},rotate=100] (0,0) ellipse (0.3ex and 0.15ex);
%% mouth
\draw[thick] (-1ex,-1ex)..controls(-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKlookright{%
\emoticon{%
%% pupils
\fill[shift={( 0.95ex,0.5ex)},rotate=80] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.25ex,0.5ex)},rotate=80] (0,0) ellipse (0.3ex and 0.15ex);
%% mouth
\draw[thick] (-1.0ex,-1ex)..controls(-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKblush{%
\emoticon{%
\pupils
%% mouth
\draw[thick] (-0.5ex,-1ex)..controls (-0.25ex,-1.25ex)and(0.25ex,-1.25ex)..(0.5ex,-1ex);
%% blush
\shade[shading=radial,inner color=white!50!red,outer color= yellow!80!orange] ( 1ex,-0.5ex) circle (0.4ex);
\shade[shading=radial,inner color=white!50!red,outer color= yellow!80!orange] (-1ex,-0.5ex) circle (0.4ex);
}%\emoticon
}

\def\RKalmostcrying{%
\emoticon{%
%% pupils
\fill[shift={( 0.5ex,0.5ex)},rotate=105] (0,0) ellipse (0.3ex and 0.15ex);
\fill[shift={(-0.5ex,0.5ex)},rotate= 75] (0,0) ellipse (0.3ex and 0.15ex);
%% mouth
\draw[thick] (-1ex,-1ex)..controls
(-0.5ex,-0.8ex)and(0.5ex,-0.8ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKmartian{%
\emoticon[inner color=white!50!green,outer color=green!70!red]{%
\pupils
%% mouth
\draw[thick] (-1ex,-1ex)..controls
(-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
}%\emoticon
}

\def\RKdevilish{%
\raisebox{-0.6ex}[0ex][0ex]{%
\emoticon[inner color=white!50!red,outer color= red!70!red!90!black]{%
\pupils
%% mouth
\draw[thick,line cap=round] (-1ex,-1ex)..controls (-0.5ex,-1.5ex)and(0.5ex,-1.5ex)..(1ex,-1ex);
%% tail
\draw[line width=0.45ex,-stealth,black] (emoticon.330)--++(330:0.01ex)..controls (3ex,-3ex)and(3.5ex,1ex)..(4.25ex,-3ex);
\draw[line width=0.27ex,-stealth,red!90!black] (emoticon.330)--++(330:0.01ex)..controls (3ex,-3ex)and(3.5ex,1ex)..(4.22ex,-2.8ex);
%% horns
\draw[fill] (emoticon.80)..controls ( 0.6ex,2.4ex)..( 1ex,2.5ex)..controls ( 0.8ex,2.3ex)..(emoticon.70);
\draw[fill] (emoticon.100)..controls (-0.6ex,2.4ex)..(-1ex,2.5ex)..controls (-0.8ex,2.3ex)..(emoticon.110); 
\draw[thick] (0,0) circle (2ex);
}%\emoticon
}%\raisebox
}

%%%%%
% Enquête
%%%%%
\setKVdefault[ClesEnquete]{Perso=Qui ?,Objet=Quoi ?,Lieu=Où ?,Largeur=4.5cm}

\newcommand\Enquete[1][]{%
  \useKVdefault[ClesEnquete]%
  \setKV[ClesEnquete]{#1}%
}

\newcommand\ListePersonnages[1]{%
  \setsepchar{§}%
  \readlist*\RetiensListePersonnages{#1}%
  \setsepchar{,}%
}

\newcommand\ListeObjets[1]{%
  \setsepchar{§}%
  \readlist*\RetiensListeObjets{#1}%
  \setsepchar{,}%
}

\newcommand\ListeLieux[1]{%
  \setsepchar{§}%
  \readlist*\RetiensListeLieux{#1}%
  \setsepchar{,}%
}

\newcommand\MelangeListe[2]{%
  % #1 Liste à mélanger
  % #2 Nombre d'éléments à conserver
  \setsepchar{,}\ignoreemptyitems%
  \readlist*\ListeInter{#1}%
  \xdef\faa{}% Liste construite
  \xdef\fii{}% Liste détruite
  % on crée les #2 premieres solutions.
  \xintFor* ##1 in {\xintSeq{1}{#2}}\do{%
    \xintifboolexpr{\ListeInterlen>1}{%
      \xdef\Alea{\fpeval{randint(\ListeInterlen)}}%
      \xdef\faa{\faa \ListeInter[\Alea],}%
      \xdef\fii{}%
      \xintFor* ##2 in {\xintSeq{1}{\ListeInterlen}}\do{%
        \xintifboolexpr{##2 == \Alea}{%
        }{%
          \xdef\fii{\fii \ListeInter[##2],}%
        }%
      }%
    }{%
      \xdef\faa{\faa \ListeInter[1]}%
    }%
    \readlist*\ListeInter{\fii}%
  }%
  \reademptyitems%
}%

\newcommand\ListeQuestions[1]{%
  \setsepchar[*]{§*/}%
  \readlist*\RetiensListeQuestions{#1}
  % On crée la liste des numéros des questions
  \xdef\foo{}%
  \xintFor* ##1 in {\xintSeq{1}{\RetiensListeQuestionslen}}\do{%
    \xdef\foo{\foo ##1,}%
  }%
  % Mélange des questions
  % on crée les 6 premieres solutions.
  \MelangeListe{\foo}{\fpeval{\RetiensListePersonnageslen}}%
  \readlist*\ListeMelangeePersonnages{\faa}%
  \readlist*\ListeRestante{\fii}%\ListeRestante[]
  \MelangeListe{\faa}{\fpeval{\RetiensListePersonnageslen-1}}%
  \readlist*\ListefuuPerso{\faa}%
  % on crée les 6 solutions suivantes.
  \xdef\fuuu{}%
  \foreachitem\compteur\in\ListeRestante{\xdef\fuuu{\fuuu,\ListeRestante[\compteurcnt]}}%
  \MelangeListe{\fuuu}{\fpeval{\RetiensListeObjetslen}}%
  \readlist*\ListeMelangeeObjets{\faa}%
  \readlist*\ListeRestante{\fii}%
  \MelangeListe{\faa}{\fpeval{\RetiensListeObjetslen-1}}%
  \readlist*\ListefuuObjets{\faa}%
  % on crée les dernieres solutions.
  \xdef\fuuu{}%
  \foreachitem\compteur\in\ListeRestante{\xdef\fuuu{\fuuu,\ListeRestante[\compteurcnt]}}%
  \MelangeListe{\fuuu}{\fpeval{\RetiensListeLieuxlen}}
  \readlist*\ListeMelangeeLieux{\faa}%
  %% \readlist*\ListeRestante{\fii}%
  \MelangeListe{\faa}{\fpeval{\RetiensListeLieuxlen-1}}%
  \readlist*\ListefuuLieux{\faa}%
  % --------------
  % Liste des questions sauvegardees
  \xdef\fuu{}%
  \foreachitem\compteur\in\ListefuuPerso{\xdef\fuu{\fuu,\ListefuuPerso[\compteurcnt]}}%
  \foreachitem\compteur\in\ListefuuObjets{\xdef\fuu{\fuu,\ListefuuObjets[\compteurcnt]}}%
  \foreachitem\compteur\in\ListefuuLieux{\xdef\fuu{\fuu,\ListefuuLieux[\compteurcnt]}}%
  \ignoreemptyitems\setsepchar{,}%
  \MelangeListe{\fuu}{\fpeval{\RetiensListePersonnageslen+\RetiensListeObjetslen+\RetiensListeLieuxlen-3}}%
  \readlist*\ListeMelangeeQuestions{\faa}%
  \reademptyitems%
}%

\newcommand\AffichageQuestions{%
  \begin{enumerate}
    \xintFor* ##1 in {\xintSeq{1}{\fpeval{\RetiensListePersonnageslen+\RetiensListeObjetslen+\RetiensListeLieuxlen-3}}}\do{%
    \item\xdef\Compteur{\ListeMelangeeQuestions[##1]}\RetiensListeQuestions[\Compteur,1]
    }
  \end{enumerate}
}

\newcommand\AffichageTableau{%
  \begin{tabular}{|>{\PfCTBstrut$\square$~}m{\useKV[ClesEnquete]{Largeur}}|}
    \hline
    \rowcolor{gray!15}\multicolumn{1}{|c|}{\PfCTBstrut\useKV[ClesEnquete]{Perso}}\\
    \hline
    \xintFor* ##1 in {\xintSeq{1}{\RetiensListePersonnageslen}}\do{%
    \RetiensListePersonnages[##1]\xdef\PfCCompteurMelange{\ListeMelangeePersonnages[##1]} $\star$ \RetiensListeQuestions[\PfCCompteurMelange,2]\\
    }
    % 
    \hline
    \rowcolor{gray!15}\multicolumn{1}{|c|}{\PfCTBstrut\useKV[ClesEnquete]{Objet}}\\
    \hline
    \xintFor* ##1 in {\xintSeq{1}{\RetiensListeObjetslen}}\do{%
    \RetiensListeObjets[##1]\xdef\PfCCompteurMelange{\ListeMelangeeObjets[##1]} $\star$ \RetiensListeQuestions[\PfCCompteurMelange,2]\\
    }
    % 
    \hline
    \rowcolor{gray!15}\multicolumn{1}{|c|}{\PfCTBstrut\useKV[ClesEnquete]{Lieu}}\\
    \hline
    \xintFor* ##1 in {\xintSeq{1}{\RetiensListeLieuxlen}}\do{%
    \RetiensListeLieux[##1]\xdef\PfCCompteurMelange{\ListeMelangeeLieux[##1]} $\star$ \RetiensListeQuestions[\PfCCompteurMelange,2]
    \\
    }
    \hline
  \end{tabular}
}%


%%%
% Modele en barre
%%%
\setKVdefault[ClesModeleBarre]{Hauteur=0.5cm,Largeur=1cm,Separation=0,Homogene=false}%Separation pour conserver le lien avec les équations.
\defKV[ClesModeleBarre]{Longueur=\setKV[ClesModeleBarre]{Homogene}}%

\newtoks\toklistemodelbarresup%
\toklistemodelbarresup{}%
\def\UpdateListeModelBarreSup#1\nil{\addtotok\toklistemodelbarresup{#1,}}%
\newtoks\toklistemodelbarreinf%
\toklistemodelbarreinf{}%
\def\UpdateListeModelBarreInf#1\nil{\addtotok\toklistemodelbarreinf{#1,}}%

\newcommand\ModeleBarre[3][]{%
  % #1 options
  % #2 éléments de la barre supérieure C1 2 $x$ 1 3/C2 1 1x/
  % #3 éléments de la barre inférieure (même lecture)
  \useKVdefault[ClesModeleBarre]%
  \setKV[ClesModeleBarre]{#1}%
  \setsepchar{\\/ }%
  \readlist\ListeModelBarreSup{#2}%
  \readlist\ListeModelBarreInf{#3}%
  \toklistemodelbarresup{}%
  \foreachitem\compteur\in\ListeModelBarreSup{%
    \foreachitem\valeur\in\ListeModelBarreSup[\compteurcnt]{%
      \expandafter\UpdateListeModelBarreSup\valeur\nil%
    }%
  }%
  \toklistemodelbarreinf{}%
  \foreachitem\compteur\in\ListeModelBarreInf{%
    \foreachitem\valeur\in\ListeModelBarreInf[\compteurcnt]{%
      \expandafter\UpdateListeModelBarreInf\valeur\nil%
    }%
  }%
  \ifboolKV[ClesModeleBarre]{Homogene}{%
    \PfCMPDessineModelBarre{\the\toklistemodelbarresup}{\the\toklistemodelbarreinf}%
  }{%
    \PfCMPDessineModelBarreNonHomogene{\the\toklistemodelbarresup}{\the\toklistemodelbarreinf}%
  }%
}%

\newcommand\PfCMPDessineModelBarre[2]{%
  \begin{mplibcode}%
    Longueur:=\useKV[ClesModeleBarre]{Longueur};
    Hauteur:=\useKV[ClesModeleBarre]{Hauteur};

    vardef Briquesup(expr col)(text t)=
    save $;
    picture $;
    $=image(
    u:=Longueur/MBnbcasessuptotal;
    remplis polygone((0,0),(u,0),(u,Hauteur),(0,Hauteur)) withcolor col;
    draw polygone((0,0),(u,0),(u,Hauteur),(0,Hauteur));
    label(TEX(t),iso((0,0),(u,Hauteur)));
    u:=1cm;
    );
    $
    enddef;

    vardef Briqueinf(expr col)(text t)=
    save $;
    picture $;
    $=image(
    u:=Longueur/MBnbcasesinftotal;
    remplis polygone((0,0),(u,0),(u,Hauteur),(0,Hauteur)) withcolor col;
    draw polygone((0,0),(u,0),(u,Hauteur),(0,Hauteur));
    label(TEX(t),iso((0,0),(u,Hauteur)));
    u:=1cm;
    );
    $
    enddef;
    
    numeric MBnbcolsup;%compte combien de couleurs
    MBnbcolsup=0;
    color MBColSup[];%Sauvegarde les couleurs de la barre sup
    numeric MBnbinfosup[];%compte combien d'infos par couleurs.
    numeric MBnbcasessup[][];
    numeric MBnbcasessuptotal;
    MBnbcasessuptotal=0;
    string MBTextcasessup[][];
    vardef toto(text t)=
    for p_=t:
    if color p_:
    MBnbcolsup:=MBnbcolsup+1;% on incrémente le nombre de couleurs
    MBColSup[MBnbcolsup]:=p_;% on définit la couleur de la série de cases
    MBnbinfosup[MBnbcolsup]:=0;
    else:
    if numeric p_:
    MBnbinfosup[MBnbcolsup]:=MBnbinfosup[MBnbcolsup]+1;
    MBnbcasessuptotal:=MBnbcasessuptotal+p_;
    MBnbcasessup[MBnbcolsup][MBnbinfosup[MBnbcolsup]]:=p_;
    else:
    MBTextcasessup[MBnbcolsup][MBnbinfosup[MBnbcolsup]]:=p_;
    fi;
    fi;
    endfor;
    enddef;
    
    toto(#1);

    numeric MBnbcolinf;%compte combien de couleurs
    MBnbcolinf=0;
    color MBColInf[];%Sauvegarde les couleurs de la barre inf
    numeric MBnbinfoinf[];%compte combien d'infos par couleurs.
    numeric MBnbcasesinf[][];
    numeric MBnbcasesinftotal;
    MBnbcasesinftotal=0;
    string MBTextcasesinf[][];
    vardef tata(text t)=
    for p_=t:
    if color p_:
    MBnbcolinf:=MBnbcolinf+1;% on incrémente le nombre de couleurs
    MBColInf[MBnbcolinf]:=p_;% on définit la couleur de la série de cases
    MBnbinfoinf[MBnbcolinf]:=0;
    else:
    if numeric p_:
    MBnbinfoinf[MBnbcolinf]:=MBnbinfoinf[MBnbcolinf]+1;
    MBnbcasesinftotal:=MBnbcasesinftotal+p_;
    MBnbcasesinf[MBnbcolinf][MBnbinfoinf[MBnbcolinf]]:=p_;
    else:
    MBTextcasesinf[MBnbcolinf][MBnbinfoinf[MBnbcolinf]]:=p_;
    fi;
    fi;
    endfor;
    enddef;
    
    tata(#2);
    
    pair VecteurDeplasup;
    VecteurDeplasup=(Longueur/MBnbcasessuptotal,0);

    numeric MBnbdepla;
    MBnbdepla=0;
    for k=1 upto MBnbcolsup:
    for l=1 upto MBnbinfosup[k]:
    for j=1 upto MBnbcasessup[k][l]:
    trace Briquesup(MBColSup[k])(MBTextcasessup[k][l]) shifted(MBnbdepla*VecteurDeplasup);
    MBnbdepla:=MBnbdepla+1;
    endfor;
    endfor;
    endfor;

    pair VecteurDeplainf;
    VecteurDeplainf=(Longueur/MBnbcasesinftotal,0);

    numeric MBnbdepla;
    MBnbdepla=0;
    for k=1 upto MBnbcolinf:
    for l=1 upto MBnbinfoinf[k]:
    for j=1 upto MBnbcasesinf[k][l]:
    trace Briqueinf(MBColInf[k])(MBTextcasesinf[k][l]) shifted(MBnbdepla*VecteurDeplainf+(0,-Hauteur));
    MBnbdepla:=MBnbdepla+1;
    endfor;
    endfor;
    endfor;
  \end{mplibcode}
}%

\newcommand\PfCMPDessineModelBarreNonHomogene[2]{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}
    Longueur:=\useKV[ClesModeleBarre]{Largeur};
    Hauteur:=\useKV[ClesModeleBarre]{Hauteur};
    Separation:=\useKV[ClesModeleBarre]{Separation};
    
    vardef Brique(expr col,nbfois)(text t)=
    save $;
    picture $;
    $=image(
    u:=Longueur;
    if t="?":
    draw polygone((0,0),(u*abs(nbfois),0),(u*abs(nbfois),Hauteur),(0,Hauteur)) dashed evenly;
    else:
    remplis polygone((0,0),(u*abs(nbfois),0),(u*abs(nbfois),Hauteur),(0,Hauteur)) withcolor col;
    draw polygone((0,0),(u*abs(nbfois),0),(u*abs(nbfois),Hauteur),(0,Hauteur));
    fi;
    if nbfois>0:
    label(TEX(t),iso((0,0),(u*abs(nbfois),Hauteur)));
    else:
    label.bot(TEX(t),iso((0,0),(u*abs(nbfois),-Hauteur)));
    drawdblarrow (0,-0.5*Hauteur)--(u*abs(nbfois),-0.5*Hauteur);
    fi;
    u:=1cm;
    );
    $
    enddef;
    
    numeric MBnbcolsup;%compte combien de couleurs
    MBnbcolsup=0;
    color MBColSup[];%Sauvegarde les couleurs de la barre sup
    numeric MBnbinfosup[];%compte combien d'infos par couleurs.
    numeric MBnbcasessup[][];
    numeric MBnbcasessuptotal;
    MBnbcasessuptotal=0;
    string MBTextcasessup[][];
    vardef toto(text t)=
    for p_=t:
    if color p_:
    MBnbcolsup:=MBnbcolsup+1;% on incrémente le nombre de couleurs
    MBColSup[MBnbcolsup]:=p_;% on définit la couleur de la série de cases
    MBnbinfosup[MBnbcolsup]:=0;
    else:
    if numeric p_:
    MBnbinfosup[MBnbcolsup]:=MBnbinfosup[MBnbcolsup]+1;
    MBnbcasessuptotal:=MBnbcasessuptotal+p_;
    MBnbcasessup[MBnbcolsup][MBnbinfosup[MBnbcolsup]]:=p_;
    else:
    MBTextcasessup[MBnbcolsup][MBnbinfosup[MBnbcolsup]]:=p_;
    fi;
    fi;
    endfor;
    enddef;
    
    toto(#1);

    numeric MBnbcolinf;%compte combien de couleurs
    MBnbcolinf=0;
    color MBColInf[];%Sauvegarde les couleurs de la barre inf
    numeric MBnbinfoinf[];%compte combien d'infos par couleurs.
    numeric MBnbcasesinf[][];
    numeric MBnbcasesinftotal;
    MBnbcasesinftotal=0;
    string MBTextcasesinf[][];
    vardef tata(text t)=
    for p_=t:
    if color p_:
    MBnbcolinf:=MBnbcolinf+1;% on incrémente le nombre de couleurs
    MBColInf[MBnbcolinf]:=p_;% on définit la couleur de la série de cases
    MBnbinfoinf[MBnbcolinf]:=0;
    else:
    if numeric p_:
    MBnbinfoinf[MBnbcolinf]:=MBnbinfoinf[MBnbcolinf]+1;
    MBnbcasesinftotal:=MBnbcasesinftotal+p_;
    MBnbcasesinf[MBnbcolinf][MBnbinfoinf[MBnbcolinf]]:=p_;
    else:
    MBTextcasesinf[MBnbcolinf][MBnbinfoinf[MBnbcolinf]]:=p_;
    fi;
    fi;
    endfor;
    enddef;
    
    tata(#2);
    
    pair VecteurDepla;
    VecteurDepla=(Longueur,0);

    numeric MBnbdepla;
    MBnbdepla=0;
    for k=1 upto MBnbcolsup:
    for l=1 upto MBnbinfosup[k]:
    trace Brique(MBColSup[k],MBnbcasessup[k][l])(MBTextcasessup[k][l]) shifted(MBnbdepla*VecteurDepla);
    MBnbdepla:=MBnbdepla+MBnbcasessup[k][l];
    endfor;
    endfor;

    MBnbdepla:=0;
    for k=1 upto MBnbcolinf:
    for l=1 upto MBnbinfoinf[k]:
    trace Brique(MBColInf[k],MBnbcasesinf[k][l])(MBTextcasesinf[k][l]) shifted(MBnbdepla*VecteurDepla+(0,-Hauteur));
    if MBnbcasesinf[k][l]<0:
    for j=1 upto (abs(MBnbcasesinf[k][l])-1):
    trace ((0,0)--(0,Hauteur)) shifted((MBnbdepla+j)*VecteurDepla+(0,-Hauteur)) withcolor black;
    endfor;
    fi;
    MBnbdepla:=MBnbdepla+abs(MBnbcasesinf[k][l]);
    endfor;
    endfor;

    if Separation>0:
    draw (u*Separation,-1.5Hauteur)--(u*Separation,1.5Hauteur) withpen pencircle scaled 1.5 dashed evenly withcolor red;
    fi;

  \end{mplibcode}%
  \else
  \begin{mpost}[mpsettings={Longueur:=\useKV[ClesModeleBarre]{Largeur};Hauteur:=\useKV[ClesModeleBarre]{Hauteur};Separation:=\useKV[ClesModeleBarre]{Separation};}]
    vardef Brique(expr col,nbfois)(text t)=
    save $;
    picture $;
    $=image(
    u:=Longueur;
    if t="?":
    draw polygone((0,0),(u*abs(nbfois),0),(u*abs(nbfois),Hauteur),(0,Hauteur)) dashed evenly;
    else:
    remplis polygone((0,0),(u*abs(nbfois),0),(u*abs(nbfois),Hauteur),(0,Hauteur)) withcolor col;
    draw polygone((0,0),(u*abs(nbfois),0),(u*abs(nbfois),Hauteur),(0,Hauteur));
    fi;
    if nbfois>0:
    label(LATEXProf(t),iso((0,0),(u*abs(nbfois),Hauteur)));
    else:
    label.bot(LATEXProf(t),iso((0,0),(u*abs(nbfois),-Hauteur)));
    drawdblarrow (0,-0.5*Hauteur)--(u*abs(nbfois),-0.5*Hauteur);
    fi;
    u:=1cm;
    );
    $
    enddef;
    
    numeric MBnbcolsup;%compte combien de couleurs
    MBnbcolsup=0;
    color MBColSup[];%Sauvegarde les couleurs de la barre sup
    numeric MBnbinfosup[];%compte combien d'infos par couleurs.
    numeric MBnbcasessup[][];
    numeric MBnbcasessuptotal;
    MBnbcasessuptotal=0;
    string MBTextcasessup[][];
    vardef toto(text t)=
    for p_=t:
    if color p_:
    MBnbcolsup:=MBnbcolsup+1;% on incrémente le nombre de couleurs
    MBColSup[MBnbcolsup]:=p_;% on définit la couleur de la série de cases
    MBnbinfosup[MBnbcolsup]:=0;
    else:
    if numeric p_:
    MBnbinfosup[MBnbcolsup]:=MBnbinfosup[MBnbcolsup]+1;
    MBnbcasessuptotal:=MBnbcasessuptotal+p_;
    MBnbcasessup[MBnbcolsup][MBnbinfosup[MBnbcolsup]]:=p_;
    else:
    MBTextcasessup[MBnbcolsup][MBnbinfosup[MBnbcolsup]]:=p_;
    fi;
    fi;
    endfor;
    enddef;
    
    toto(#1);

    numeric MBnbcolinf;%compte combien de couleurs
    MBnbcolinf=0;
    color MBColInf[];%Sauvegarde les couleurs de la barre inf
    numeric MBnbinfoinf[];%compte combien d'infos par couleurs.
    numeric MBnbcasesinf[][];
    numeric MBnbcasesinftotal;
    MBnbcasesinftotal=0;
    string MBTextcasesinf[][];
    vardef tata(text t)=
    for p_=t:
    if color p_:
    MBnbcolinf:=MBnbcolinf+1;% on incrémente le nombre de couleurs
    MBColInf[MBnbcolinf]:=p_;% on définit la couleur de la série de cases
    MBnbinfoinf[MBnbcolinf]:=0;
    else:
    if numeric p_:
    MBnbinfoinf[MBnbcolinf]:=MBnbinfoinf[MBnbcolinf]+1;
    MBnbcasesinftotal:=MBnbcasesinftotal+p_;
    MBnbcasesinf[MBnbcolinf][MBnbinfoinf[MBnbcolinf]]:=p_;
    else:
    MBTextcasesinf[MBnbcolinf][MBnbinfoinf[MBnbcolinf]]:=p_;
    fi;
    fi;
    endfor;
    enddef;
    
    tata(#2);
    
    pair VecteurDepla;
    VecteurDepla=(Longueur,0);

    numeric MBnbdepla;
    MBnbdepla=0;
    for k=1 upto MBnbcolsup:
    for l=1 upto MBnbinfosup[k]:
    trace Brique(MBColSup[k],MBnbcasessup[k][l])(MBTextcasessup[k][l]) shifted(MBnbdepla*VecteurDepla);
    MBnbdepla:=MBnbdepla+MBnbcasessup[k][l];
    endfor;
    endfor;

    MBnbdepla:=0;
    for k=1 upto MBnbcolinf:
    for l=1 upto MBnbinfoinf[k]:
    trace Brique(MBColInf[k],MBnbcasesinf[k][l])(MBTextcasesinf[k][l]) shifted(MBnbdepla*VecteurDepla+u*(0,-0.5));
    if MBnbcasesinf[k][l]<0:
    for j=1 upto (abs(MBnbcasesinf[k][l])-1):
    trace ((0,0)--(0,Hauteur)) shifted((MBnbdepla+j)*VecteurDepla+u*(0,-0.5)) withcolor black;
    endfor;
    fi;
    MBnbdepla:=MBnbdepla+abs(MBnbcasesinf[k][l]);
    endfor;
    endfor;

    if Separation>0:
    draw u*(Separation,-0.75)--u*(Separation,0.75) withpen pencircle scaled 1.5 dashed evenly withcolor red;
    fi;

  \end{mpost}
  \fi
}%

%%%
% Fiche m\'emorisation active
%%%
\setKVdefault[ClesFicheMemo]{TexteReponses=Réponses,TexteQuestions=Questions,Solution=false,Largeur=\linewidth}

\newcommand\FicheMemo[3][]{%
  \xdef\CountcolUn{0}%
  \xdef\CountcolDeux{0}%
  \useKVdefault[ClesFicheMemo]%
  \setKV[ClesFicheMemo]{#1}%
  \setsepchar[*]{§*/}\reademptyitems%
  \readlist*\ListeQuestionColonneUn{#2}%
  \readlist*\ListeQuestionColonneDeux{#3}%
  \renewcommand{\arraystretch}{1.35}%
  \begin{NiceTabular}[width=\useKV[ClesFicheMemo]{Largeur}]{X[1]X[1]X[1]X[1]}[hvlines]
    \CodeBefore%
    \rowcolor{gray!15}{1}%
    \tikz\draw[dashed,gray!50](2-|1.5) to (last-|1.5);%
    \tikz\draw[dashed,gray!50](2-|4.5) to (last-|4.5);%
    \Body%
    \Block{1-1}{\bfseries\useKV[ClesFicheMemo]{TexteReponses}}&&&\Block{1-1}{\bfseries\useKV[ClesFicheMemo]{TexteReponses}}\\
    \xintFor* ##1 in {\xintSeq {1}{\ListeQuestionColonneUnlen}}\do{%
      \xintifboolexpr{\listlen\ListeQuestionColonneUn[##1]==2}{%
        \uppercase{&}}{%
        \Block[l]{\fpeval{\ListeQuestionColonneUn[##1,1]}-1}{\ifboolKV[ClesFicheMemo]{Solution}{\ListeQuestionColonneUn[##1,3]}{}}%
        \uppercase{&}\xdef\CountcolUn{\fpeval{\CountcolUn+1}}\Block[l]{\fpeval{\ListeQuestionColonneUn[##1,1]}-1}{\ListeQuestionColonneUn[##1,2]}%
      }%
      &%
      \xintifboolexpr{\listlen\ListeQuestionColonneDeux[##1]==2}{%
        \uppercase{&}%
      }{%
        \xdef\CountcolDeux{\fpeval{\CountcolDeux+1}}\Block[l]{\fpeval{\ListeQuestionColonneDeux[##1,1]}-1}{\ListeQuestionColonneDeux[##1,2]}\uppercase{&}\Block[l]{\fpeval{\ListeQuestionColonneDeux[##1,1]}-1}{\ifboolKV[ClesFicheMemo]{Solution}{\ListeQuestionColonneDeux[##1,3]}{}}%
      }%
      \\%
    }%
    \CodeAfter%
    \tikz\node[xshift=0.5em] at (2-|1) {\scriptsize\faCut};%
    \xdef\PfCCountCutUn{2}%
    \xintFor* ##1 in {\xintSeq {1}{\ListeQuestionColonneUnlen}}\do{%
      \xintifboolexpr{\listlen\ListeQuestionColonneUn[##1]==2}{%
      }{%
        \xdef\PfCCountCutUn{\fpeval{\PfCCountCutUn+\ListeQuestionColonneUn[##1,1]}}%
        \tikz\node[xshift=0.5em] at (\fpeval{\PfCCountCutUn}-|1) {\scriptsize\faCut};%
      }%
    }%
    \tikz\node[xshift=-0.5em] at (2-|last) {\scriptsize\rotatebox{180}{\faCut}};%
    \xdef\PfCCountCutDeux{2}%
    \xintFor* ##1 in {\xintSeq {1}{\ListeQuestionColonneDeuxlen}}\do{%
      \xintifboolexpr{\listlen\ListeQuestionColonneDeux[##1]==2}{%
      }{%
        \xdef\PfCCountCutDeux{\fpeval{\PfCCountCutDeux+\ListeQuestionColonneDeux[##1,1]}}%
        \tikz\node[xshift=-0.5em] at (\fpeval{\PfCCountCutDeux}-|last) {\scriptsize\rotatebox{180}{\faCut}};%
      }%
    }%
    \tikz\node[xshift=0.5em] at (1-|1) {\color{gray}\scriptsize\faCut};%
    \tikz\node[xshift=0.5em] at (last-|1) {\color{gray}\scriptsize\faCut};%
    \tikz\node[xshift=-0.5em] at (1-|last) {\color{gray}\scriptsize\rotatebox{180}{\faCut}};%
    \tikz\node[xshift=-0.5em] at (last-|last) {\color{gray}\scriptsize\rotatebox{180}{\faCut}};%
    \tikz\node at (1.5-|2.5) {\bfseries\useKV[ClesFicheMemo]{TexteQuestions} 1 à \num{\CountcolUn}};%
    \tikz\node at (1.5-|3.5) {\bfseries\useKV[ClesFicheMemo]{TexteQuestions} \num{\fpeval{\CountcolUn+1}} à \num{\fpeval{\CountcolUn+\CountcolDeux}}};%
  \end{NiceTabular}%
  \renewcommand{\arraystretch}{1}%
  \setsepchar{,}%
}%

%%%
% Op\'erations pos\'es à trou
%%%
%% D'après https://tex.stackexchange.com/questions/277246/drawing-a-circle-around-the-numbers-in-xlop-package

\newcommand\PfCchiffre[2]{\tikz[remember picture] \node[inner sep=0pt](#1){#2};}

\newcommand\PfCentoure[2]{\tikz[remember picture,overlay] \node[preaction={draw={\useKV[ClesOperations]{CouleurCadre}},ultra thick,opacity=1,
transform canvas={xshift=0em,yshift=0em}},rectangle,rounded corners,ultra thick,inner sep=.55em,fit=(#1.center)(#2.center)]{} ;}

\newcounter{divxlop}%
\newcounter{mulxlop}%
\newcounter{addxlop}%
\newcounter{subxlop}%

\setKVdefault[ClesOperations]{Solution=false,CouleurCadre=LightSteelBlue,CouleurSolution=red,CouleurFond=white,CouleurVirgule=white}

\newcommand\Division[3][]{%
  \useKVdefault[ClesOperations]%
  \setKV[ClesOperations]{#1}%
  \setcounter{divxlop}{0}%
  \ifboolKV[ClesOperations]{Solution}{\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurSolution}}}{\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurFond}}}%
  \opidiv[lineheight=1.5em,columnwidth=1.25em,displayintermediary=all,voperator=bottom,intermediarystyle=\stepcounter{divxlop}\color{PfCSolOp}\PfCchiffre{A\thedivxlop},remainderstyle=\stepcounter{divxlop}\color{PfCSolOp}\PfCchiffre{A\thedivxlop},resultstyle=\stepcounter{divxlop}\color{PfCSolOp}\PfCchiffre{A\thedivxlop}]{#2}{#3}%
  \foreach \i in {1,...,\thedivxlop}{%
    \PfCentoure{A\i}{A\i}%
  }%
}%

\newcommand\DivisionD[3][]{%
  \useKVdefault[ClesOperations]%
  \setKV[ClesOperations]{#1}%
  \setcounter{divxlop}{0}%
  \ifboolKV[ClesOperations]{Solution}{\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurSolution}}\colorlet{PfCCouleurVirgule}{PfCSolOp}}{\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurFond}}\colorlet{PfCCouleurVirgule}{\useKV[ClesOperations]{CouleurVirgule}}}%
  \opdiv[decimalsepsymbol={,},lineheight=1.5em,columnwidth=1.5em,displayintermediary=all,voperator=bottom,intermediarystyle=\stepcounter{divxlop}\color{PfCSolOp}\PfCchiffre{A\thedivxlop},remainderstyle=\stepcounter{divxlop}\color{PfCSolOp}\PfCchiffre{A\thedivxlop},resultstyle=\stepcounter{divxlop}\color{PfCSolOp}\PfCchiffre{A\thedivxlop},resultstyle.d=\color{PfCCouleurVirgule}]{#2}{#3}%
  \foreach \i in {1,...,\thedivxlop}{%
    \PfCentoure{A\i}{A\i}%
  }%
}%

\newcommand\Multiplication[3][]{%
  \useKVdefault[ClesOperations]%
  \setKV[ClesOperations]{#1}%
  \setcounter{mulxlop}{0}%
  \ifboolKV[ClesOperations]{Solution}{\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurSolution}}\colorlet{PfCCouleurVirgule}{PfCSolOp}}{\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurFond}}\colorlet{PfCCouleurVirgule}{\useKV[ClesOperations]{CouleurVirgule}}}%
  \opmul[decimalsepsymbol={,},lineheight=2em,columnwidth=1.5em,displayintermediary=all,voperator=bottom,intermediarystyle=\stepcounter{mulxlop}\color{PfCSolOp}\PfCchiffre{A\themulxlop},resultstyle=\stepcounter{mulxlop}\color{PfCSolOp}\PfCchiffre{A\themulxlop},resultstyle.d=\color{PfCCouleurVirgule}]{#2}{#3}%
  \foreach \i in {1,...,\themulxlop}{%
    \PfCentoure{A\i}{A\i}%
  }%
}%

\newcommand\Addition[3][]{%
  \useKVdefault[ClesOperations]%
  \setKV[ClesOperations]{#1}%
  \setcounter{addxlop}{0}%
  \ifboolKV[ClesOperations]{Solution}{\opset{carryadd,carrystyle=\color{PfCSolOp}\scriptsize}\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurSolution}}\colorlet{PfCCouleurVirgule}{PfCSolOp}}{\opset{carryadd=false}\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurFond}}\colorlet{PfCCouleurVirgule}{\useKV[ClesOperations]{CouleurVirgule}}}%
  \opadd[decimalsepsymbol={,},lineheight=1.75em,columnwidth=1.5em,displayintermediary=all,voperator=bottom,intermediarystyle=\stepcounter{addxlop}\color{PfCSolOp}\PfCchiffre{A\theaddxlop},resultstyle=\stepcounter{addxlop}\color{PfCSolOp}\PfCchiffre{A\theaddxlop},resultstyle.d=\color{PfCCouleurVirgule}]{#2}{#3}
  \foreach \i in {1,...,\theaddxlop}{%
    \PfCentoure{A\i}{A\i}%
  }%
}%

\newcommand\Soustraction[3][]{%
  \useKVdefault[ClesOperations]%
  \setKV[ClesOperations]{#1}%
  \setcounter{subxlop}{0}%
  \ifboolKV[ClesOperations]{Solution}{\opset{carrysub,carrystyle=\color{PfCSolOp}\scriptsize}\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurSolution}}\colorlet{PfCCouleurVirgule}{PfCSolOp}}{\opset{carrysub=false}\colorlet{PfCSolOp}{\useKV[ClesOperations]{CouleurFond}}\colorlet{PfCCouleurVirgule}{\useKV[ClesOperations]{CouleurVirgule}}}%
  \opsub[decimalsepsymbol={,},lineheight=1.75em,columnwidth=1.5em,displayintermediary=all,voperator=bottom,intermediarystyle=\stepcounter{subxlop}\color{PfCSolOp}\PfCchiffre{A\thesubxlop},resultstyle=\stepcounter{subxlop}\color{PfCSolOp}\PfCchiffre{A\thesubxlop},resultstyle.d=\color{PfCCouleurVirgule}]{#2}{#3}%
  \foreach \i in {1,...,\thesubxlop}{%
    \PfCentoure{A\i}{A\i}
  }%
}%

%%%
% Cartographie
%%%
\setKVdefault[Cartographie]{Echelle=1,Carte=false,All=false,Europe=false,Asie=false,Amsud=false,Amnord=false,Amcentre=false,Caraibes=false,Afrique=false,AfficheEchelle=false,PaysSeul=false,VillesSup=false,Capitales=false,Impression=false,Fleuves=false,CouleurFond=ciel,Largeur=12,Hauteur=12,Arborescence="/usr/local/texlive/2022/texmf-dist/metapost/profcollege/datastest/",Projection=false,TypeProjection="mercator",CouleurPays=Cornsilk,Pasl=2,PasL=2}
\defKV[Cartographie]{EchelleCarte=\setKV[Cartographie]{Carte}}
\defKV[Cartographie]{Pays=\setKV[Cartographie]{PaysSeul}}
\defKV[Cartographie]{Villes=\setKV[Cartographie]{VillesSup}}

\newcommand\Cartographie[3][]{%
  \ifluatex
  \useKVdefault[Cartographie]
  \setKV[Cartographie]{#1}
  \ifboolKV[Cartographie]{Projection}{%
    \mplibforcehmode
    \begin{mplibcode}
      input PfCMonde;
      string arborescence;
      arborescence:=\useKV[Cartographie]{Arborescence};
      boolean Impression,VillesSup;
      VillesSup=\useKV[Cartographie]{VillesSup};
      Impression=\useKV[Cartographie]{Impression};
      
      maillage:=true;
      fleuves:=false;
      lacs:=false;
      capitales:=false;

      if Impression:
      noncolore:=true;
      payscolor:=white;
      else:
      noncolore:=true;
      payscolor:=\useKV[Cartographie]{CouleurPays};
      fi;

      projection:=\useKV[Cartographie]{TypeProjection};
      feuillet:=u*(-20,-20)--u*(20,-20)--u*(20,20)--u*(-20,20)--cycle;
      drawoptions(withpen pencircle scaled 0.5 withcolor 0.5white);
      Projection(3,48,\useKV[Cartographie]{Echelle});
      drawoptions();

      if projection="mercator":
      clip currentpicture to (mercatorc(-85,-180)--mercatorc(-85,180)--mercatorc(85,180)--mercatorc(85,-180)--cycle);
      draw mercatorc(0,-180)--mercatorc(0,180);
      draw mercatorc(-85,0)--mercatorc(85,0);
      label.llft(TEX("\tiny \ang{"&decimal(0)&"}"),mercatorc(0,0));
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 8:
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),mercatorc(-k*10,0));
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),mercatorc(k*10,0));
      endfor;
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 18:
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),mercatorc(0,-k*10));
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),mercatorc(0,k*10));
      endfor;
      elseif projection="cylindrique":
      clip currentpicture to (cylindriquec(-85,-180)--cylindriquec(-85,180)--cylindriquec(85,180)--cylindriquec(85,-180)--cycle);
      draw cylindriquec(0,-180)--cylindriquec(0,180);
      draw cylindriquec(-85,0)--cylindriquec(85,0);
      label.llft(TEX("\tiny \ang{"&decimal(0)&"}"),cylindriquec(0,0));
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 8:
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(-k*10,0));
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(k*10,0));
      endfor;
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 18:
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(0,-k*10));
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(0,k*10));
      endfor;
      elseif projection="winkel":
      clip currentpicture to (winkelc(-85,-180)--winkelc(-85,180) for k=-80 step 5 until 85:--winkelc(k,180) endfor --winkelc(85,-180) for k=80 step -5 until -85:--winkelc(k,-180) endfor --cycle);
      draw winkelc(0,-180)--winkelc(0,180);
      draw winkelc(-85,0)--winkelc(85,0);
      label.llft(TEX("\tiny \ang{"&decimal(0)&"}"),winkelc(0,0));
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 8:
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),winkelc(-k*10,0));
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),winkelc(k*10,0));
      endfor;
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 18:
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),winkelc(0,-k*10));
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),winkelc(0,k*10));
      endfor;
      elseif projection="cylindrique":
      clip currentpicture to (cylindriquec(-85,-180)--cylindriquec(-85,180)--cylindriquec(85,180)--cylindriquec(85,-180)--cycle);
      draw cylindriquec(0,-180)--cylindriquec(0,180);
      draw cylindriquec(-85,0)--cylindriquec(85,0);
      label.llft(TEX("\tiny \ang{"&decimal(0)&"}"),cylindriquec(0,0));
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 8:
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(-k*10,0));
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(k*10,0));
      endfor;
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 18:
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(0,-k*10));
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),cylindriquec(0,k*10));
      endfor;
      elseif projection="simple":
      clip currentpicture to (simplec(-85,-180)--simplec(-85,180)--simplec(85,180)--simplec(85,-180)--cycle);
      draw simplec(0,-180)--simplec(0,180);
      draw simplec(-85,0)--simplec(85,0);
      label.llft(TEX("\tiny \ang{"&decimal(0)&"}"),simplec(0,0));
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 8:
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),simplec(-k*10,0));
      label.lft(TEX("\tiny \ang{"&decimal(k*10)&"}"),simplec(k*10,0));
      endfor;
      for k=\useKV[Cartographie]{Pasl} step \useKV[Cartographie]{Pasl} until 18:
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),simplec(0,-k*10));
      label.bot(TEX("\tiny \ang{"&decimal(k*10)&"}"),simplec(0,k*10));
      endfor;
      fi;
      if VillesSup:
      nomfichiermul:=\useKV[Cartographie]{Villes};
      nblec:=scantokens readfrom nomfichiermul;
      drawoptions(withcolor (0.15,0.15,0.15));
      for p=1 upto nblec:
      pair Coord[],latlon;string p_;
      latlon=scantokens readfrom nomfichiermul;
      p_=scantokens readfrom nomfichiermul;
      if projection="mercator":
      Coord[p]=mercatorc(ypart(latlon),xpart(latlon));
      elseif projection="winkel":
      Coord[p]=winkelc(ypart(latlon),xpart(latlon));
      elseif projection="cylindrique":
      Coord[p]=cylindriquec(ypart(latlon),xpart(latlon));
      elseif projection="simple":
      Coord[p]=simplec(ypart(latlon),xpart(latlon));
      fi;
      marque_p:="croix";
      pointe(Coord[p]);
      label.scantokens readfrom nomfichiermul(TEX(""&p_&""),Coord[p]);
      endfor;
      drawoptions();
      closefrom nomfichiermul;
      fi;
    \end{mplibcode}
  }{%    
    \mplibforcehmode
    \begin{mplibcode}
      input PfCMonde;
      string arborescence;
      arborescence:=\useKV[Cartographie]{Arborescence};
      LargeurCadre=\useKV[Cartographie]{Largeur};
      HauteurCadre=\useKV[Cartographie]{Hauteur};
      distanceecran=100*\useKV[Cartographie]{Echelle};
      fleuves:=\useKV[Cartographie]{Fleuves};
      boolean Carte,Impression,VillesSup;
      Carte=\useKV[Cartographie]{Carte};
      Impression=\useKV[Cartographie]{Impression};
      VillesSup=\useKV[Cartographie]{VillesSup};
      couleurfond:=\useKV[Cartographie]{CouleurFond};
      if Impression:
      noncolore:=true;
      payscolor:=0.85white;
      couleurfond:=white;
      couleurfleuve:=couleurfond;
      fi;
      capitales:=\useKV[Cartographie]{Capitales};
      All:=\useKV[Cartographie]{All};
      Europe:=\useKV[Cartographie]{Europe};
      Asie:=\useKV[Cartographie]{Asie};
      Amsud:=\useKV[Cartographie]{Amsud};
      Amnord:=\useKV[Cartographie]{Amnord};
      Amcentrale:=\useKV[Cartographie]{Amcentre};
      Caraibes:=\useKV[Cartographie]{Caraibes};
      Afrique:=\useKV[Cartographie]{Afrique};
      if Carte:
      Echelle:=\useKV[Cartographie]{AfficheEchelle};
      figure(-0.5u*LargeurCadre,-0.5u*HauteurCadre,0.5u*LargeurCadre,0.5u*HauteurCadre);
      if \useKV[Cartographie]{PaysSeul}:
      projection:="bonne";
      theta:=#2;
      phi:=#3;
      zoom(echelle(#2,#3,\useKV[Cartographie]{EchelleCarte}));
      fill (bonnec(-90,-180) for k=-85 step 5 until 90:..bonnec(k,-180) endfor)..reverse(bonnec(-90,180) for k=-85 step 5 until 90:..bonnec(k,180) endfor)..cycle withcolor couleurfond;
      lecturep(arborescence&\useKV[Cartographie]{Pays}&".dat",couleurfond);%
      trace feuillet withpen pencircle scaled 2;
      if Echelle=true:
      draw ((Xa,Ya)+u*(1,1))--((Xa,Ya)+u*(2,1));
      labeloffset:=labeloffset*1.5;
      label.top(btex 0 etex,(Xa,Ya)+u*(1,1));
      label.top(TEX(""&decimal(Long)&"~km"),(Xa,Ya)+u*(2,1));
      labeloffset:=labeloffset/1.5;
      draw ((Xa,Ya)+u*(1,1.1))--((Xa,Ya)+u*(1,0.9));
      draw (((Xa,Ya)+u*(1,1.1))--((Xa,Ya)+u*(1,0.9))) shifted(u*(1,0));
      fi;
      else:
      projection:="bonne";
      Projection(#2,#3,echelle(#2,#3,\useKV[Cartographie]{EchelleCarte}));
      trace feuillet withpen pencircle scaled 2;
      fi;
      if VillesSup:
      nomfichiermul:=\useKV[Cartographie]{Villes};
      nblec:=scantokens readfrom nomfichiermul;
      drawoptions(withcolor (0.15,0.15,0.15));
      projection:="bonne";
      for p=1 upto nblec:
      pair Coord[],latlon;string p_;
      latlon=scantokens readfrom nomfichiermul;
      p_=scantokens readfrom nomfichiermul;
      Coord[p]=bonnec(ypart(latlon),xpart(latlon));
      dotlabel.scantokens readfrom nomfichiermul(TEX(""&p_&""),Coord[p]);
      endfor;
      drawoptions();
      closefrom nomfichiermul;
      fi;
      else:
      mappemonde(#2,#3);
      fi;
    \end{mplibcode}
  }
  \else
  \PackageWarning{ProfCollege}{"La commande Cartographie n'est compatible qu'avec LuaLaTeX."}
  \fi
}%

%%%
% Twitter
%%%
\setKVdefault[Twitter]{Largeur=0.95\linewidth,Auteur=Christophe,Date=\today,Url=ViveLaTeX,EchelleLogo=0.035,Logo=DrStrange,Publie=false}

\NewEnviron{Twitter}[1][]{%
  \useKVdefault[Twitter]%
  \setKV[Twitter]{#1}%
  \xdef\EchelleLogo{\useKV[Twitter]{EchelleLogo}}%
  \begin{tcolorbox}[%
    enhanced,%
    overlay unbroken and first={%
      \node[anchor=west,xshift=3em,yshift=-2em] at (frame.north west) {\textbf{\useKV[Twitter]{Auteur}}~{\color{gray}@\ttfamily \useKV[Twitter]{Url} - \useKV[Twitter]{Date}}};
      \node[anchor=center,xshift=1em+2mm,yshift=-2em] at (frame.north west) {\LogoTW{\useKV[Twitter]{Logo}}{\EchelleLogo}};
      \node[xshift=-1em,yshift=-2em] at (frame.north east) {\color{gray}...};
      \coordinate[yshift=1em] (A) at (frame.south west);
      \coordinate[yshift=1em] (B) at (frame.south east);
      \node[] (C1) at ($(A)!0.1!(B)$) {\faComment[regular]\ifboolKV[Twitter]{Publie}{~\fpeval{randint(1,10)}}{}};
      \node[] (C2) at ($(A)!0.325!(B)$) {\faRetweet\ifboolKV[Twitter]{Publie}{~\fpeval{randint(1,10)}}{}};
      \node[] (C3) at ($(A)!0.55!(B)$) {\faHeart[regular]\ifboolKV[Twitter]{Publie}{~\fpeval{randint(1,10)}}{}};
      \node[] (C4) at ($(A)!0.775!(B)$) {\faShareSquare};
    },
    colback=white,
    colframe=gray!15,
    top=2em,
    left=3em,
    bottom=2em]
    \vspace*{0.5em}\par
    \BODY%
  \end{tcolorbox}
}

%%%
% Facebook
%%%
\setKVdefault[Facebook]{Largeur=0.95\linewidth,Auteur=Christophe,Date=\today,Heure=3:14,EchelleLogo=0.035,Logo=DrStrange,Publie=false}

\NewEnviron{Facebook}[1][]{%
  \useKVdefault[Facebook]%
  \setKV[Facebook]{#1}%
  \xdef\EchelleLogo{\useKV[Facebook]{EchelleLogo}}%
  \begin{tcolorbox}[%
    enhanced,%
    overlay unbroken and first={%
      \node[anchor=west,xshift=3em,yshift=-1em] at (frame.north west) {\textbf{\useKV[Facebook]{Auteur}}};
      \node[anchor=west,xshift=3em,yshift=-2em] at (frame.north west) {\scriptsize\color{gray}\useKV[Facebook]{Date}, \useKV[Facebook]{Heure}};
      \node[anchor=center,xshift=1em+2mm,yshift=-1.5em] at (frame.north west) {\LogoTW{\useKV[Facebook]{Logo}}{\EchelleLogo}};
      \node[xshift=-1em,yshift=-1.5em] at (frame.north east) {\bfseries\color{gray}...};
      \coordinate[yshift=1.15em] (A) at (frame.south west);
      \coordinate[yshift=1.15em] (B) at (frame.south east);
      \coordinate[xshift=0.5em,yshift=1.8em] (A1) at (frame.south west);
      \coordinate[xshift=-0.5em,yshift=1.8em] (B1) at (frame.south east);
      \coordinate[xshift=0.5em,yshift=0.5em] (A2) at (frame.south west);
      \coordinate[xshift=-0.5em,yshift=0.5em] (B2) at (frame.south east);
      \ifboolKV[Facebook]{Publie}{%
        \coordinate[xshift=1em,yshift=1em] (A3) at (A1);
        \draw[blue,fill=blue] (A3) circle (1.5mm);
        \node[] at (A3) {\tiny\color{white}\faThumbsUp};
        \node[anchor=west] at (A3) {~\scriptsize\fpeval{randint(1,150)}};
        \node[anchor=east,xshift=-1em,yshift=1em] at (B1) {\scriptsize\fpeval{randint(2,20)} commentaires~\fpeval{randint(2,10)} partages};
      }{}
      \draw[gray] (A1)--(B1);
      \draw[gray] (A2)--(B2);
      \node[] (C1) at ($(A)!0.15!(B)$) {\footnotesize\faThumbsUp{}~\bfseries J'aime};
      \node[] (C2) at ($(A)!0.5!(B)$) {\footnotesize\faComment*[regular]~\bfseries Commenter};     \node[] (C3) at ($(A)!0.85!(B)$) {\footnotesize\faShareSquare~\bfseries Partager};
    },
    colback=white,
    colframe=gray!15,
    top=2em,
    left=3em,
    bottom=4em]
    %\vspace*{0.5em}\par
    \BODY%
  \end{tcolorbox}
}

%%%
% Instagram
%%%
\setKVdefault[Instagram]{Largeur=0.95\linewidth,Auteur=Christophe,Expediteur=Pierre,Date=\today,Temps=34,Publie=false,Logo=DrStrange,LogoEx=tiger,EchelleLogo=0.035,Texte={}}

\NewEnviron{Instagram}[1][]{%
  \useKVdefault[Instagram]%
  \setKV[Instagram]{#1}%
  \xdef\EchelleLogo{\useKV[Instagram]{EchelleLogo}}%
  \begin{tcolorbox}[%
    enhanced,%
    underlay unbroken and first={%
      \node[anchor=west,xshift=3em,yshift=-1.5em] at (frame.north west) {\textbf{\useKV[Instagram]{Expediteur}}};
      \node[anchor=center,xshift=1em+2mm,yshift=-1.5em] at (frame.north west) {\LogoTW{\useKV[Instagram]{LogoEx}}{\EchelleLogo}};
      \node[xshift=-1em,yshift=-1.5em,rotate=90] at (frame.north east) {\bfseries\color{gray}...};
      \coordinate[yshift=-3em] (HA) at (frame.north west);
      \coordinate[yshift=-3em] (HB) at (frame.north east);
      \draw[gray!15] (HA)--(HB);
      \coordinate[yshift=7em] (BA) at (frame.south west);
      \coordinate[yshift=7em] (BB) at (frame.south east);
      \draw[gray!15] (BA)--(BB);
      \coordinate[xshift=1em,yshift=6em] (A) at (frame.south west);
      \node[anchor=west] at (A) {\bfseries\faHeart[regular]\quad\faComment[regular]\quad\faPaperPlane};
      \coordinate[xshift=-1em,yshift=6em] (A1) at (frame.south east);
      \node[anchor=east] at (A1) {\bfseries\faBookmark[regular]};
      \coordinate[xshift=1em,yshift=5em] (B) at (frame.south west);
      \node[anchor=west] at (B) {\footnotesize\bfseries\fpeval{randint(10,30)} J'aime};
      \coordinate[xshift=1em,yshift=4em] (C) at (frame.south west);
      \node[anchor=west] at (C) {\textbf{\useKV[Instagram]{Expediteur}}~\useKV[Instagram]{Texte}};
      \node[anchor=center,xshift=2em,yshift=2.25em] at (frame.south west) {\LogoTW{\useKV[Instagram]{Logo}}{\EchelleLogo}};
      \node[anchor=west,xshift=4em,yshift=2.25em] at (frame.south west) {\textcolor{gray!50}{Ajouter un commentaire\dots}};
      \node[anchor=east,xshift=-1em,yshift=2.25em] at (frame.south east) {\textcolor{red}{\faHeart}\quad\textcolor{Gold}{\faHandSpock}\quad\textcolor{gray!50}{\faPlusCircle}};
      \node[anchor=west,xshift=1em,yshift=0.5em] at (frame.south west) {\scriptsize\color{gray} Il y a \useKV[Instagram]{Temps} secondes};
    },
    colback=white,
    colframe=gray!15,
    top=3em,
    left=3em,
    bottom=7em]
    \BODY%
  \end{tcolorbox}
}

%%%
% Snapchat
%%%
\setKVdefault[Snapchat]{Largeur=0.95\linewidth,Auteur=Christophe,Date=\today,Temps=34,Logo=DrStrange,EchelleLogo=0.035,Texte=Envoyer un Chat}

\NewEnviron{Snapchat}[1][]{%
  \useKVdefault[Snapchat]%
  \setKV[Snapchat]{#1}%
  \xdef\EchelleLogo{\useKV[Snapchat]{EchelleLogo}}%
  \begin{tcolorbox}[%
    enhanced,%
    underlay unbroken and first={%
      \node[anchor=west,xshift=3em,yshift=-1em] at (frame.north west) {\textbf{\useKV[Snapchat]{Auteur}}};
      \node[anchor=west,xshift=3em,yshift=-2em] at (frame.north west) {\scriptsize\color{gray} il y a \useKV[Snapchat]{Temps}~min};
      \node[anchor=center,xshift=1em+2mm,yshift=-1.5em] at (frame.north west) {\LogoTW{\useKV[Snapchat]{Logo}}{\EchelleLogo}};
      \node[xshift=-1em,yshift=-1.5em,rotate=90] at (frame.north east) {\bfseries...};
      \node[xshift=-3em,yshift=-1.5em] at (frame.north east) {\faBell[regular]};
      \coordinate[xshift=2em,yshift=2em] (P1) at (frame.south west);
      \coordinate[xshift=4.5em,yshift=2em] (P2) at (frame.south west);
      \coordinate[xshift=-3em,yshift=2em] (P4) at (frame.south west);
      \coordinate[xshift=-2em,yshift=2em] (P3) at (frame.south east);
      \coordinate[xshift=4.5em,yshift=1em] (P5) at (frame.south west);
      \coordinate[xshift=4.5em,yshift=3em] (P8) at (frame.south west);
      \coordinate[xshift=-4.5em,yshift=1em] (P6) at (frame.south east);
      \coordinate[xshift=-4.5em,yshift=3em] (P7) at (frame.south east);
      \draw (P1) circle (1em);
      \node at (P1) {\faCamera};
      \draw (P3) circle (1em);
      \node[xshift=-0.125em,rotate=-45] at (P3) {\faLocationArrow};
      \node[anchor=west,inner sep=0pt] at (P2) {\useKV[Snapchat]{Texte}};
      \draw (P5) -- (P6) arc(270:450:1em) -- (P7) -- (P8) arc(90:270:1em) -- cycle;
    },
    colback=white,
    colframe=gray!15,
    top=3em,
    left=3em,
    bottom=3em]
    \BODY%
  \end{tcolorbox}
}

%%%
% Bon de sortie
%%%
\newcommand\BonSortieBandeau{%
  Nom : \hfill Date : \hspace*{3cm}
}

\newtcolorbox{Sortie}{%
  %Titre
  colbacktitle=white,
  fonttitle=\color{black}\Large\bfseries,
  toptitle=2mm,
  bottomtitle=2mm,
  title={\BonSortieBandeau},
  %%Cadre principal
  enhanced,
  nobeforeafter,
  width=13.15cm,
  height=8.8cm,
  colback=white,
  valign=top,
  %Cadre bas
  sidebyside,
  righthand width=0.05\linewidth,
}

\setKVdefault[ClesSortie]{MemeEnonce=false}%

\newcommand\BonSortieSmiley{%
  \Huge
  \begin{center}
    \RKangry

    \vspace{1em}
    
    \RKsad

    \vspace{1em}
    
    \RKsmallsmile
    
    \vspace{1em}

    \RKbigsmile
  \end{center}
}

\NewDocumentCommand\BonSortie{o m m m m}{%
  \clearpage%
  \useKVdefault[ClesSortie]%
  \setKV[ClesSortie]{#1}%
  \begin{tikzpicture}[remember picture, overlay]
    \draw[dashed] (current page.north) to (current page.south);
    \draw[dashed] (current page.west) to (current page.east);
    \coordinate[xshift=7.425cm,yshift=-5.25cm] (A) at (current page.north west);
    \coordinate[xshift=-7.425cm,yshift=-5.25cm] (B) at (current page.north east);
    \coordinate[xshift=7.425cm,yshift=5.25cm] (C) at (current page.south west);
    \coordinate[xshift=-7.425cm,yshift=5.25cm] (D) at (current page.south east);
    \ifboolKV[ClesSortie]{MemeEnonce}{%
      \foreach\i\in in {A,B,C,D}{%
        \node (\i1) at (\i) {\begin{Sortie}
            #2
            \tcblower
            \BonSortieSmiley
          \end{Sortie}
        };
      }
    }{%
      \node (A1) at (A) {\begin{Sortie}
          #2
          \tcblower
          \BonSortieSmiley
        \end{Sortie}
      };
      \node (B1) at (B) {\begin{Sortie}
          #3
          \tcblower
          \BonSortieSmiley
        \end{Sortie}
      };
      \node (C1) at (C) {\begin{Sortie}
          #4
          \tcblower
          \BonSortieSmiley
        \end{Sortie}
      };
      \node (D1) at (D) {\begin{Sortie}
          #5
          \tcblower
          \BonSortieSmiley
        \end{Sortie}
      };
    }
  \end{tikzpicture}
}

%%%
% Ecriture des nombres en lettres
%%%
\setKVdefault[ClesEcriture]{Math=false,Majuscule=false,E=false,Tradition=false,Zero=false}

\newcommand\EcriturePluriel[1]{%
  \xintifboolexpr{#1 > 1}{s}{}%
}

\newcommand\EcritureDecimale{%
  \StrLen{\ListeEcriture[2]}[\LongueurDecimale]%
  \xintifboolexpr{\LongueurDecimale == 6}{%
    ~millionième\EcriturePluriel{\ListeEcriture[2]}%
  }{\xintifboolexpr{\LongueurDecimale == 5}{%
     ~cent-millième\EcriturePluriel{\ListeEcriture[2]}
    }{\xintifboolexpr{\LongueurDecimale == 4}{%
        ~dix-millième\EcriturePluriel{\ListeEcriture[2]}
      }{\xintifboolexpr{\LongueurDecimale == 3}{%
          ~millième\EcriturePluriel{\ListeEcriture[2]}
        }{\xintifboolexpr{\LongueurDecimale == 2}{%
            ~centième\EcriturePluriel{\ListeEcriture[2]}
          }{\xintifboolexpr{\LongueurDecimale == 1}{%
              ~dixième\EcriturePluriel{\ListeEcriture[2]}
            }{}%
          }%
        }%
      }%
    }%
  }%
}%

\newcommand\Ecriture[2][]{%
  \useKVdefault[ClesEcriture]%
  \setKV[ClesEcriture]{#1}%
  \ifboolKV[ClesEcriture]{Tradition}{%
    \fmtcountsetoptions{french={dash or space=traditional}}%
  }{%
    \fmtcountsetoptions{french={dash or space=always}}%
  }%
  \setsepchar{.}%
  \readlist*\ListeEcriture{#2}%
  \xintifboolexpr{\ListeEcriturelen == 2}{%
    \ifboolKV[ClesEcriture]{Majuscule}{%
      \ifboolKV[ClesEcriture]{Zero}{}{\Numberstringnum{\ListeEcriture[1]}}\ifboolKV[ClesEcriture]{Math}{\ifboolKV[ClesEcriture]{Zero}{}{\ifboolKV[ClesEcriture]{E}{e}{}~unité\EcriturePluriel{\ListeEcriture[1]} et }}{\ifboolKV[ClesEcriture]{Tradition}{ virgule }{-virgule-}}\numberstringnum{\ListeEcriture[2]}\ifboolKV[ClesEcriture]{Math}{\EcritureDecimale}{}%
    }{%
      \ifboolKV[ClesEcriture]{Zero}{}{\numberstringnum{\ListeEcriture[1]}}\ifboolKV[ClesEcriture]{Math}{\ifboolKV[ClesEcriture]{Zero}{}{\ifboolKV[ClesEcriture]{E}{e}{}~unité\EcriturePluriel{\ListeEcriture[1]} et }}{\ifboolKV[ClesEcriture]{Tradition}{ virgule }{-virgule-}}\numberstringnum{\ListeEcriture[2]}\ifboolKV[ClesEcriture]{Math}{\EcritureDecimale}{}%
    }}{%
    \ifboolKV[ClesEcriture]{Majuscule}{%
      \Numberstringnum{\ListeEcriture[1]}\ifboolKV[ClesEcriture]{Math}{\ifboolKV[ClesEcriture]{E}{e}{}~unité\EcriturePluriel{\ListeEcriture[1]}}{}%
    }{%
      \numberstringnum{\ListeEcriture[1]}\ifboolKV[ClesEcriture]{Math}{\ifboolKV[ClesEcriture]{E}{e}{}~unité\EcriturePluriel{\ListeEcriture[1]}}{}%
    }%
  }%
}%

%%%
% D\'ecomposition de fractions d\'ecimales
%%%
\setKVdefault[ClesFracDeci]{Complete=false,SansZero=false,Remediation=false}

\newcommand\FractionDecimale[2][]{%
  \useKVdefault[ClesFracDeci]%
  \setKV[ClesFracDeci]{#1}%
  \setsepchar[*]{/}%
  \readlist*\ListeFractionDecimale{#2}%
  \xdef\FractionDeciNum{\ListeFractionDecimale[1]}%
  \xdef\FractionDeciDeno{\ListeFractionDecimale[2]}%
  \xdef\PartieEntiereFractionDeci{\fpeval{floor(\FractionDeciNum/\FractionDeciDeno)}}%
  \xdef\PartieDecimaleFractionDeci{\fpeval{\FractionDeciNum-floor(\FractionDeciNum/\FractionDeciDeno)*\FractionDeciDeno}}%
  \StrLen{\PartieDecimaleFractionDeci}[\LongueurPartieDecimale]%
  \StrLen{\fpeval{\FractionDeciDeno}}[\LongueurFracDeciDeno]%
  \StrLen{\fpeval{\FractionDeciNum}}[\LongueurFracDeciNum]%
  \xintifboolexpr{\PartieEntiereFractionDeci == 0}{\xdef\LongueurPartieEntiere{0}}{\StrLen{\PartieEntiereFractionDeci}[\LongueurPartieEntiere]}%
  \xintifboolexpr{\PartieEntiereFractionDeci == \fpeval{\FractionDeciNum/\FractionDeciDeno}}{%
    \ensuremath{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\PartieEntiereFractionDeci}}}%
  }{%
    \ifboolKV[ClesFracDeci]{SansZero}{%
      \ensuremath{%
        \xintifboolexpr{\PartieEntiereFractionDeci == 0}{}{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\PartieEntiereFractionDeci}}+}%
        \xintFor* ##1 in {\xintSeq{1}{\LongueurPartieDecimale}}\do{%
          \StrMid{\PartieDecimaleFractionDeci}{##1}{##1}[\ChiffrePartieDecimale]%
          \xintifForFirst{}{\xintifboolexpr{\ChiffrePartieDecimale == 0}{}{+}}\xintifboolexpr{\ChiffrePartieDecimale == 0}{}{\frac{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\ChiffrePartieDecimale}}}{\num{\fpeval{10**(\LongueurFracDeciDeno-1-\LongueurPartieDecimale+##1)}}}}%
        }%
      }%
    }{%
      \ifboolKV[ClesFracDeci]{Complete}{%
        \xintifboolexpr{\FractionDeciNum>\FractionDeciDeno}{%
          \ensuremath{%
            % on affiche la partie entière.
            \xintifboolexpr{\PartieEntiereFractionDeci == 0}{}{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\PartieEntiereFractionDeci}}+}%
            \StrGobbleLeft{\FractionDeciNum}{\fpeval{\LongueurPartieEntiere}}[\DecompositionFracDeciComplete]%
            % on affiche la partie décimale.
            \xintFor* ##1 in {\xintSeq{1}{\fpeval{\LongueurFracDeciNum-\LongueurPartieEntiere}}}\do{%
              \xintifForFirst{}{+}\StrMid{\DecompositionFracDeciComplete}{##1}{##1}[\ChiffrePartieDecimale]\frac{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\ChiffrePartieDecimale}}}{\num{\fpeval{10**##1}}}%
            }%
          }%
        }{%
          \ensuremath{%
            \xintFor* ##1 in {\xintSeq{1}{\LongueurPartieDecimale}}\do{%
              \StrMid{\PartieDecimaleFractionDeci}{##1}{##1}[\ChiffrePartieDecimale]%
              \xintifForFirst{}{+}\frac{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\ChiffrePartieDecimale}}}{\num{\fpeval{10**(\LongueurFracDeciDeno-1-\LongueurPartieDecimale+##1)}}}%
            }%
          }%
        }%
      }{%
        \ensuremath{%
          \xintifboolexpr{\PartieEntiereFractionDeci == 0}{}{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\PartieEntiereFractionDeci}}+}\frac{\ifboolKV[ClesFracDeci]{Remediation}{\dots}{\num{\PartieDecimaleFractionDeci}}}{\num{\FractionDeciDeno}}%
        }%
      }%
    }%
  }%
}%

%%%
% Pyramide de calculs
%%%
\newcommand\DessinePyramideNombreMul[1]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    pair A[],B[],O;
    cote:=\useKV[ClesPyramide]{Cote};
    boolean Aide,Produit,Solution,Vide;
    Aide:=\useKV[ClesPyramide]{Aide};
    Vide:=\useKV[ClesPyramide]{Vide};
    Produit:=\useKV[ClesPyramide]{Produit};
    Solution:=\useKV[ClesPyramide]{Solution};
    A1=u*(1,1);
    A2-A1=cote*(1,0);
    A3=rotation(A2,A1,60);
    A4=A1;
    B1=iso(A1,A2);
    B2=iso(A2,A3);
    B3=iso(A3,A1);
    O=iso(A1,A2,A3);
    path BoiteRec;
    BoiteRec=((-0.4,-0.5)--(0.4,-0.5){dir0}..{dir90}(0.5,-0.4)--(0.5,0.4){dir90}..{dir180}(0.4,0.5)--(-0.4,0.5){dir180}..{dir-90}(-0.5,0.4)--(-0.5,-0.4){dir-90}..cycle) scaled 1u;
    % On trace et on affiche...éventuellement :)
    trace polygone(A1,A2,A3);
    for k=1 upto 3:
    trace segment(O,B[k]) dashed withdots scaled 0.25;
    draw BoiteRec shifted (1.75[O,B[k]]-center BoiteRec) dashed evenly scaled 0.5;
    endfor;
    if Vide:
    else:
    % On récupère les valeurs pour déterminer les produits
    k=0;
    for p_=#1:
    k:=k+1;
    Facteur[k]=p_;
    endfor;
    Produit[1]=Facteur[1] * Facteur[2];
    Produit[2]=Facteur[2] * Facteur[3];
    Produit[3]=Facteur[3] * Facteur[1];
    for k=1 upto 3:
    if Produit or Solution:
    label(TEX("\num{"&decimal(Produit[k])&"}"),(1.75[O,B[k]]-center BoiteRec));
    fi;
    if Produit:
    else:
    label(TEX("\num{"&decimal(Facteur[k])&"}"),(0.5[O,A[k]]-center BoiteRec));
    fi;
    endfor;
    fi;
    if Aide:
    for k=1 upto 3:
    drawarrow (0.5[O,A[k]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (1.75[O,B[k]]-center BoiteRec) dashed evenly scaled 0.5;
    drawarrow (0.5[O,A[k+1]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (1.75[O,B[k]]-center BoiteRec) dashed evenly scaled 0.5;
    endfor;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={cote:=\useKV[ClesPyramide]{Cote};
      boolean Aide,Produit,Solution,Vide;
      Aide:=\useKV[ClesPyramide]{Aide};
      Vide:=\useKV[ClesPyramide]{Vide};
      Produit:=\useKV[ClesPyramide]{Produit};
      Solution:=\useKV[ClesPyramide]{Solution};}]
    pair A[],B[],O;
    A1=u*(1,1);
    A2-A1=cote*(1,0);
    A3=rotation(A2,A1,60);
    A4=A1;
    B1=iso(A1,A2);
    B2=iso(A2,A3);
    B3=iso(A3,A1);
    O=iso(A1,A2,A3);
    path BoiteRec;
    BoiteRec=((-0.4,-0.5)--(0.4,-0.5){dir0}..{dir90}(0.5,-0.4)--(0.5,0.4){dir90}..{dir180}(0.4,0.5)--(-0.4,0.5){dir180}..{dir-90}(-0.5,0.4)--(-0.5,-0.4){dir-90}..cycle) scaled 1u;
    % On trace et on affiche...éventuellement :)
    trace polygone(A1,A2,A3);
    for k=1 upto 3:
    trace segment(O,B[k]) dashed withdots scaled 0.25;
    draw BoiteRec shifted (1.75[O,B[k]]-center BoiteRec) dashed evenly scaled 0.5;
    endfor;
    if Vide:
    else:
    % On récupère les valeurs pour déterminer les produits
    k=0;
    for p_=#1:
    k:=k+1;
    Facteur[k]=p_;
    endfor;
    Produit[1]=Facteur[1] * Facteur[2];
    Produit[2]=Facteur[2] * Facteur[3];
    Produit[3]=Facteur[3] * Facteur[1];
    for k=1 upto 3:
    if Produit or Solution:
    label(TEX("\num{"&decimal(Produit[k])&"}"),(1.75[O,B[k]]-center BoiteRec));
    fi;
    if Produit:
    else:
    label(TEX("\num{"&decimal(Facteur[k])&"}"),(0.5[O,A[k]]-center BoiteRec));
    fi;
    endfor;
    fi;
    if Aide:
    for k=1 upto 3:
    drawarrow (0.5[O,A[k]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (1.75[O,B[k]]-center BoiteRec) dashed evenly scaled 0.5;
    drawarrow (0.5[O,A[k+1]]--1.75[O,B[k]]) cutbefore segment(A[k],A[k+1]) cutafter BoiteRec shifted (1.75[O,B[k]]-center BoiteRec) dashed evenly scaled 0.5;
    endfor;
    fi;
  \end{mpost}
  \fi
}

\newcommand\DessinePyramideNombre[1]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    pair A[][],B[];
    path Case[];
    color CaseCouleur;
    nbetages:=\useKV[ClesPyramide]{Etages};
    largeur:=\useKV[ClesPyramide]{Largeur};
    hauteur:=\useKV[ClesPyramide]{Hauteur};
    CaseCouleur:=\useKV[ClesPyramide]{Couleur};
    boolean Double;
    Double=\useKV[ClesPyramide]{Double};
    Nbeb:=0;%Pour associer les textes avec les points. Plus facile :)
    if Double:
    for k=nbetages downto 1:
    for l=0 upto (k-1):
    Nbeb:=Nbeb+1;
    A[k][l]=(0,0)+(nbetages-k)*(largeur/2,0)+(l*largeur,(nbetages-k)*hauteur);
    B[Nbeb]=A[k][l];
    Case[Nbeb]=((unitsquare xscaled largeur) yscaled hauteur) shifted (A[k][l]-0.5*(largeur,hauteur));
    trace Case[Nbeb];
    endfor;
    endfor;
    for k=nbetages-1 downto 1:
    for l=0 upto (k-1):
    Nbeb:=Nbeb+1;
    A[-k][l]=(0,0)+(nbetages-k)*(largeur/2,0)+(l*largeur,-(nbetages-k)*hauteur);
    B[Nbeb]=A[-k][l];
    Case[Nbeb]=((unitsquare xscaled largeur) yscaled hauteur) shifted (A[-k][l]-0.5*(largeur,hauteur));
    trace Case[Nbeb];
    endfor;
    endfor;
    else:
    if \useKV[ClesPyramide]{Inverse}:
    change:=-1;
    else:
    change=1;
    fi;
    for k=nbetages downto 1:
    for l=0 upto (k-1):
    Nbeb:=Nbeb+1;
    A[k][l]=(0,0)+(nbetages-k)*(largeur/2,0)+(l*largeur,change*(nbetages-k)*hauteur);
    B[Nbeb]=A[k][l];
    Case[Nbeb]=((unitsquare xscaled largeur) yscaled hauteur) shifted (A[k][l]-0.5*(largeur,hauteur));
    trace Case[Nbeb];
    endfor;
    endfor;
    fi;
    if \useKV[ClesPyramide]{Vide}:
    else:
    Nbeb:=0;
    for p_=#1:
    Nbeb:=Nbeb+1;
    if (substring(0,1) of p_)="*":
    fill Case[Nbeb] withcolor CaseCouleur;
    trace Case[Nbeb];
    label(TEX(substring(1,length p_) of p_),B[Nbeb]);
    elseif (substring(0,1) of p_)="!":
    drawoptions(withcolor \useKV[ClesPyramide]{CouleurNombre});
    label(TEX(substring(1,length p_) of p_),B[Nbeb]);
    drawoptions();
    else:
    label(TEX(p_),B[Nbeb]);
    fi;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={nbetages:=\useKV[ClesPyramide]{Etages};largeur:=\useKV[ClesPyramide]{Largeur};hauteur:=\useKV[ClesPyramide]{Hauteur};boolean Vide;Vide=\useKV[ClesPyramide]{Vide};boolean Inverse;Inverse=\useKV[ClesPyramide]{Inverse};color CaseCouleur; CaseCouleur:=\useKV[ClesPyramide]{Couleur};boolean Double;Double=\useKV[ClesPyramide]{Double}; color CouleurNombre;CouleurNombre=\useKV[ClesPyramide]{CouleurNombre};}]
    pair A[][],B[];
    path Case[];
    Nbeb:=0;
    if Double:
    for k=nbetages downto 1:
    for l=0 upto (k-1):
    Nbeb:=Nbeb+1;
    A[k][l]=(0,0)+(nbetages-k)*(largeur/2,0)+(l*largeur,(nbetages-k)*hauteur);
    B[Nbeb]=A[k][l];
    Case[Nbeb]=((unitsquare xscaled largeur) yscaled hauteur) shifted (A[k][l]-0.5*(largeur,hauteur));
    trace Case[Nbeb];
    endfor;
    endfor;
    for k=nbetages-1 downto 1:
    for l=0 upto (k-1):
    Nbeb:=Nbeb+1;
    A[-k][l]=(0,0)+(nbetages-k)*(largeur/2,0)+(l*largeur,-(nbetages-k)*hauteur);
    B[Nbeb]=A[-k][l];
    Case[Nbeb]=((unitsquare xscaled largeur) yscaled hauteur) shifted (A[-k][l]-0.5*(largeur,hauteur));
    trace Case[Nbeb];
    endfor;
    endfor;
    else:
    if \useKV[ClesPyramide]{Inverse}:
    change:=-1;
    else:
    change=1;
    fi;
    for k=nbetages downto 1:
    for l=0 upto (k-1):
    Nbeb:=Nbeb+1;
    A[k][l]=(0,0)+(nbetages-k)*(largeur/2,0)+(l*largeur,change*(nbetages-k)*hauteur);
    B[Nbeb]=A[k][l];
    Case[Nbeb]=((unitsquare xscaled largeur) yscaled hauteur) shifted (A[k][l]-0.5*(largeur,hauteur));
    trace Case[Nbeb];
    endfor;
    endfor;
    fi;
    if \useKV[ClesPyramide]{Vide}:
    else:
    Nbeb:=0;
    for p_=#1:
    Nbeb:=Nbeb+1;
    if (substring(0,1) of p_)="*":
    fill Case[Nbeb] withcolor CaseCouleur;
    trace Case[Nbeb];
    label(LATEX(substring(1,length p_) of p_),B[Nbeb]);
    elseif (substring(0,1) of p_)="!":
    drawoptions(withcolor CouleurNombre);
    label(LATEX(substring(1,length p_) of p_),B[Nbeb]);
    drawoptions();
    else:
    label(LATEX(p_),B[Nbeb]);
    fi;
    endfor;
  \end{mpost}
  \fi
}%

\setKVdefault[ClesPyramide]{Etages=5,Largeur=2cm,Hauteur=1cm,Vide=false,Inverse=false,Double=false,Couleur=Crimson,Multiplication=false,CouleurNombre=blue,Produit=false,Solution=false,Aide=false,Cote=4cm}%

\newtoks\toklistecaseP%
\def\UpdatetoksPyramide#1\nil{\addtotok\toklistecaseP{"#1",}}%
\def\UpdatetoksPyramideMul#1\nil{\addtotok\toklistecaseP{#1,}}%

\NewDocumentCommand\PyramideNombre{o m}{%
  \useKVdefault[ClesPyramide]%
  \setKV[ClesPyramide]{#1}%
  \ifboolKV[ClesPyramide]{Multiplication}{%
    \ifx\bla#2\bla%
    \setKV[ClesPyramide]{Vide=true}%
    \DessinePyramideNombreMul{\the\toklistecaseP}%
    \else
    \setsepchar{,}%
    \readlist*\ListePyramide{#2}%
    \DessinePyramideNombreMul{\ListePyramide[1],\ListePyramide[2],\ListePyramide[3]}%
    \fi
  }{%
    \ifx\bla#2\bla%
    \setKV[ClesPyramide]{Vide=true}%
    \DessinePyramideNombre{\the\toklistecaseP}%
    \else%
    \setsepchar{,}%
    \readlist*\ListePyramide{#2}%
    \ifboolKV[ClesPyramide]{Double}{%
      \def\CalculNombreComposants{\fpeval{\useKV[ClesPyramide]{Etages}*\useKV[ClesPyramide]{Etages}}}%
    }{%
      \def\CalculNombreComposants{\fpeval{\useKV[ClesPyramide]{Etages}*(\useKV[ClesPyramide]{Etages}+1)/2}}%
    }%
    \xintifboolexpr{\ListePyramidelen==\CalculNombreComposants}{%
      \toklistecaseP{}%
      \foreachitem\compteur\in\ListePyramide{\expandafter\UpdatetoksPyramide\compteur\nil}%
      \DessinePyramideNombre{\the\toklistecaseP}%
    }{Le nombre d'éléments dans la liste des propositions n'est pas compatible avec le nombre d'étages choisi.}%
    \fi%
  }%
}%

%%%
% Tables Addition-Multiplication
%%%
\setKVdefault[Tables]{Addition=false,Multiplication=true,Seul=false,Debut=0,Fin=10,Couleur=white}

% pour m\'emoire
\newcommand\TableMultiplicationComplete{%
  \xdef\NbColTabMul{\fpeval{\useKV[Tables]{Fin}+1-\useKV[Tables]{Debut}}}%
  \begin{tabular}{|>{\columncolor{gray!15}\centering\arraybackslash}p{1.5em}|*{\NbColTabMul}{>{\centering\arraybackslash}p{1.5em}|}}%
    \hline
    $\times$\xintFor* ##1 in {\xintSeq {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{%
    &\cellcolor{gray!15}\fpeval{##1}
      }
    \\
    \hline
    \xintFor* ##1 in {\xintSeq {0}{10}}\do{%
    ##1\xintFor* ##2 in {\xintSeq {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{%
    &\fpeval{##2*##1}
      }
    \\
    \hline
    }
  \end{tabular}%
}
%%%%

\newcommand\TableMultiplicationCompleteColore{%
  \xdef\NbColTabMul{\fpeval{\useKV[Tables]{Fin}+1-\useKV[Tables]{Debut}}}%
  \begin{tabular}{|>{\columncolor{gray!15}\centering}p{15pt}|*{\NbColTabMul}{>{\centering\arraybackslash}p{15pt}|}}%
    \hline
    $\times$\xintFor* ##1 in {\xintSeq {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{%
    &\cellcolor{gray!15}\fpeval{##1}%
      }
    \\
    \hline
    \xintFor* ##1 in {\xintSeq {0}{10}}\do{%
    ##1\xintFor* ##2 in {\xintSeq {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{%
    &\xintifboolexpr{##2<##1}{\cellcolor{\useKV[Tables]{Couleur}!\fpeval{##1*10}}}{\xintifboolexpr{##2>##1}{\cellcolor{\useKV[Tables]{Couleur}!\fpeval{##2*10}}}{}}\fpeval{##2*##1}%
      }%
    \\
    \hline
    }%
  \end{tabular}%
}%

\newcommand\TableAdditionComplete{%
  \xdef\NbColTabMul{\fpeval{\useKV[Tables]{Fin}+1-\useKV[Tables]{Debut}}}%
  \begin{tabular}{|>{\columncolor{gray!15}\centering}p{15pt}|*{\NbColTabMul}{>{\centering\arraybackslash}p{15pt}|}}%
    \hline
    $+$\xintFor* ##1 in {\xintSeq {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{%
    &\cellcolor{gray!15}\fpeval{##1}
      }
    \\
    \hline
    \xintFor* ##1 in {\xintSeq {0}{10}}\do{%
    ##1\xintFor* ##2 in {\xintSeq {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{%
    &\fpeval{##2+##1}
      }
    \\
    \hline
    }
  \end{tabular}%
}

\newcommand\TableMultiplicationSeule[1]{%
  \ensuremath{%
    \begin{array}{ccccc}%
      \xintFor* ##1 in {\xintSeq
      {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{
      ##1&\times&#1&=&\fpeval{##1*#1}\\
      }
    \end{array}
  }%
}%

\newcommand\TableAdditionSeule[1]{%
  \ensuremath{%
    \begin{array}{ccccc}
      \xintFor* ##1 in {\xintSeq
      {\useKV[Tables]{Debut}}{\useKV[Tables]{Fin}}}\do{
      ##1&+&#1&=&\fpeval{##1+#1}\\
      }
    \end{array}
  }%
}%

\newcommand\Tables[2][]{%
  \useKVdefault[Tables]%
  \setKV[Tables]{#1}%
  \ifboolKV[Tables]{Seul}{%
    \ifboolKV[Tables]{Addition}{%
      \TableAdditionSeule{#2}%
    }{%
      \TableMultiplicationSeule{#2}%
    }%
  }{%
    \ifboolKV[Tables]{Addition}{%
      \TableAdditionComplete%
    }{%
      \TableMultiplicationCompleteColore%
    }%
  }%
}%

%%%
% Defi Table
%%%

\setKVdefault[DefiTable]{Solution=false,Math=false,LargeurT=5mm,Graines=false,Creation=false}
\defKV[DefiTable]{Graine=\setKV[DefiTable]{Graines}}%

\newcommand\MelangeListeNew[2]{%
  % #1 Liste à mélanger
  % #2 Nombre d'éléments à conserver
  \setsepchar[*]{/}\ignoreemptyitems%
  \readlist*\ListeInter{#1}%
  \xdef\faa{}% Liste construite
  \xdef\fii{}% Liste détruite
  % on crée les #2 premieres solutions.
  \xintFor* ##1 in {\xintSeq{1}{#2}}\do{%
    \xintifboolexpr{\ListeInterlen>1}{%
      \xdef\Alea{\fpeval{randint(\ListeInterlen)}}%
      \xdef\faa{\faa \ListeInter[\Alea]/}%
      \xdef\fii{}%
      \xintFor* ##2 in {\xintSeq{1}{\ListeInterlen}}\do{%
        \xintifboolexpr{##2 == \Alea}{%
        }{%
          \xdef\fii{\fii \ListeInter[##2]/}%
        }%
      }%
    }{%
      \xdef\faa{\faa \ListeInter[1]}%
    }%
    \readlist*\ListeInter{\fii}%
  }%
  \reademptyitems%
}%

\newcommand\DefiTableNombreLettreduCode[1]{%
  \xdef\ListeDesCaracteresFoo{a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/à/é/è/ê/ï/î/ô/ö/ù/ç/A/B/C/D/E/F/G/H/I/J/K/L/M/N/O/P/Q/R/S/T/U/V/W/X/Y/Z/À/É/È/,/$?$/$;$/./$!$/$:$/-}
  \savecomparemode%
  \comparestrict%
  \xdef\PfCFooDepart{}
  \StrLen{#1}[\LongueurMot]%
  \xintFor* ##1 in{\xintSeq{1}{\LongueurMot}}\do{%
    \StrChar{#1}{##1}[\LettreMot]
    \xdef\PfCFooDepart{\PfCFooDepart \LettreMot/}
  }%
  \setsepchar[*]{/}\reademptyitems%
  \readlist*\ListeDesLettres{\PfCFooDepart}%
  \xdef\PfCFooArrivee{\ListeDesLettres[1]}%
  \xintFor* ##1 in{\xintSeq{2}{\LongueurMot}}\do{%
    \StrCompare{\ListeDesLettres[##1]}{\\}[\PfCRetiensEtoile]
    \StrCompare{\ListeDesLettres[##1]}{ }[\PfCRetiensPara]
    \xintifboolexpr{\PfCRetiensEtoile==0 || \PfCRetiensPara==0}{}{%
      \xdef\PfCTotal{0}%
      \xintFor* ##2 in{\xintSeq{1}{\fpeval{##1-1}}}\do{%
        \StrCompare{\ListeDesLettres[##1]}{\ListeDesLettres[##2]}[\PfCRetiens]
        \xdef\PfCTotal{\fpeval{\PfCTotal+\PfCRetiens}}%
      }%
      \xintifboolexpr{\PfCTotal==\fpeval{##1-1}}{\xdef\PfCFooArrivee{\PfCFooArrivee/\ListeDesLettres[##1]}}{}%
    }%
  }%
  %Arrivee = \PfCFooArrivee\par
  \setsepchar[*]{/}\ignoreemptyitems%
  \readlist*\ListeDesLettresUniques{\PfCFooArrivee}%
  %La liste des lettres uniques ainsi créée :\par
  %\showitems\ListeDesLettresUniques[]%
  % Il faut retirer les lettres uniques de la liste des caracteres
  \readlist*\ListeTotaleDesCaracteres{\ListeDesCaracteresFoo}%
  %\par
  %La liste totale des caractères est :\par
  %\showitems\ListeTotaleDesCaracteres[]
  %\par
  \xdef\ListeCaracteresUniques{}%
  \xintFor* ##1 in{\xintSeq{1}{\ListeTotaleDesCaractereslen}}\do{%
    %Le caractère testé est \ListeTotaleDesCaracteres[##1]. On le compare à :%
    \xdef\PfCTotal{0}%
    \xintFor* ##2 in{\xintSeq{1}{\ListeDesLettresUniqueslen}}\do{%
      \StrCompare{\ListeTotaleDesCaracteres[##1]}{\ListeDesLettresUniques[##2]}[\PfCRetiens]
      \xdef\PfCTotal{\fpeval{\PfCTotal+\PfCRetiens}}%
    }%
    \xintifboolexpr{\PfCTotal==\ListeDesLettresUniqueslen}{\xdef\ListeCaracteresUniques{\ListeCaracteresUniques\ListeTotaleDesCaracteres[##1]/}}{}%
  }%
  %La liste des caractères uniques à ajouter
  \MelangeListeNew{\ListeCaracteresUniques}{\fpeval{42-\ListeDesLettresUniqueslen}}%
  %\par La liste des éléments à mélanger est :\par
  \xdef\ListeDesCaracteresAUtiliser{}
  \xintFor* ##1 in{\xintSeq{1}{\ListeDesLettresUniqueslen}}\do{%
    \xdef\ListeDesCaracteresAUtiliser{\ListeDesCaracteresAUtiliser \ListeDesLettresUniques[##1]/}%
  }%
  \xdef\ListeDesCaracteresAUtiliser{\ListeDesCaracteresAUtiliser \faa}
  \MelangeListeNew{\ListeDesCaracteresAUtiliser}{42}
  %Finalement, on utilise ces caractères :\par
  \ignoreemptyitems%
  \readlist*\ListeFinaleDesCaracteres{\faa}
  \xdef\ListeDesProduitsFoo{1/2/3/4/5/6/7/8/9/10/12/14/16/18/20/15/21/24/27/30/28/32/36/40/25/35/45/50/42/48/54/60/49/56/63/70/64/72/80/81/90/100}
  \MelangeListeNew{\ListeDesProduitsFoo}{42}
  %Les produits mélangés sont :\par
  \readlist*\ListeDesProduits{\faa}%
  \restorecomparemode
  \reademptyitems
}

\newcommand\DefiTable[2][]{%
  % 1 les clés
  % 2 la table de décodage
  \useKVdefault[DefiTable]%
  \setKV[DefiTable]{#1}%
  \ifboolKV[DefiTable]{Creation}{
    \ifboolKV[DefiTable]{Graines}{\PfCGraineAlea{\useKV[DefiTable]{Graine}}}{}%
    \DefiTableNombreLettreduCode{#2}
    \begin{center}
      \begin{tabular}{|>{\columncolor{gray!15}}c|*{10}{c|}}
        \hline
        \rowcolor{gray!15}$\times$&\xintFor* ##1 in {\xintSeq {1}{10}}\do{%
                                    \xintifForFirst{}{&}##1%
                                                        }\\\hline%
        \xintFor* ##1 in{\xintSeq{1}{10}}\do{%
        ##1\xintFor* ##2 in{\xintSeq{1}{10}}\do{%
                                  &\xintFor* ##3 in{\xintSeq{1}{42}}\do{%
                                    \xintifboolexpr{\fpeval{##1*##2}==\ListeDesProduits[##3]}{\ListeFinaleDesCaracteres[##3]}{}%
                                    }%
                                    }\\\hline%
        }%
      \end{tabular}%
    \end{center}
  }{%
  \setsepchar[*]{§* }%
  \readlist*\ListeDefiTableCode{#2}%
  \begin{NiceTabular}{>{\columncolor{gray!15}}{c}*{10}{c}}[hvlines]
    \rowcolor{gray!15}$\times$&\xintFor* ##1 in {\xintSeq {1}{10}}\do{%
      \xintifForFirst{}{&}##1}
    \\
    1\xintFor* ##1 in {\xintSeq {1}{10}}\do{%
      &\ListeDefiTableCode[1,##1]%
    }\\
    \xintFor* ##1 in {\xintSeq {2}{9}}\do{%
      ##1\xintFor* ##2 in {\xintSeq {1}{##1}}\do{%
        &\ListeDefiTableCode[##2,\fpeval{##1-##2+1}]%
      }\xintFor* ##2 in {\xintSeq {1}{\fpeval{10-##1}}}\do{%
        &\ListeDefiTableCode[##1,\fpeval{##2+1}]%
        }%
      \\
    }%
    10&\ListeDefiTableCode[1,10]&\ListeDefiTableCode[2,9]&\ListeDefiTableCode[3,8]&\ListeDefiTableCode[4,7]&\ListeDefiTableCode[5,6]&\ListeDefiTableCode[6,5]&\ListeDefiTableCode[7,4]&\ListeDefiTableCode[8,3]&\ListeDefiTableCode[9,2]&\ListeDefiTableCode[10,1]\\
  \end{NiceTabular}%
  }%
}%

\newcommand\DefiTableTexte[3][]{%
  \useKVdefault[DefiTable]%
  \setKV[DefiTable]{#1}%
  \ifboolKV[DefiTable]{Creation}{%
    \setsepchar[*]{\\* }%
    \readlist*\ListeDefiTableTableau{#3}%
    \xdef\ListeDefiTableMax{0}%
    \xintFor* ##1 in{\xintSeq{1}{\ListeDefiTableTableaulen}}\do{%
      \StrLen{\ListeDefiTableTableau[##1]}[\PfCDTLongueur]%
      \xintifboolexpr{\ListeDefiTableMax<\PfCDTLongueur}{\xdef\ListeDefiTableMax{\fpeval{\PfCDTLongueur}}}{}%%
    }%
    %\par Le max est \ListeDefiTableMax
    \begin{NiceTabular}{*{\fpeval{\ListeDefiTableMax}}{>{\centering\arraybackslash}m{\useKV[DefiTable]{LargeurT}}}}
      \xintFor* ##1 in {\xintSeq {1}{\fpeval{\ListeDefiTableTableaulen}}}\do{%
        \StrLen{\ListeDefiTableTableau[##1]}[\PfCDTLongueur]%
        \xintFor* ##2 in {\xintSeq {1}{\PfCDTLongueur}}\do{%
          \xintifForFirst{}{&}%
          \StrMid{\ListeDefiTableTableau[##1]}{##2}{##2}[\DefiTableMaLettre]%
          \IfStrEq{\DefiTableMaLettre}{ }{\Block[]{1-1}{}}{\Block[borders={bottom}]{1-1}{\ifboolKV[DefiTable]{Solution}{\StrMid{\ListeDefiTableTableau[##1]}{##2}{##2}}{}}}%
        }\\
        \StrLen{\ListeDefiTableTableau[##1]}[\PfCDTLongueur]%
        \xintFor* ##2 in {\xintSeq {1}{\PfCDTLongueur}}\do{%
          \xintifForFirst{}{&}%
          \StrMid{\ListeDefiTableTableau[##1]}{##2}{##2}[\DefiTableMaLettre]%
          \IfStrEq{\DefiTableMaLettre}{*}{}{%
            \xintFor* ##3 in{\xintSeq{1}{42}}\do{%
              \IfStrEq{\DefiTableMaLettre}{\ListeFinaleDesCaracteres[##3]}{\Block{}{\footnotesize\ListeDesProduits[##3]}}{}%
            }%
          }%
        }\\
        \StrLen{\ListeDefiTableTableau[##1]}[\PfCDTLongueur]%
        \xintFor* ##2 in {\xintSeq {1}{\PfCDTLongueur}}\do{%
          \xintifForFirst{}{&}
        }\\
      }%
    \end{NiceTabular}%
  }{%
    \setsepchar[*]{§*/}%
    \readlist*\ListeDefiTableTableau{#2}%
    \xdef\ListeDefiTableMax{0}%
    \setsepchar{§}%
    \readlist*\ListeDefiTablePhrase{#3}%
    \foreachitem\compteur\in\ListeDefiTableTableau{%
      \xintifboolexpr{\ListeDefiTableMax<\listlen\ListeDefiTableTableau[\compteurcnt]}{\xdef\ListeDefiTableMax{\fpeval{\listlen\ListeDefiTableTableau[\compteurcnt]}}}{}%
    }%
    \begin{NiceTabular}{*{\fpeval{\ListeDefiTableMax}}{>{\centering\arraybackslash}m{\useKV[DefiTable]{LargeurT}}}}
      \xintFor* ##1 in {\xintSeq {1}{\fpeval{\ListeDefiTableTableaulen}}}\do{%
        \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeDefiTableTableau[##1]}}\do{%
          \xintifForFirst{}{&}\ifboolKV[DefiTable]{Solution}{%
            \StrMid{\ListeDefiTablePhrase[##1]}{##2}{##2}[\DefiTableMaLettre]%
            \IfStrEq{\DefiTableMaLettre}{*}{\Block[]{2-1}{}}{\Block[borders={bottom}]{2-1}{\StrMid{\ListeDefiTablePhrase[##1]}{##2}{##2}}}%
          }{%
            \IfStrEq{\ListeDefiTableTableau[##1,##2]}{*}{\Block[]{2-1}{}}{\Block[borders={bottom}]{2-1}{}}%
          }%%
        }\\
        \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeDefiTableTableau[##1]}}\do{%
          \xintifForFirst{}{&}
        }\\
        \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeDefiTableTableau[##1]}}\do{%
          \xintifForFirst{}{&}\IfStrEq{\ListeDefiTableTableau[##1,##2]}{*}{}{\footnotesize\ifboolKV[DefiTable]{Math}{\ListeDefiTableTableau[##1,##2]}{\num{\ListeDefiTableTableau[##1,##2]}}}%
        }\\
      }%
    \end{NiceTabular}%
  }%
}%

%%%
% Rangement des nombres
%%%
\setKVdefault[ClesRgt]{Croissant,Decroissant=false,Strict,Fraction=false,Details=false}

\dtlexpandnewvalue%
\DTLgnewdb{mtnumedb}%
\DTLgnewdb{mtRGTdb}% Pb de doublon avec mtdb de Mediane

\newcommand\Rangement[2][]{%
  \useKVdefault[ClesRgt]%
  \setKV[ClesRgt]{#1}%
  \ifboolKV[ClesRgt]{Fraction}{%
    \setsepchar[*]{,*/}\ignoreemptyitems%
    \readlist*\ListeRgt{#2}%
    % on cherche le d\'enominateur commun
    \ppcm=1\relax
    \foreachitem\x\in\ListeRgt{%
      \PPCM{\fpeval{\ListeRgt[\xcnt,2]}}{\fpeval{\the\ppcm}}%
    }%
    % On cr\'ee la liste des rangements.
    \DTLcleardb{mtnumedb}%
%    % on les trie pour les ranger par ordre croissant
    \foreachitem\x\in\ListeRgt{%
      \DTLnewrow{mtnumedb}%
      \xdef\toto{\fpeval{\ListeRgt[\xcnt,1]*\the\ppcm/\ListeRgt[\xcnt,2]}}%
      \DTLnewdbentry{mtnumedb}{numeric}{\toto}%
    }%
%    % On trie
    \ifboolKV[ClesRgt]{Decroissant}{%
%      % On trie la liste
      \dtlsort{numeric=descending}{mtnumedb}{\dtlicompare}%
      \ifboolKV[ClesRgt]{Details}{\ensuremath{\DTLforeach{mtnumedb}{\numeroDonnee=numeric}{\frac{\num{\numeroDonnee}}{\num{\the\ppcm}}\DTLiflastrow{}{\ifboolKV[ClesRgt]{Strict}{>}{\geqslant}}}}}{%
        \ensuremath{\DTLforeach{mtnumedb}{\numeroDonnee=numeric}{\Simplification{\numeroDonnee}{\ppcm}\DTLiflastrow{}{\ifboolKV[ClesRgt]{Strict}{>}{\geqslant}}}}%
      }
    }{%
%      % On trie la liste
      \dtlsort{numeric}{mtnumedb}{\dtlicompare}%
      \ifboolKV[ClesRgt]{Details}{%
        \ensuremath{\DTLforeach{mtnumedb}{\numeroDonnee=numeric}{\frac{\num{\numeroDonnee}}{\num{\the\ppcm}}\DTLiflastrow{}{\ifboolKV[ClesRgt]{Strict}{<}{\leqslant}}}}%
      }{%
        \ensuremath{\DTLforeach{mtnumedb}{\numeroDonnee=numeric}{\Simplification{\numeroDonnee}{\ppcm}\DTLiflastrow{}{\ifboolKV[ClesRgt]{Strict}{<}{\leqslant}}}}%
      }%
    }%
  }{%
    \setsepchar{,}\ignoreemptyitems%
    \readlist*\ListeRgt{#2}%
    % on cr\'ee la base de donn\'ees des valeurs
    \DTLcleardb{mtRGTdb}%
%    % on les trie pour les ranger par ordre croissant
    \foreachitem\x\in\ListeRgt{%
      \DTLnewrow{mtRGTdb}%
      \itemtomacro\ListeRgt[\xcnt]\y%
      \DTLnewdbentry{mtRGTdb}{numeric}{\y}%
    }%
%    % 
    \ifboolKV[ClesRgt]{Decroissant}{%
      % On trie la liste
      \dtlsort{numeric=descending}{mtRGTdb}{\dtlicompare}%
      \ensuremath{\DTLforeach{mtRGTdb}{\numeroDonnee=numeric}{\num{\numeroDonnee}\DTLiflastrow{}{\ifboolKV[ClesRgt]{Strict}{>}{\geqslant}}}}%
    }{%
%      % On trie la liste
      \dtlsort{numeric}{mtRGTdb}{\dtlicompare}%
      \ensuremath{\DTLforeach{mtRGTdb}{\numeroDonnee=numeric}{\num{\numeroDonnee}\DTLiflastrow{}{\ifboolKV[ClesRgt]{Strict}{<}{\leqslant}}}}%
    }%
  }%
}%

%%%
% Mots Cod\'es
%%%
\setKVdefault[MotsCodes]{LargeurT=1cm,Colonnes=5,Largeur=3cm,Solution=false,Math=false}%

\newcommand\MotsCodes[2][]{%
  \useKVdefault[MotsCodes]%
  \setKV[MotsCodes]{#1}%
  \setsepchar[*]{§*/}%
  \readlist*\ListeMotsCodes{#2}%
  \xdef\ListeMotsCodesPas{\fpeval{\ListeMotsCodeslen/\useKV[MotsCodes]{Colonnes}}}%
  \begin{NiceTabular}{*{\fpeval{\useKV[MotsCodes]{Colonnes}}}{>{\centering\arraybackslash}m{\useKV[MotsCodes]{Largeur}}}}
    \xintFor* ##1 in {\xintSeq {1}{\ListeMotsCodesPas}}\do{%
      \xintFor* ##2 in {\xintSeq {1}{\fpeval{\useKV[MotsCodes]{Colonnes}}}}\do{%
        \xintifForFirst{}{&}\Block[draw=black]{4-1}{}%
      }\\
      \xintFor* ##2 in {\xintSeq {1}{\fpeval{\useKV[MotsCodes]{Colonnes}}}}\do{%
        \xintifForFirst{}{&}\ListeMotsCodes[\fpeval{(##1-1)*\useKV[MotsCodes]{Colonnes}+##2},1]
      }\\
      \xintFor* ##2 in {\xintSeq {1}{\fpeval{\useKV[MotsCodes]{Colonnes}}}}\do{%
        \xintifForFirst{}{&}%
      }\\
      \xintFor* ##2 in {\xintSeq {1}{\fpeval{\useKV[MotsCodes]{Colonnes}}}}\do{%
        \xintifForFirst{}{&}\textbf{\Large\ListeMotsCodes[\fpeval{(##1-1)*\useKV[MotsCodes]{Colonnes}+##2},2]}
      }\\
    }%
  \end{NiceTabular}%
}%

\newcommand\MotsCodesTableau[3][]{%
  \useKVdefault[MotsCodes]%
  \setKV[MotsCodes]{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeMotsCodesTableau{#2}%
  \xdef\ListeMotsCodesMax{0}%
  \setsepchar{,}%
  \readlist*\ListeMotsCodesPhrase{#3}%
  \foreachitem\compteur\in\ListeMotsCodesTableau{%
    \xintifboolexpr{\ListeMotsCodesMax<\listlen\ListeMotsCodesTableau[\compteurcnt]}{\xdef\ListeMotsCodesMax{\fpeval{\listlen\ListeMotsCodesTableau[\compteurcnt]}}}{}%
  }%
  \begin{NiceTabular}{*{\fpeval{\ListeMotsCodesMax}}{>{\centering\arraybackslash}m{\useKV[MotsCodes]{LargeurT}}}}
    \xintFor* ##1 in {\xintSeq {1}{\fpeval{\ListeMotsCodesTableaulen}}}\do{%
      \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeMotsCodesTableau[##1]}}\do{%
        \xintifForFirst{}{&}\ifboolKV[MotsCodes]{Solution}{%
          \StrMid{\ListeMotsCodesPhrase[##1]}{##2}{##2}[\MotsCodesMaLettre]%
          \IfStrEq{\MotsCodesMaLettre}{*}{\Block[draw=black,fill=black]{3-1}{}}{\Block[draw=black]{3-1}{\StrMid{\ListeMotsCodesPhrase[##1]}{##2}{##2}}}%
        }{%
          \IfStrEq{\ListeMotsCodesTableau[##1,##2]}{*}{\Block[draw=black,fill=black]{3-1}{}}{\Block[draw=black]{3-1}{}}%
        }%%
      }\\
      \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeMotsCodesTableau[##1]}}\do{%
        \xintifForFirst{}{&}
      }\\
      \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeMotsCodesTableau[##1]}}\do{%
        \xintifForFirst{}{&}\IfStrEq{\ListeMotsCodesTableau[##1,##2]}{*}{}{\footnotesize\ifboolKV[MotsCodes]{Math}{\ListeMotsCodesTableau[##1,##2]}{\num{\ListeMotsCodesTableau[##1,##2]}}}%
      }\\
    }%
  \end{NiceTabular}%
}%

%%%
% Labyrinthe
%%%
\setKVdefault[Labyrinthe]{Lignes=6,Colonnes=3,Longueur=4,Hauteur=2,Passages=false,EcartH=1,EcartV=1,CouleurF=gray!50,Texte=\color{black},SensImpose=false,Slop}

\tikzset{FDirect/.style={-stealth}}
\tikzset{FIndirect/.style={stealth-}}
\tikzset{FBidirect/.style={stealth-stealth}}

\newcommand\Labyrinthe[3][]{%
  \useKVdefault[Labyrinthe]%
  \setKV[Labyrinthe]{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeLaby{#2}%
  \xdef\LabySlop{\ifboolKV[Labyrinthe]{Slop}{sloped}{}}%
  \ifboolKV[Labyrinthe]{Passages}{%
    \readlist*\ListeLabySol{#3}%
  }{}%
  \xdef\LabyLong{\useKV[Labyrinthe]{Longueur}}%
  \xdef\LabyHaut{\useKV[Labyrinthe]{Hauteur}}%
  \ifboolKV[Labyrinthe]{SensImpose}{%
    \xdef\TotalLaby{\fpeval{4*(\useKV[Labyrinthe]{Colonnes}-1)+1}}%
  }{%
    \xdef\TotalLaby{\fpeval{3*\useKV[Labyrinthe]{Colonnes}-2}}%
  }%
  \xdef\CouleurF{\useKV[Labyrinthe]{CouleurF}}%
  \xdef\MotifTexte{\noexpand\useKV[Labyrinthe]{Texte}}%
  \xintifboolexpr{\ListeLabylen==\fpeval{\useKV[Labyrinthe]{Lignes}*\useKV[Labyrinthe]{Colonnes}}}{%
    \begin{tikzpicture}[remember picture]%
%      % on dessine les cadres
      \foreach \compteurv in {1,...,\useKV[Labyrinthe]{Lignes}}{%
        \foreach \compteurh in {1,...,\useKV[Labyrinthe]{Colonnes}}{%
          \xdef\ColorFill{\ListeLaby[\fpeval{\useKV[Labyrinthe]{Colonnes}*(\compteurv-1)+\compteurh},2]}%
          \node[fill=\ColorFill,draw,minimum height=\LabyHaut*1cm,minimum width=\LabyLong*1cm,name=A-\compteurh-\compteurv] at
          (\fpeval{\LabyLong+\useKV[Labyrinthe]{EcartH}}*\compteurh,-\fpeval{\LabyHaut+\useKV[Labyrinthe]{EcartV}}*\compteurv) {\ListeLaby[\fpeval{\useKV[Labyrinthe]{Colonnes}*(\compteurv-1)+\compteurh},1]};%
        }%
      }%
      % fin des cadres
      % on dessine les fl\`eches
      \ifboolKV[Labyrinthe]{SensImpose}{%
        %verticales
        \foreach \compteurv in {1,...,\fpeval{\useKV[Labyrinthe]{Lignes}-1}}{%
          \foreach \compteurh in {1,...,\useKV[Labyrinthe]{Colonnes}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)},1]}%
              \xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)},2]>0}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)},2]==1}{\xdef\NomStyle{FDirect}}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)},2]==2}{\xdef\NomStyle{FIndirect}}{\xdef\NomStyle{FBidirect}}}%
                \draw[\CouleurF,line width=3pt,\NomStyle] (A-\compteurh-\compteurv) -- node[fill=white,midway,inner sep=2pt]{\MotifTexte\NomNode}(A-\compteurh-\fpeval{\compteurv+1});}{}%
            }{%
              \draw[\CouleurF,line width=3pt,FBidirect] (A-\compteurh-\compteurv) -- (A-\compteurh-\fpeval{\compteurv+1});%
            }%
          }%
        }%
%        % horizontales
        \foreach \compteurv in {1,...,\useKV[Labyrinthe]{Lignes}}{%
          \foreach \compteurh in {1,...,\fpeval{\useKV[Labyrinthe]{Colonnes}-1}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\compteurh},1]}%
              \xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\compteurh},2]>0}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\compteurh},2]==1}{\xdef\NomStyle{FDirect}}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\compteurh},2]==2}{\xdef\NomStyle{FIndirect}}{\xdef\NomStyle{FBidirect}}}%
              \draw[\CouleurF,line width=3pt,\NomStyle](A-\compteurh-\compteurv) -- node[fill=white,midway,\LabySlop,inner sep=2pt]{\MotifTexte\NomNode}(A-\fpeval{\compteurh+1}-\compteurv);}{}
            }{%
              \draw[\CouleurF,line width=3pt,FBidirect](A-\compteurh-\compteurv) -- (A-\fpeval{\compteurh+1}-\compteurv);%
            }%
          }%
        }%
%        % diagonales "inverses"
        \foreach \compteurv in {2,...,\fpeval{\useKV[Labyrinthe]{Lignes}}}{%
          \foreach \compteurh in {1,...,\fpeval{\useKV[Labyrinthe]{Colonnes}-1}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-2)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+2},1]}%
              \xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-2)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+2},2]>0}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-2)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+2},2]==1}{\xdef\NomStyle{FDirect}}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-2)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+2},2]==2}{\xdef\NomStyle{FIndirect}}{\xdef\NomStyle{FBidirect}}}%
                \draw[\CouleurF,line width=3pt,\NomStyle] (A-\compteurh-\compteurv) -- node[fill=white,near start,\LabySlop,inner sep=2pt]{\MotifTexte\NomNode}(A-\fpeval{\compteurh+1}-\fpeval{\compteurv-1});
              }{}
            }{%
              \draw[\CouleurF,line width=3pt,FBidirect] (A-\compteurh-\compteurv) -- (A-\fpeval{\compteurh+1}-\fpeval{\compteurv-1});
            }%
          }%
        }%
%%        % diagonales directes
        \foreach \compteurv in {1,...,\fpeval{\useKV[Labyrinthe]{Lignes}-1}}{%
          \foreach \compteurh in {1,...,\fpeval{\useKV[Labyrinthe]{Colonnes}-1}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+1},1]}%
              \xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+1},2]>0}{%
                \xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+1},2]==1}{\xdef\NomStyle{FDirect}}{\xintifboolexpr{\ListeLabySol[\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+3*(\compteurh-1)+1},2]==2}{\xdef\NomStyle{FIndirect}}{\xdef\NomStyle{FBidirect}}}
                \draw[\CouleurF,line width=3pt,\NomStyle] (A-\compteurh-\compteurv) -- node[fill=white,near start,\LabySlop,inner sep=2pt]{\MotifTexte\NomNode}(A-\fpeval{\compteurh+1}-\fpeval{\compteurv+1});
              }{}%
            }{%
              \draw[\CouleurF,line width=3pt,FBidirect] (A-\compteurh-\compteurv) -- node[fill=white,near start,\LabySlop]{\MotifTexte\NomNode}(A-\fpeval{\compteurh+1}-\fpeval{\compteurv+1});
            }%          
          }%
        }%
      }{%
        \foreach \compteurv in {1,...,\fpeval{\useKV[Labyrinthe]{Lignes}-1}}{%
          \foreach \compteurh in {1,...,\useKV[Labyrinthe]{Colonnes}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[1,\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+2*(\compteurh-1)}]}%
              \draw[\CouleurF,line width=3pt,stealth-stealth] (A-\compteurh-\compteurv) -- node[fill=white,midway]{\MotifTexte\NomNode}(A-\compteurh-\fpeval{\compteurv+1});%
            }{%
              \draw[\CouleurF,line width=3pt,stealth-stealth] (A-\compteurh-\compteurv) -- (A-\compteurh-\fpeval{\compteurv+1});%
            }%
          }%
        }%
        \foreach \compteurv in {1,...,\useKV[Labyrinthe]{Lignes}}{%
          \foreach \compteurh in {1,...,\fpeval{\useKV[Labyrinthe]{Colonnes}-1}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[1,\fpeval{\TotalLaby*(\compteurv-1)+\compteurh}]}%
              \draw[\CouleurF,line width=3pt,stealth-stealth]
              (A-\compteurh-\compteurv) -- node[fill=white,midway]{\MotifTexte\NomNode}(A-\fpeval{\compteurh+1}-\compteurv);
            }{%
              \draw[\CouleurF,line width=3pt,stealth-stealth]
              (A-\compteurh-\compteurv) -- (A-\fpeval{\compteurh+1}-\compteurv);
            }%
          }
        }
        \foreach \compteurv in {2,...,\fpeval{\useKV[Labyrinthe]{Lignes}}}{%
          \foreach \compteurh in {1,...,\fpeval{\useKV[Labyrinthe]{Colonnes}-1}}{%
            \draw[\CouleurF,line width=3pt,stealth-stealth] (A-\compteurh-\compteurv) -- (A-\fpeval{\compteurh+1}-\fpeval{\compteurv-1});
          }
        }
        \foreach \compteurv in {1,...,\fpeval{\useKV[Labyrinthe]{Lignes}-1}}{%
          \foreach \compteurh in {1,...,\fpeval{\useKV[Labyrinthe]{Colonnes}-1}}{%
            \ifboolKV[Labyrinthe]{Passages}{%
              \xdef\NomNode{\noexpand\ListeLabySol[1,\fpeval{\TotalLaby*(\compteurv-1)+\useKV[Labyrinthe]{Colonnes}+2*(\compteurh-1)+1}]}%
              \draw[\CouleurF,line width=3pt,stealth-stealth] (A-\compteurh-\compteurv) -- node[fill=white,midway]{\MotifTexte\NomNode}(A-\fpeval{\compteurh+1}-\fpeval{\compteurv+1});
            }{%
              \draw[\CouleurF,line width=3pt,stealth-stealth] (A-\compteurh-\compteurv) -- (A-\fpeval{\compteurh+1}-\fpeval{\compteurv+1});
            }%          
          }%
        }%
%      % fin des fl\`eches
    }
  \end{tikzpicture}
   }{
  \textbf{! Le nombre d'informations n'est pas compatible avec les
    d\'efinitions de {\ttfamily Colonnes} et {\ttfamily Lignes} !}}%
}

%%%
% Triominos
%%%
\setKVdefault[ClesTriomino]{Longueur=5cm,Etages=3,Ecart=0.6,AffichagePiece=false,Hexagone=false,Recapitulatif=false,Colonnes=2}%
\defKV[ClesTriomino]{Piece=\setKV[ClesTriomino]{AffichagePiece=true}}%

\def\TraceTriomino#1{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesTriomino]{Longueur};
    Rayon:=0.75*u*sqrt(3)/6;
    Etages:=\useKV[ClesTriomino]{Etages};
    pair A,B,C,D,E,F;
    A=(0,0);
    B-A=Etages*u*(1,0);
    C=rotation(B,A,60);
    D=(1/Etages)[C,A];
    E=(1/Etages)[C,B];
    F=C;
    trace polygone(A,B,C);
    for k=1 upto Etages-1:
    trace (k/Etages)[C,A]--(k/Etages)[C,B];
    trace (k/Etages)[A,C]--(k/Etages)[A,B];
    trace (k/Etages)[B,A]--(k/Etages)[B,C];
    endfor;
    pair G[];color H[];%Couleur pour garder l'orientation des textes...
    G[1]=iso(D,E,F);
    H1=blue;
    n=1;
    for k=1 upto Etages-1:
    for l=0 upto (2*k):
    n:=n+1;
    if (l mod 2=0):
    G[n]=G[1] shifted(k*(D-F)+(l div 2)*(E-D));
    H[n]=blue;
    else:
    G[n]=symetrie(G[1],D,E) shifted((k-1)*(D-F)+(l div 2)*(E-D));
    H[n]=green;
    fi;
    endfor;
    endfor;
    % affichage des textes
    nba=0;
    for p_=#1:
    if (nba mod 3)=1:
    if H[(nba div 3)+1]=blue:
    label(TEX(p_) rotated 120,pointarc(cercles(G[(nba div 3)+1],Rayon),30));
    else:
    label(TEX(p_) rotated 180,pointarc(cercles(G[(nba div 3)+1],Rayon),90));
    fi;
    elseif (nba mod 3)=2:
    if H[(nba div 3)+1]=blue:
    label(TEX(p_),pointarc(cercles(G[(nba div 3)+1],Rayon),270));
    else:
    label(TEX(p_) rotated 60,pointarc(cercles(G[(nba div 3)+1],Rayon),330));
    fi;
    else:
    if H[(nba div 3)+1]=blue:
    label(TEX(p_) rotated 240,pointarc(cercles(G[(nba div 3)+1],Rayon),150));
    else:
    label(TEX(p_) rotated 300,pointarc(cercles(G[(nba div 3)+1],Rayon),210));
    fi;
    fi;
    nba:=nba+1;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesTriomino]{Longueur}; Etages:=\useKV[ClesTriomino]{Etages};}]
    Rayon:=0.75*u*sqrt(3)/6;
    pair A,B,C,D,E,F;
    A=(0,0);
    B-A=Etages*u*(1,0);
    C=rotation(B,A,60);
    D=(1/Etages)[C,A];
    E=(1/Etages)[C,B];
    F=C;
    trace polygone(A,B,C);
    for k=1 upto Etages-1:
    trace (k/Etages)[C,A]--(k/Etages)[C,B];
    trace (k/Etages)[A,C]--(k/Etages)[A,B];
    trace (k/Etages)[B,A]--(k/Etages)[B,C];
    endfor;
    pair G[];color H[];%Couleur pour garder l'orientation des textes...
    G[1]=iso(D,E,F);
    H1=blue;
    n=1;
    for k=1 upto Etages-1:
    for l=0 upto (2*k):
    n:=n+1;
    if (l mod 2=0):
    G[n]=G[1] shifted(k*(D-F)+(l div 2)*(E-D));
    H[n]=blue;
    else:
    G[n]=symetrie(G[1],D,E) shifted((k-1)*(D-F)+(l div 2)*(E-D));
    H[n]=green;
    fi;
    endfor;
    endfor;
    % affichage des textes
    nba=0;
    for p_=#1:
    if (nba mod 3)=1:
    if H[(nba div 3)+1]=blue:
    label(LATEX(p_) rotated 120,pointarc(cercles(G[(nba div 3)+1],Rayon),30));
    else:
    label(LATEX(p_) rotated 180,pointarc(cercles(G[(nba div 3)+1],Rayon),90));
    fi;
    elseif (nba mod 3)=2:
    if H[(nba div 3)+1]=blue:
    label(LATEX(p_),pointarc(cercles(G[(nba div 3)+1],Rayon),270));
    else:
    label(LATEX(p_) rotated 60,pointarc(cercles(G[(nba div 3)+1],Rayon),330));
    fi;
    else:
    if H[(nba div 3)+1]=blue:
    label(LATEX(p_) rotated 240,pointarc(cercles(G[(nba div 3)+1],Rayon),150));
    else:
    label(LATEX(p_) rotated 300,pointarc(cercles(G[(nba div 3)+1],Rayon),210));
    fi;
    fi;
    nba:=nba+1;
    endfor;    
  \end{mpost}
  \fi
}

\def\TraceTriominoHexa#1{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesTriomino]{Longueur};
    RayonCercle:=u;
    Rayon:=\useKV[ClesTriomino]{Ecart}*0.5*u*sqrt(3)/6;
    pair O,A,B,C,D,E,F,G,H[],I[];
    O=(0,0);
    path cc;
    cc=cercles(O,RayonCercle);
    A=pointarc(cc,0);
    B=rotation(A,O,60);
    C=rotation(B,O,60);
    D=rotation(C,O,60);
    E=rotation(D,O,60);
    F=rotation(E,O,60);
    G=rotation(F,O,60);
    H1=iso(A,B);
    H2=iso(B,C);
    H3=iso(C,D);
    H4=iso(D,E);
    H5=iso(E,F);
    H6=iso(F,A);
    I1=iso(C,1/2[C,D],rotation(1/2[C,D],C,60));
    I2=symetrie(I1,C,F);
    I3=symetrie(I2,1/2[B,C],1/2[D,E]);
    I4=symetrie(I3,1/2[B,C],1/2[F,A]);
    I5=symetrie(I4,B,E);
    I6-I1=0.5*(D-C);
    I7-I2=0.5*(D-C);
    I8-I3=0.5*(D-C);
    I9-I4=0.5*(D-C);
    I10-I5=0.5*(D-C);
    I11=symetrie(I10,1/2[C,B],1/2[F,A]);
    I12=symetrie(I11,1/2[A,B],1/2[E,F]);
    I13=symetrie(I6,A,D);
    I14=symetrie(I7,A,D);
    I15=symetrie(I8,A,D);
    I16=symetrie(I9,A,D);
    I17=symetrie(I10,A,D);
    I18=symetrie(I11,A,D);
    I19=symetrie(I12,A,D);
    I20=symetrie(I1,A,D);
    I21=symetrie(I2,A,D);
    I22=symetrie(I3,A,D);
    I23=symetrie(I4,A,D);
    I24=symetrie(I5,A,D);
    trace polygone(A,B,C,D,E,F);
    trace polygone(H1,H3,H5);
    trace polygone(H2,H4,H6);
    trace segment(A,D);
    trace segment(B,E);
    trace segment(C,F);
    color N[];%Couleur pour garder l'orientation des textes...
    N1=blue;
    for l=2 upto 5:
    if (l mod 2=0):
    N[l]=green;
    else:
    N[l]=blue;
    fi;
    endfor;
    for l=6 upto 12:
    if (l mod 2=0):
    N[l]=blue;
    else:
    N[l]=green;
    fi;
    endfor;
    for l=13 upto 19:
    if (l mod 2=0):
    N[l]=blue;
    else:
    N[l]=green;
    fi;
    endfor;
    for l=20 upto 24:
    if (l mod 2=0):
    N[l]=green;
    else:
    N[l]=blue;
    fi;
    endfor;
    % affichage des textes
    nba=0;
    for p_=#1:
    if (nba mod 3)=1:
    if N[(nba div 3)+1]=blue:
    label(TEX(p_) rotated 120,pointarc(cercles(I[(nba div 3)+1],Rayon),30));
    else:
    label(TEX(p_) rotated 180,pointarc(cercles(I[(nba div 3)+1],Rayon),90));
    fi;
    elseif (nba mod 3)=2:
    if N[(nba div 3)+1]=blue:
    label(TEX(p_),pointarc(cercles(I[(nba div 3)+1],Rayon),270));
    else:
    label(TEX(p_) rotated 60,pointarc(cercles(I[(nba div 3)+1],Rayon),330));
    fi;
    else:
    if N[(nba div 3)+1]=blue:
    label(TEX(p_) rotated 240,pointarc(cercles(I[(nba div 3)+1],Rayon),150));
    else:
    label(TEX(p_) rotated 300,pointarc(cercles(I[(nba div 3)+1],Rayon),210));
    fi;
    fi;
    nba:=nba+1;
    endfor;
  \end{mplibcode}
  \else
    \begin{mpost}[mpsettings={u:=\useKV[ClesTriomino]{Longueur};RayonCercle:=u; Rayon:=\useKV[ClesTriomino]{Ecart}*0.5*u*sqrt(3)/6;}]
    pair O,A,B,C,D,E,F,G,H[],I[];
    O=(0,0);
    path cc;
    cc=cercles(O,RayonCercle);
    A=pointarc(cc,0);
    B=rotation(A,O,60);
    C=rotation(B,O,60);
    D=rotation(C,O,60);
    E=rotation(D,O,60);
    F=rotation(E,O,60);
    G=rotation(F,O,60);
    H1=iso(A,B);
    H2=iso(B,C);
    H3=iso(C,D);
    H4=iso(D,E);
    H5=iso(E,F);
    H6=iso(F,A);
    I1=iso(C,1/2[C,D],rotation(1/2[C,D],C,60));
    I2=symetrie(I1,C,F);
    I3=symetrie(I2,1/2[B,C],1/2[D,E]);
    I4=symetrie(I3,1/2[B,C],1/2[F,A]);
    I5=symetrie(I4,B,E);
    I6-I1=0.5*(D-C);
    I7-I2=0.5*(D-C);
    I8-I3=0.5*(D-C);
    I9-I4=0.5*(D-C);
    I10-I5=0.5*(D-C);
    I11=symetrie(I10,1/2[C,B],1/2[F,A]);
    I12=symetrie(I11,1/2[A,B],1/2[E,F]);
    I13=symetrie(I6,A,D);
    I14=symetrie(I7,A,D);
    I15=symetrie(I8,A,D);
    I16=symetrie(I9,A,D);
    I17=symetrie(I10,A,D);
    I18=symetrie(I11,A,D);
    I19=symetrie(I12,A,D);
    I20=symetrie(I1,A,D);
    I21=symetrie(I2,A,D);
    I22=symetrie(I3,A,D);
    I23=symetrie(I4,A,D);
    I24=symetrie(I5,A,D);
    trace polygone(A,B,C,D,E,F);
    trace polygone(H1,H3,H5);
    trace polygone(H2,H4,H6);
    trace segment(A,D);
    trace segment(B,E);
    trace segment(C,F);
    color N[];%Couleur pour garder l'orientation des textes...
    N1=blue;
    for l=2 upto 5:
    if (l mod 2=0):
    N[l]=green;
    else:
    N[l]=blue;
    fi;
    endfor;
    for l=6 upto 12:
    if (l mod 2=0):
    N[l]=blue;
    else:
    N[l]=green;
    fi;
    endfor;
    for l=13 upto 19:
    if (l mod 2=0):
    N[l]=blue;
    else:
    N[l]=green;
    fi;
    endfor;
    for l=20 upto 24:
    if (l mod 2=0):
    N[l]=green;
    else:
    N[l]=blue;
    fi;
    endfor;
    % affichage des textes
    nba=0;
    for p_=#1:
    if (nba mod 3)=1:
    if N[(nba div 3)+1]=blue:
    label(LATEX(p_) rotated 120,pointarc(cercles(I[(nba div 3)+1],Rayon),30));
    else:
    label(LATEX(p_) rotated 180,pointarc(cercles(I[(nba div 3)+1],Rayon),90));
    fi;
    elseif (nba mod 3)=2:
    if N[(nba div 3)+1]=blue:
    label(LATEX(p_),pointarc(cercles(I[(nba div 3)+1],Rayon),270));
    else:
    label(LATEX(p_) rotated 60,pointarc(cercles(I[(nba div 3)+1],Rayon),330));
    fi;
    else:
    if N[(nba div 3)+1]=blue:
    label(LATEX(p_) rotated 240,pointarc(cercles(I[(nba div 3)+1],Rayon),150));
    else:
    label(LATEX(p_) rotated 300,pointarc(cercles(I[(nba div 3)+1],Rayon),210));
    fi;
    fi;
    nba:=nba+1;
    endfor;
  \end{mpost}
  \fi
}

\newtoks\toklisteTriomino%
\def\UpdatetoksTriomino#1\nil{\addtotok\toklisteTriomino{"#1",}}%
  
\newcommand\Triomino[2][]{%
  \useKVdefault[ClesTriomino]%
  \setKV[ClesTriomino]{#1}%
  \setsepchar{§}%\ignoreemptyitems%
  \readlist*\ListeTriominos{#2}%
  \toklisteTriomino{}%
  \ifboolKV[ClesTriomino]{Recapitulatif}{%
    %\begin{longtable}{|>{\centering}p{0.45\linewidth}|p{0.45\linewidth}|}
    %  \hline
    %  \xintFor* ##1 in {\xintSeq{1}{\ListeTriominoslen}}\do{
    %    &\\
    %    &\\
    %    \ListeTriominos[##1]&\\
    %    &\\
    %    &\\
    %    \hline
    %  }%
    %\end{longtable}
  }{%
    \ifboolKV[ClesTriomino]{AffichagePiece}{%
      \setKV[ClesTriomino]{Etages=1}%
      \TraceTriomino{"\ListeTriominos[\fpeval{3*\useKV[ClesTriomino]{Piece}-2}]","\ListeTriominos[\fpeval{3*\useKV[ClesTriomino]{Piece}-1}]","\ListeTriominos[\fpeval{3*\useKV[ClesTriomino]{Piece}}]"}%
    }{%
      \foreachitem\compteur\in\ListeTriominos{\expandafter\UpdatetoksTriomino\compteur\nil}%
      \ifboolKV[ClesTriomino]{Hexagone}{%
        \TraceTriominoHexa{\the\toklisteTriomino}%
      }{%
        \TraceTriomino{\the\toklisteTriomino}%
      }%
    }%
  }%
}%

%%%
% Labyrinthe Nombre
%%%
\setKVdefault[ClesLabyNb]{Multiple=5,XDepart=0,YDepart=0,Longueur=7,Largeur=4,XArrivee=6,YArrivee=3,Solution=false,Echelle=1,Angle=0,Couleur=red,Murs=false,Nom=Ex1,CouleurChemin=LightSteelBlue,DoubleOperation=false,Chemin=false,EntreeSortie=false,Entree="Nord",Sortie="Sud",SortieUnique=true}

\newcommand\LabyNombre[1][]{%
  \useKVdefault[ClesLabyNb]%
  \setKV[ClesLabyNb]{#1}%
  \ifboolKV[ClesLabyNb]{Solution}{%
    \TraceLabyFactoSolution{\useKV[ClesLabyNb]{Multiple}}{\useKV[ClesLabyNb]{Longueur}}{\useKV[ClesLabyNb]{Largeur}}{(\useKV[ClesLabyNb]{YDepart},\useKV[ClesLabyNb]{XDepart})}{(\useKV[ClesLabyNb]{YArrivee},\useKV[ClesLabyNb]{XArrivee})}{\useKV[ClesLabyNb]{Solution}}%
  }{%
    \TraceLabyFacto{\useKV[ClesLabyNb]{Multiple}}{\useKV[ClesLabyNb]{Longueur}}{\useKV[ClesLabyNb]{Largeur}}{(\useKV[ClesLabyNb]{YDepart},\useKV[ClesLabyNb]{XDepart})}{(\useKV[ClesLabyNb]{YArrivee},\useKV[ClesLabyNb]{XArrivee})}{\useKV[ClesLabyNb]{Solution}}%
  }%    
}%

\newcommand\TraceLabyFacto[6]{%
  \mplibforcehmode%
  \xdef\PfCNomLabyrinthe{\useKV[ClesLabyNb]{Nom}}%
  \begin{mplibcode}[\PfCNomLabyrinthe]
    input PfCLabyNombre;

    boolean Murs;
    Murs=\useKV[ClesLabyNb]{Murs};

    string Entree,Sortie;
    Entree=\useKV[ClesLabyNb]{Entree};
    Sortie=\useKV[ClesLabyNb]{Sortie};
    boolean SortieUnique,EntreeSortie;
    SortieUnique:=\useKV[ClesLabyNb]{SortieUnique};
    EntreeSortie:=\useKV[ClesLabyNb]{EntreeSortie};
    picture Square;
    Square=image(
    path Test;
    Test=unitsquare scaled 10mm;
    trace subpath(0.85,1.15) of Test;
    trace subpath(1.85,2.15) of Test;
    trace subpath(2.85,3.15) of Test;
    trace subpath(3.85,4.15) of Test;
    );

    vardef RemplissagePremier=
    Totalpremier:=if indiceChemin<62:62 else: indiceChemin fi;

    numeric p[]; boolean n_is_prime; p[1]=2; kis:=1;
    for nis=3 step 2 until infinity:
    n_is_prime := true;
    for jis=2 upto kis:
    if nis mod p[jis]=0: n_is_prime := false; fi
    exitif nis/p[jis] < p[jis];
    endfor
    if n_is_prime: p[incr kis] := nis; exitif kis=Totalpremier; fi
    endfor fi
    
    numeric PR[],pretiens[];
    
    for ki=1 upto Totalpremier-1:
    pretiens[ki]:=p[ki+1];
    endfor;
    
    Kk:=0;
    
    for ki=Totalpremier-1 downto 1:
    alea:=1+floor(uniformdeviate(ki));
    PR[incr Kk]:=pretiens[alea];
    % message("k="&decimal(k)&" alea="&decimal(alea)&" Kk="&decimal(Kk)&" PR[Kk]="&decimal(PR[Kk]));
    Kkl:=0;
    for li=1 upto ki:
    if li<>alea:
      pretiens[incr Kkl]:=pretiens[li];
      % message("Kkl="&decimal(Kkl));
      fi;
    endfor;
    endfor;
    enddef;
    
    numeric Multiple;
    Multiple=#1;
    % Initialisation du labyrinthe
    InitialisationLabyrinthe(#2,#3);
    % On initialise les paramètres du parcours
    numeric choixligneD,choixligneA,choixcolonneD,choixcolonneA;
    choixligneD=xpart(#4);
    choixcolonneD=ypart(#4);
    choixligneA=xpart(#5);
    choixcolonneA=ypart(#5);%
    pair Depart;
    Depart=N[choixligneD][choixcolonneD];
    pair Arrivee;
    Arrivee=N[choixligneA][choixcolonneA];
    pair Mobile;
    Mobile=Depart;
    %
    RAZPileChemin;

    if \useKV[ClesLabyNb]{SortieUnique}:
    if (Sortie="Est") or (Sortie="Ouest"):
    for k=0 upto LargeurLaby-1:
    if k<>choixligneA:
    CaseExploree[k][choixcolonneA]:=true;
    fi;
    endfor;
    elseif (Sortie="Nord") or (Sortie="Sud"):
    for k=0 upto LongueurLaby-1:
    if k<>choixcolonneA:
    CaseExploree[choixligneA][k]:=true;
    fi;
    endfor;
    fi;
    fi;
    % Exploration du labyrinthe
    if Entree="Nord":
    CaseExploree[choixligneD-1][choixcolonneD]:=true;
    elseif Entree="Sud":
    CaseExploree[choixligneD+1][choixcolonneD]:=true;
    elseif Entree="Est":
    CaseExploree[choixligneD][choixcolonneD+1]:=true;
    elseif Entree="Ouest":
    CaseExploree[choixligneD][choixcolonneD-1]:=true;
    fi;
    %
    PushChemin((choixligneD,choixcolonneD));
    CaseExploree[choixligneD][choixcolonneD]:=true;
    VoisinDispo(choixligneD,choixcolonneD);
    forever: exitif Mobile=Arrivee;%nb=0;
    nb:=ceiling(uniformdeviate(nbvoisin));
    if nb>0:
      for k=1 upto nbvoisin:
        CaseExploree[xpart(PileVoisin[k])][ypart(PileVoisin[k])]:=true;
      endfor;
      PushChemin((xpart(PileVoisin[nb]),ypart(PileVoisin[nb])));
      Mobile:=N[xpart(PileChemin[indiceChemin])][ypart(PileChemin[indiceChemin])];
      VoisinDispo(xpart(PileChemin[indiceChemin]),ypart(PileChemin[indiceChemin]));
    else:
      PopCheminMathAlea;
    fi;
    endfor;
    % Affichagefinal
    % on sauvegarde les nombres aléatoires
    numeric NbAffiche[];
    numeric NbSol[];
    % on écrit des nombres au hasard, mais sans être multiple du nombre choisi
    numeric nbaffiche;
    nbaffiche=0;
    for k=0 upto LargeurLaby-1:
      for l=0 upto LongueurLaby-1:
      nbaffiche:=nbaffiche+1;
      if Multiple=1:%On affichera que des multiples de 2/3/5/9/10 pour afficher un chemin de nombre premiers
      mathalea:=uniformdeviate(5);
      if mathalea<1:
      NbAffiche[nbaffiche]:=(10+ceiling(uniformdeviate(100)))*2;
      elseif mathalea<2:
      NbAffiche[nbaffiche]:=(10+ceiling(uniformdeviate(100)))*3;
      elseif mathalea<3:
      NbAffiche[nbaffiche]:=(10+ceiling(uniformdeviate(100)))*5;
      elseif mathalea<4:
      NbAffiche[nbaffiche]:=(10+ceiling(uniformdeviate(100)))*9;
      else:  NbAffiche[nbaffiche]:=(10+ceiling(uniformdeviate(100)))*10;
      fi;
      else:
      NbAffiche[nbaffiche]:=(50+ceiling(uniformdeviate(100)))*Multiple+ceiling(uniformdeviate(Multiple-1));
      fi;
      endfor;
    endfor;
    % On crée des multiples du nombre choisi
    RemplissagePremier;
    
    for k=1 upto indiceChemin:
    if Multiple>1:
    NbSol[k]=(50+ceiling(uniformdeviate(100)))*Multiple;
    else:
    NbSol[k]=PR[k];
    fi;
    endfor;
    % On affiche
    picture Corps;
    Corps=image(
      nbaffiche:=0;
      for k=0 upto LargeurLaby-1:
        for l=0 upto LongueurLaby-1:
	  nbaffiche:=nbaffiche+1;
          label(TEX("\num{"&decimal(NbAffiche[nbaffiche])&"}"),M[k][l]);
        endfor;
      endfor;
      for k=1 upto indiceChemin:
      remplis ((unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])]) withcolor white;
      label(TEX("\num{"&decimal(NbSol[k])&"}"),M[xpart(PileChemin[k])][ypart(PileChemin[k])]);
      endfor;
      if EntreeSortie=false:
      remplis ((unitsquare scaled 10mm) shifted N[choixligneD][choixcolonneD]) withcolor \useKV[ClesLabyNb]{Couleur};
      remplis ((unitsquare scaled 10mm) shifted Arrivee) withcolor \useKV[ClesLabyNb]{Couleur};
      trace TraceLabyrinthe;
      else:
      for k=0 upto LargeurLaby-1:
      for l=0 upto LongueurLaby-1:
      trace Square shifted N[k][l];
      endfor;
      endfor;
      trace u*(0,0)--u*(LongueurLaby,0)--u*(LongueurLaby,-LargeurLaby)--u*(0,-LargeurLaby)--cycle;
      % On dessine l'entrée.
      if Entree="Nord":
      N[-1][-1]:=Depart+(0,10mm);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(1,4) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(0.18,0.82) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      elseif Entree="Ouest":
      N[-1][-1]:=Depart+(-10mm,0);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(2,5) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(1.15,1.85) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      elseif Entree="Sud":
      N[-1][-1]:=Depart+(0,-10mm);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(3,6) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(2.15,2.85) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      elseif Entree="Est":
      N[-1][-1]:=Depart+(10mm,0);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(0,3) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(3.18,3.82) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      fi;
      % On dessine les sorties
      if Sortie="Nord":
      N[-2][-2]=Arrivee+(5mm,20mm);
      for k=0 upto LongueurLaby-1:
      draw ((point(0.15) of unitsquare scaled 10mm)--0.5[(point(0.15) of unitsquare scaled 10mm),(point(2.85) of unitsquare scaled 10mm)]) shifted (N[0][k]+(0,10mm));
      draw ((point(0.85) of unitsquare scaled 10mm)--0.5[(point(0.85) of unitsquare scaled 10mm),(point(2.15) of unitsquare scaled 10mm)]) shifted (N[0][k]+(0,10mm));
      undraw (subpath(0.18,0.82) of unitsquare scaled 10mm) shifted (N[0][k]+(0,10mm)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[0][k]+(0,10mm)));
      endfor;
      elseif Sortie="Ouest":
      N[-2][-2]=Arrivee+(-10mm,5mm);
      for k=0 upto LargeurLaby-1:
      draw ((point(1.15) of unitsquare scaled 10mm)--0.5[(point(1.15) of unitsquare scaled 10mm),(point(3.85) of unitsquare scaled 10mm)]) shifted (N[k][0]+(-10mm,0));
      draw ((point(1.85) of unitsquare scaled 10mm)--0.5[(point(1.85) of unitsquare scaled 10mm),(point(3.15) of unitsquare scaled 10mm)]) shifted (N[k][0]+(-10mm,0));
      undraw (subpath(1.18,1.82) of unitsquare scaled 10mm) shifted (N[k][0]+(-10mm,0)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[k][0]+(-10mm,0)));
      endfor;
      elseif Sortie="Sud":
      N[-2][-2]=Arrivee+(5mm,-10mm);
      for k=0 upto LongueurLaby-1:
      draw ((point(2.85) of unitsquare scaled 10mm)--0.5[(point(0.15) of unitsquare scaled 10mm),(point(2.85) of unitsquare scaled 10mm)]) shifted (N[LargeurLaby-1][k]+(0,-10mm));
      draw ((point(2.15) of unitsquare scaled 10mm)--0.5[(point(0.85) of unitsquare scaled 10mm),(point(2.15) of unitsquare scaled 10mm)]) shifted (N[LargeurLaby-1][k]+(0,-10mm));
      undraw (subpath(2.18,2.82) of unitsquare scaled 10mm) shifted (N[LargeurLaby-1][k]+(0,-10mm)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[LargeurLaby-1][k]+(0,-10mm)));
      endfor;
      elseif Sortie="Est":
      N[-2][-2]=Arrivee+(20mm,5mm);
      for k=0 upto LargeurLaby-1:
      draw ((point(3.15) of unitsquare scaled 10mm)--0.5[(point(3.15) of unitsquare scaled 10mm),(point(1.85) of unitsquare scaled 10mm)]) shifted (N[k][LongueurLaby-1]+(10mm,0));
      draw ((point(3.85) of unitsquare scaled 10mm)--0.5[(point(3.85) of unitsquare scaled 10mm),(point(1.15) of unitsquare scaled 10mm)]) shifted (N[k][LongueurLaby-1]+(10mm,0));
      undraw (subpath(3.18,3.8) of unitsquare scaled 10mm) shifted (N[k][LongueurLaby-1]+(10mm,0)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[k][LongueurLaby-1]+(10mm,0)));
      endfor;
      fi;
      fi;
      );
    Corps:=(Corps scaled \useKV[ClesLabyNb]{Echelle}) rotated \useKV[ClesLabyNb]{Angle};
    trace Corps;
  \end{mplibcode}
}

\newcommand\TraceLabyFactoSolution[6]{%
  \mplibforcehmode%
  \xdef\PfCNomLabyrinthe{\useKV[ClesLabyNb]{Nom}}%
  \begin{mplibcode}[\PfCNomLabyrinthe]
    color CouleurChemin;
    CouleurChemin:=\useKV[ClesLabyNb]{CouleurChemin};
    picture CorpsSolution;
    CorpsSolution=image(
    nbaffiche:=0;
      for k=0 upto LargeurLaby-1:
        for l=0 upto LongueurLaby-1:
          nbaffiche:=nbaffiche+1;
          label(TEX("\num{"&decimal(NbAffiche[nbaffiche])&"}"),M[k][l]);
        endfor;
      endfor;
      if EntreeSortie=false:
            remplis ((unitsquare scaled 10mm) shifted N[choixligneD][choixcolonneD]) withcolor \useKV[ClesLabyNb]{Couleur};
      remplis ((unitsquare scaled 10mm) shifted Arrivee) withcolor \useKV[ClesLabyNb]{Couleur};
      for k=2 upto indiceChemin-1:
        remplis ((unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])]) withcolor \useKV[ClesLabyNb]{CouleurChemin};
        label(TEX("\num{"&decimal(NbSol[k])&"}"),M[xpart(PileChemin[k])][ypart(PileChemin[k])]);
        endfor;
        else:
      for k=1 upto indiceChemin:
      remplis ((unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])]) withcolor white;
      label(TEX("\num{"&decimal(NbSol[k])&"}"),M[xpart(PileChemin[k])][ypart(PileChemin[k])]);
      endfor;
      fi;
      if EntreeSortie=false:
      trace TraceLabyrinthe;
      else:
      for k=0 upto LargeurLaby-1:
      for l=0 upto LongueurLaby-1:
      trace Square shifted N[k][l];
      endfor;
      endfor;
      trace u*(0,0)--u*(LongueurLaby,0)--u*(LongueurLaby,-LargeurLaby)--u*(0,-LargeurLaby)--cycle;
      % On dessine l'entrée.
      if Entree="Nord":
      N[-1][-1]:=Depart+(0,10mm);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(1,4) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(0.18,0.82) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      elseif Entree="Ouest":
      N[-1][-1]:=Depart+(-10mm,0);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(2,5) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(1.15,1.85) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      elseif Entree="Sud":
      N[-1][-1]:=Depart+(0,-10mm);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(3,6) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(2.15,2.85) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      elseif Entree="Est":
      N[-1][-1]:=Depart+(10mm,0);
      fill ((unitsquare scaled 10mm) shifted N[-1][-1]) withcolor white;
      draw (subpath(0,3) of unitsquare scaled 10mm) shifted N[-1][-1];
      undraw (subpath(3.18,3.82) of unitsquare scaled 10mm) shifted N[-1][-1] withpen pencircle scaled 1.25;
      label(btex \footnotesize Départ etex,(center Square) shifted N[-1][-1]);
      fi;
      % On dessine les sorties
      if Sortie="Nord":
      N[-2][-2]=Arrivee+(5mm,20mm);
      for k=0 upto LongueurLaby-1:
      draw ((point(0.15) of unitsquare scaled 10mm)--0.5[(point(0.15) of unitsquare scaled 10mm),(point(2.85) of unitsquare scaled 10mm)]) shifted (N[0][k]+(0,10mm));
      draw ((point(0.85) of unitsquare scaled 10mm)--0.5[(point(0.85) of unitsquare scaled 10mm),(point(2.15) of unitsquare scaled 10mm)]) shifted (N[0][k]+(0,10mm));
      undraw (subpath(0.18,0.82) of unitsquare scaled 10mm) shifted (N[0][k]+(0,10mm)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[0][k]+(0,10mm)));
      endfor;
      elseif Sortie="Ouest":
      N[-2][-2]=Arrivee+(-10mm,5mm);
      for k=0 upto LargeurLaby-1:
      draw ((point(1.15) of unitsquare scaled 10mm)--0.5[(point(1.15) of unitsquare scaled 10mm),(point(3.85) of unitsquare scaled 10mm)]) shifted (N[k][0]+(-10mm,0));
      draw ((point(1.85) of unitsquare scaled 10mm)--0.5[(point(1.85) of unitsquare scaled 10mm),(point(3.15) of unitsquare scaled 10mm)]) shifted (N[k][0]+(-10mm,0));
      undraw (subpath(1.18,1.82) of unitsquare scaled 10mm) shifted (N[k][0]+(-10mm,0)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[k][0]+(-10mm,0)));
      endfor;
      elseif Sortie="Sud":
      N[-2][-2]=Arrivee+(5mm,-10mm);
      for k=0 upto LongueurLaby-1:
      % draw (Square) shifted (N[LargeurLaby-1][k]+(0,-10mm)) withcolor red;
      draw ((point(2.85) of unitsquare scaled 10mm)--0.5[(point(0.15) of unitsquare scaled 10mm),(point(2.85) of unitsquare scaled 10mm)]) shifted (N[LargeurLaby-1][k]+(0,-10mm));
      draw ((point(2.15) of unitsquare scaled 10mm)--0.5[(point(0.85) of unitsquare scaled 10mm),(point(2.15) of unitsquare scaled 10mm)]) shifted (N[LargeurLaby-1][k]+(0,-10mm));
      undraw (subpath(2.18,2.82) of unitsquare scaled 10mm) shifted (N[LargeurLaby-1][k]+(0,-10mm)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[LargeurLaby-1][k]+(0,-10mm)));
      endfor;
      elseif Sortie="Est":
      N[-2][-2]=Arrivee+(20mm,5mm);
      for k=0 upto LargeurLaby-1:
      draw ((point(3.15) of unitsquare scaled 10mm)--0.5[(point(3.15) of unitsquare scaled 10mm),(point(1.85) of unitsquare scaled 10mm)]) shifted (N[k][LongueurLaby-1]+(10mm,0));
      draw ((point(3.85) of unitsquare scaled 10mm)--0.5[(point(3.85) of unitsquare scaled 10mm),(point(1.15) of unitsquare scaled 10mm)]) shifted (N[k][LongueurLaby-1]+(10mm,0));
      undraw (subpath(3.18,3.8) of unitsquare scaled 10mm) shifted (N[k][LongueurLaby-1]+(10mm,0)) withpen pencircle scaled 1.25;
      label(TEX("\footnotesize S"&decimal(k)),center (Square) shifted (N[k][LongueurLaby-1]+(10mm,0)));
      endfor;
      fi;
      path CheminSolution;
      CheminSolution=(N[-1][-1] shifted (5mm,5mm))--((center unitsquare scaled 10mm) shifted N[choixligneD][choixcolonneD])
      for k=2 upto indiceChemin-1:
      -- ((center unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])])
      endfor
      --((center unitsquare scaled 10mm) shifted Arrivee)--N[-2][-2];
      trace CheminSolution dashed evenly withcolor CouleurChemin;
      fi;
      );
      CorpsSolution:=(CorpsSolution scaled \useKV[ClesLabyNb]{Echelle}) rotated \useKV[ClesLabyNb]{Angle};
      trace CorpsSolution;
  \end{mplibcode}
}

\newcommand\TraceLabyNombreDouble[6]{%
  \mplibforcehmode%
  \xdef\PfCNomLabyrinthe{\useKV[ClesLabyNb]{Nom}}%
  \begin{mplibcode}[\PfCNomLabyrinthe]
    input PfCLabyNombre;

    boolean Murs;
    Murs=\useKV[ClesLabyNb]{Murs};
    
    numeric Multiple;
    Multiple=#1;
    % Initialisation du labyrinthe
    InitialisationLabyrinthe(#2,#3);
    % On initialise les paramètres du parcours
    numeric choixligneD,choixligneA,choixcolonneD,choixcolonneA;
    choixligneD=xpart(#4);
    choixcolonneD=ypart(#4);
    choixligneA=xpart(#5);
    choixcolonneA=ypart(#5);%
    pair Depart;
    Depart=N[choixligneD][choixcolonneD];
    pair Arrivee;
    Arrivee=N[choixligneA][choixcolonneA];
    pair Mobile;
    Mobile=Depart;
    RAZPileChemin;
    % Exploration du labyrinthe
    PushChemin((choixligneD,choixcolonneD));
    CaseExploree[choixligneD][choixcolonneD]:=true;
    VoisinDispo(choixligneD,choixcolonneD);
    forever: exitif Mobile=Arrivee;%nb=0;
    nb:=ceiling(uniformdeviate(nbvoisin));
    if nb>0:
      for k=1 upto nbvoisin:
        CaseExploree[xpart(PileVoisin[k])][ypart(PileVoisin[k])]:=true;
      endfor;
      PushChemin((xpart(PileVoisin[nb]),ypart(PileVoisin[nb])));
      Mobile:=N[xpart(PileChemin[indiceChemin])][ypart(PileChemin[indiceChemin])];
      VoisinDispo(xpart(PileChemin[indiceChemin]),ypart(PileChemin[indiceChemin]));
    else:
      PopChemin;
    fi;
    endfor;
    % Affichagefinal
    % on sauvegarde les nombres aléatoires
    numeric NbAffiche[];
    numeric NbSol[];
    % on écrit des nombres au hasard, mais sans être multiple du nombre choisi
    numeric nbaffiche;
    nbaffiche=0;
    NbAffiche[0]=5+ceiling(uniformdeviate(7));
    for k=0 upto LargeurLaby-1:
      for l=0 upto LongueurLaby-1:
      nbaffiche:=nbaffiche+1;
      mathalea:=uniformdeviate(1);
      if mathalea<0.95:
      NbAffiche[nbaffiche]=NbAffiche[nbaffiche-1]+Multiple+1;
      else:
      NbAffiche[nbaffiche]=NbAffiche[nbaffiche-1]*(Multiple-1);
      fi;
      endfor;
    endfor;
    % On crée des multiples du nombre choisi
    NbSol[1]=5+ceiling(uniformdeviate(7));
    for k=2 upto indiceChemin-1:
    mathalea:=uniformdeviate(1);
    if mathalea<0.9:
    NbSol[k]=NbSol[k-1]+Multiple;
    else:
    NbSol[k]=NbSol[k-1]*Multiple;
    fi;
    endfor;
    % On affiche
    picture Corps;
    Corps=image(
      nbaffiche:=0;
      for k=0 upto LargeurLaby-1:
        for l=0 upto LongueurLaby-1:
	  nbaffiche:=nbaffiche+1;
          label(TEX("\num{"&decimal(NbAffiche[nbaffiche])&"}"),M[k][l]);
        endfor;
      endfor;
      remplis ((unitsquare scaled 10mm) shifted N[choixligneD][choixcolonneD]) withcolor \useKV[ClesLabyNb]{Couleur};
      remplis ((unitsquare scaled 10mm) shifted Arrivee) withcolor \useKV[ClesLabyNb]{Couleur};
      for k=2 upto indiceChemin-1:
        remplis ((unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])]) withcolor white;
        label(TEX("\num{"&decimal(NbSol[k])&"}"),M[xpart(PileChemin[k])][ypart(PileChemin[k])]);
      endfor;
      trace TraceLabyrinthe;
    );
    Corps:=(Corps scaled \useKV[ClesLabyNb]{Echelle}) rotated \useKV[ClesLabyNb]{Angle};
    trace Corps;
  \end{mplibcode}
}

\newcommand\TraceDoubleSolution[6]{%
  \mplibforcehmode%
  \xdef\PfCNomLabyrinthe{\useKV[ClesLabyNb]{Nom}}%
  \begin{mplibcode}[\PfCNomLabyrinthe]
    picture CorpsSolution;
    CorpsSolution=image(
      nbaffiche:=0;
      for k=0 upto #3-1:
        for l=0 upto #2-1:
          nbaffiche:=nbaffiche+1;
          label(TEX("\num{"&decimal(NbAffiche[nbaffiche])&"}"),M[k][l]);
        endfor;
        endfor;
      remplis ((unitsquare scaled 10mm) shifted N[choixligneD][choixcolonneD]) withcolor \useKV[ClesLabyNb]{Couleur};
      remplis ((unitsquare scaled 10mm) shifted Arrivee) withcolor \useKV[ClesLabyNb]{Couleur};
      if \useKV[ClesLabyNb]{Chemin}:
      for k=2 upto indiceChemin-1:
      remplis ((unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])]) withcolor white;
      endfor;
      trace ((center unitsquare scaled 10mm) shifted N[choixligneD][choixcolonneD])
      for k=2 upto indiceChemin-1:
      -- ((center unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])])
      endfor
      --((center unitsquare scaled 10mm) shifted Arrivee) dashed evenly withcolor Brown;
      for k=2 upto indiceChemin-1:
      label(TEX("\num{"&decimal(NbSol[k])&"}"),M[xpart(PileChemin[k])][ypart(PileChemin[k])]);
      endfor;
      else:
      for k=2 upto indiceChemin-1:
      remplis ((unitsquare scaled 10mm) shifted N[xpart(PileChemin[k])][ypart(PileChemin[k])]) withcolor \useKV[ClesLabyNb]{CouleurChemin};
      label(TEX("\num{"&decimal(NbSol[k])&"}"),M[xpart(PileChemin[k])][ypart(PileChemin[k])]);
      endfor;
      fi;
      trace TraceLabyrinthe;
      );
      CorpsSolution:=(CorpsSolution scaled \useKV[ClesLabyNb]{Echelle}) rotated \useKV[ClesLabyNb]{Angle};
      trace CorpsSolution;
  \end{mplibcode}
}%

%%%
% Mots croisés
%%%
\setKVdefault[ClesCroises]{Lignes=6,Colonnes=8,Solution=false,Croises=false,Couleur=gray,Largeur=1em}

\newcounter{PfCLettreHorizontal}

\newcommand\MotsCroises[2][]{%
  \useKVdefault[ClesCroises]%
  \setKV[ClesCroises]{#1}%
  \setcounter{PfCLettreHorizontal}{0}%
  \setsepchar[*]{§*,*/}%
  \readlist*\ListeCasesCroises{#2}%
  \begin{NiceTabular}{*{\fpeval{\useKV[ClesCroises]{Colonnes}}}{p{\useKV[ClesCroises]{Largeur}}}}[first-row,first-col]%
    \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[ClesCroises]{Colonnes}}}}\do{%
      &\ifboolKV[ClesCroises]{Croises}{\stepcounter{PfCLettreHorizontal}\footnotesize\Alph{PfCLettreHorizontal}}{}
    }\\
    \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[ClesCroises]{Lignes}}}}\do{%
      \ifboolKV[ClesCroises]{Croises}{\footnotesize##1}{}\xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[ClesCroises]{Colonnes}}}}\do{%
        &\IfStrEq{\ListeCasesCroises[##1,##2,1]}{!}{%
        }{%
          \IfStrEq{\ListeCasesCroises[##1,##2,1]}{*}{%
            \Block[draw,fill=black]{}{\PfCTBstrut}}{%
            \IfStrEq{\ListeCasesCroises[##1,##2,1]}{+}{%
              \Block[draw,fill=\useKV[ClesCroises]{Couleur}]{}{%
                \PfCTBstrut\ifboolKV[ClesCroises]{Solution}{%
                  \ListeCasesCroises[##1,##2,2]%
                }{}%
              }
            }{%
              \Block[draw]{}{\PfCTBstrut\ifboolKV[ClesCroises]{Solution}{%
                  \ListeCasesCroises[##1,##2,2]}{}%
              }%
            }%
          }%
        }%
      }\\
    }%
    \CodeAfter
    \xintFor* ##1 in {\xintSeq{1}{\fpeval{\useKV[ClesCroises]{Lignes}}}}\do{%
      \xintFor* ##2 in {\xintSeq{1}{\fpeval{\useKV[ClesCroises]{Colonnes}}}}\do{%
        \IfStrEq{\ListeCasesCroises[##1,##2,1]}{!}{%
        }{%
          \IfStrEq{\ListeCasesCroises[##1,##2,1]}{*}{%
          }{%
            \IfStrEq{\ListeCasesCroises[##1,##2,1]}{+}{%
            }{%
              \xintifboolexpr{\fpeval{\ListeCasesCroises[##1,##2,1]}>0}{\tikz\node[transform canvas={xshift=1mm,yshift=-1mm}] at (\fpeval{##1}-|\fpeval{##2}){\tiny\ListeCasesCroises[##1,##2,1]};}{}%
            }%
          }%
        }%
      }%
    }%
  \end{NiceTabular}%
  \setsepchar{,}%
}%


%%%
% Mots empilés
%%%
\setKVdefault[ClesMotEmpile]{Colonne=4,Solution=false,Couleur=black}

\newcounter{CompteurMotEmpile}

\newcommand\MotsEmpiles[2][]{%
  \useKVdefault[ClesMotEmpile]%
  \setKV[ClesMotEmpile]{#1}%
  \setcounter{CompteurMotEmpile}{0}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeMotsEmpiles{#2}%
  \xdef\ListeMotsEmpilesMax{0}%
  \colorlet{MotEmpileCouleur}{\useKV[ClesMotEmpile]{Couleur}}%
  \foreachitem\compteur\in\ListeMotsEmpiles{%
    \StrLen{\ListeMotsEmpiles[\compteurcnt,2]}[\LongueurMot]%
    \xintifboolexpr{\ListeMotsEmpilesMax<\fpeval{\ListeMotsEmpiles[\compteurcnt,1]+\LongueurMot}}{\xdef\ListeMotsEmpilesMax{\fpeval{\ListeMotsEmpiles[\compteurcnt,1]+\LongueurMot}}}{}%
  }%
  \begin{NiceTabular}{c|*{\fpeval{\ListeMotsEmpilesMax}}{m{0.5em}}}%
    \Block{1-\fpeval{\useKV[ClesMotEmpile]{Colonne}+2}}{}\xintFor* ##1 in {\xintSeq {1}{\fpeval{\useKV[ClesMotEmpile]{Colonne}}}}\do{&}&$\downarrow$\xintFor* ##1 in {\xintSeq {1}{\fpeval{\ListeMotsEmpilesMax-\useKV[ClesMotEmpile]{Colonne}-1}}}\do{&}\\
    \xintFor* ##1 in {\xintSeq {1}{\fpeval{\ListeMotsEmpileslen}}}\do{%
      \rule[-1.2ex]{0pt}{3.8ex}\stepcounter{CompteurMotEmpile}\Alph{CompteurMotEmpile}&\Block{1-\fpeval{\ListeMotsEmpiles[##1,1]}}{}\xintFor* ##2 in {\xintSeq {1}{\fpeval{\ListeMotsEmpiles[##1,1]}}}\do{%
        &
      }%
      \StrLen{\ListeMotsEmpiles[##1,2]}[\LongueurMot]%
      \xintFor* ##3 in {\xintSeq {1}{\fpeval{\LongueurMot}}}\do{%
        \xintifForFirst{}{&}\Block[draw=black]{1-1}{\ifboolKV[ClesMotEmpile]{Solution}{\centering\arraybackslash\StrMid{\ListeMotsEmpiles[##1,2]}{##3}{##3}}{}}%%
      }%
      \\
    }%
    \CodeAfter\tikz\draw[line width=1.5pt,MotEmpileCouleur](row-2-|col-\fpeval{\useKV[ClesMotEmpile]{Colonne}+2}) rectangle (row-\fpeval{\ListeMotsEmpileslen+2}-|col-\fpeval{\useKV[ClesMotEmpile]{Colonne}+3});
  \end{NiceTabular}%
}%

%%% Colorilude %%%
\setKVdefault[Colorilude]{Largeur=10,Lignes=10,Legende=false,Coef=0.6,Solution=false,CartonReponse=false,Resultats=false}

\newcommand\dispogpfc[3][]{%
  \setbox1=\hbox{#2}%
  \setbox2=\hbox{#3}%
  \begin{minipage}{\wd2}%
    #3%
  \end{minipage}%
  \quad%
  \begin{minipage}{\wd1}%
    #2%
  \end{minipage}%
}%

\newcommand\TraceEchiquierColorilude{%
  \ifluatex
  \begin{mplibcode}
    pair A,B,C,D;%pour la grille
    A=(0,0);
    B-A=u*\useKV[Colorilude]{Coef}*(\useKV[Colorilude]{Largeur},0);
    C-B=u*\useKV[Colorilude]{Coef}*(0,-\useKV[Colorilude]{Lignes});
    D-C=A-B;
    nblargeur=\useKV[Colorilude]{Largeur};
    nblignes=\useKV[Colorilude]{Lignes};
    for k=1 upto nblargeur-1:
    draw (k/nblargeur)[A,B]--(k/nblargeur)[D,C];
    endfor;
    for k=1 upto nblignes-1:
    draw (k/nblignes)[A,D]--(k/nblignes)[B,C];
    endfor;
    draw polygone(A,B,C,D) withpen pensquare scaled 1.5;
    if \useKV[Colorilude]{Legende}:
    label.lrt(btex \tiny d'après APMEP etex rotated 90,B);
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={boolean Legende;
      Legende=\useKV[Colorilude]{Legende};
      nblargeur:=\useKV[Colorilude]{Largeur};
      nblignes:=\useKV[Colorilude]{Lignes};
      coef:=\useKV[Colorilude]{Coef};}]
    pair A,B,C,D;%pour la grille
    A=(0,0);
    B-A=u*coef*(nblargeur,0);
    C-B=u*coef*(0,-nblignes);
    D-C=A-B;
    for k=1 upto nblargeur-1:
    draw (k/nblargeur)[A,B]--(k/nblargeur)[D,C];
    endfor;
    for k=1 upto nblignes-1:
    draw (k/nblignes)[A,D]--(k/nblignes)[B,C];
    endfor;
    draw polygone(A,B,C,D) withpen pensquare scaled 1.5;
    if Legende:
    label.lrt(\btex \tiny d'après APMEP etex rotated 90,B);
    fi;
  \end{mpost}
  \fi
}%

\newcommand\TraceEchiquierColoreColorilude{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}
    pair A,B,C,D;%pour la grille
    A=(0,0);
    B-A=u*\useKV[Colorilude]{Coef}*(\useKV[Colorilude]{Largeur},0);
    C-B=u*\useKV[Colorilude]{Coef}*(0,-\useKV[Colorilude]{Lignes});
    D-C=A-B;
    numeric nblargeur,nblignes;
    nblargeur:=\useKV[Colorilude]{Largeur};
    nblignes:=\useKV[Colorilude]{Lignes};
    % on récupère les données de coloriage
    numeric n;
    n:=0;
    numeric nbCases[];
    color ColorSucc[];
    for p_=\the\toklisteremplissage:
    n:=n+1;
    if (n mod 2)=0:
    nbCases[n div 2]:=p_;
    else:
    ColorSucc[n div 2]:=p_;
    fi;
    endfor;
    % on colorie :)
    numeric NBCASES;
    NBCASES:=0;
    for l=1 upto (n div 2):
    fill ((unitsquare xscaled (\useKV[Colorilude]{Coef}*u*nbCases[l]) yscaled (\useKV[Colorilude]{Coef}*u)) shifted(\useKV[Colorilude]{Coef}*u*(NBCASES mod nblargeur,-1-(NBCASES div nblargeur)))) withcolor ColorSucc[l-1];
    NBCASES:=NBCASES+nbCases[l];
    endfor;
    % on trace le quadrillage
    for k=1 upto nblargeur-1:
    draw (k/nblargeur)[A,B]--(k/nblargeur)[D,C];
    endfor;
    for k=1 upto nblignes-1:
    draw (k/nblignes)[A,D]--(k/nblignes)[B,C];
    endfor;
    draw polygone(A,B,C,D) withpen pensquare scaled 1.5;
    if \useKV[Colorilude]{Legende}:
    label.lrt(btex \tiny d'après APMEP etex rotated 90,B);
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={boolean Legende;
      Legende=\useKV[Colorilude]{Legende};
      nblargeur:=\useKV[Colorilude]{Largeur};
      nblignes:=\useKV[Colorilude]{Lignes};
      coef:=\useKV[Colorilude]{Coef};
      numeric n;
      n:=0;
      numeric nbCases[];
      color ColorSucc[];
      for p_=\the\toklisteremplissage:
      n:=n+1;
      if (n mod 2)=0:
      nbCases[n div 2]:=p_;
      else:
      ColorSucc[n div 2]:=p_;
      fi;
      endfor;
    }]
    pair A,B,C,D;%pour la grille
    A=(0,0);
    B-A=u*coef*(nblargeur,0);
    C-B=u*coef*(0,-nblignes);
    D-C=A-B;
    % on colorie :)
    numeric NBCASES;
    NBCASES:=0;
    for l=1 upto (n div 2):
    fill ((unitsquare xscaled (coef*u*nbCases[l]) yscaled (coef*u)) shifted(coef*u*(NBCASES mod nblargeur,-1-(NBCASES div nblargeur)))) withcolor ColorSucc[l-1];
    NBCASES:=NBCASES+nbCases[l];
    endfor;
    % on trace le quadrillage
    for k=1 upto nblargeur-1:
    draw (k/nblargeur)[A,B]--(k/nblargeur)[D,C];
    endfor;
    for k=1 upto nblignes-1:
    draw (k/nblignes)[A,D]--(k/nblignes)[B,C];
    endfor;
    draw polygone(A,B,C,D) withpen pensquare scaled 1.5;
    if Legende:
    label.lrt(\btex \tiny d'après APMEP etex rotated 90,B);
    fi;
  \end{mpost}
  \fi
}%

\newtoks\toklisteremplissage%
\toklisteremplissage{}%
\def\UpdateRemplissage#1\nil{\addtotok\toklisteremplissage{#1,}}%

\newcommand\ColoriludeEnonce{%
Pour chaque ligne de la grille, colorie de gauche à droite, de la
couleur indiquée, le nombre de cases donné par le résultat du calcul.
}%

\newcommand\ColoriludeListeCouleur[1]{%
  \setsepchar{ }%
  \readlist\ListeColoriludeCouleurs{#1}%
  \foreachitem\compteur\in\ListeColoriludeCouleurs{%
     \ifodd\compteurcnt\fbox{\begin{minipage}{1em}\centering\text{\ttfamily\bfseries\compteur}\end{minipage}}~\else\compteur\quad\fi%
  }%
}%

\newcommand\Colorilude[2][]{%
  \useKVdefault[Colorilude]%
  \setKV[Colorilude]{#1}%
  \setsepchar{\\/ }%
  \readlist\ListeColorilude{#2}%
  \ifboolKV[Colorilude]{Solution}{%
    \toklisteremplissage{}%
    \foreachitem\compteur\in\ListeColorilude{%
      \foreachitem\couleur\in\ListeColorilude[\compteurcnt]{%
        \expandafter\UpdateRemplissage\couleur\nil}%
    }%
    \TraceEchiquierColoreColorilude%
  }{%
    \dispogpfc{%
      \TraceEchiquierColorilude%
    }{%
      % On cherche le nombre max de colonnes
      \xdef\ListeColoriludeMax{0}%
      \xintFor* ##1 in {\xintSeq {1}{\ListeColoriludelen}}\do{%
        \xintifboolexpr{\listlen\ListeColorilude[##1]>\ListeColoriludeMax}{%
          \xdef\ListeColoriludeMax{\listlen\ListeColorilude[##1]}%
        }{}%
      }%
      \setlength{\tabcolsep}{0.2\tabcolsep}%
      \begin{NiceTabular}{*{\fpeval{\ListeColoriludeMax/2}}{rl}}%
        \xintFor* ##1 in {\xintSeq {1}{\ListeColoriludelen}}\do{%
          \xintifboolexpr{\listlen\ListeColorilude[##1]==\ListeColoriludeMax}{%
            \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeColorilude[##1]}}\do{%
              \xintifForFirst{}{&~}\ifodd##2\fbox{\begin{minipage}{1em}\centering\text{\ttfamily\bfseries\ListeColorilude[##1,##2]}\end{minipage}}\ifboolKV[Colorilude]{Resultats}{\fbox{\begin{minipage}{1em}\centering\ttfamily\bfseries \phantom{R}\end{minipage}}}{}~\else\ifboolKV[Colorilude]{CartonReponse}{\pointilles[25pt]}{$\ListeColorilude[##1,##2]$}\fi%
            }%
          }{%
            \xintFor* ##2 in {\xintSeq {1}{\listlen\ListeColorilude[##1]}}\do{%
              \xintifForFirst{}{&~}\ifodd##2\fbox{\begin{minipage}{1em}\centering\text{\ttfamily\bfseries\ListeColorilude[##1,##2]}\end{minipage}}\ifboolKV[Colorilude]{Resultats}{\fbox{\begin{minipage}{1em}\centering\ttfamily\bfseries \phantom{R}\end{minipage}}}{}~\else\ifboolKV[Colorilude]{CartonReponse}{\pointilles[25pt]}{$\ListeColorilude[##1,##2]$}\fi%
            }%
            &\hbox to5pt{}&\Cdots%
          }%
          \\[0.5em]%
        }%
      \end{NiceTabular}%
    }%
  }%
}%

%%%
% Mosaique
%%%
\setKVdefault[ClesMosaique]{Largeur=2,Hauteur=2,Solution=false,Type=1,Label,Echelle=1cm}

\newcommand\DessineMosaique[2][]{%
  \useKVdefault[ClesMosaique]%
  \setKV[ClesMosaique]{#1}%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}
    u:=\useKV[ClesMosaique]{Echelle};
    Type:=\useKV[ClesMosaique]{Type};
    input PfCMosaique;
    trace if Type=1:MosaiqueUn[#2] elseif Type=2: MosaiqueDeux[#2] fi;
  \end{mplibcode}%
  \else%
  \begin{mpost}[mpsettings={u:=\useKV[ClesMosaique]{Echelle};Type:=\useKV[ClesMosaique]{Type};}]%
    input PfCMosaique;
    trace if Type=1:MosaiqueUn[#2] elseif Type=2: MosaiqueDeux[#2] fi;
  \end{mpost}%
  \fi%
}%

\newcommand\DessineMosaiqueComplet[1]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCMosaique;
    Largeur=\useKV[ClesMosaique]{Largeur};
    Hauteur=\useKV[ClesMosaique]{Hauteur};
    Type=\useKV[ClesMosaique]{Type};
    boolean Solution,Label;
    Solution=\useKV[ClesMosaique]{Solution};
    Label=\useKV[ClesMosaique]{Label};
    pair A,B,C,D;
    A=u*(0,1);
    B-A=u*(Largeur,0);
    C-B=u*(0,-Hauteur);
    D-C=A-B;
    picture mosaique;
    path case;
    case=unitsquare scaled 1cm;
    if Type=1:
    mosaique=image(
    trace case withcolor 0.5white;
    trace (point(0) of case)--(point(2) of case) withcolor 0.75white;
    trace (point(1) of case)--(point(3) of case) withcolor 0.75white;
    trace (point(0.5) of case)--(point(2.5) of case) withcolor 0.75white;
    trace (point(1.5) of case)--(point(3.5) of case) withcolor 0.75white;
    );
    else:
    mosaique=image(
    trace case withcolor 0.5white;
    trace (point(0.5) of case)--(point(2.5) of case) withcolor 0.75white;
    trace (point(1.5) of case)--(point(3.5) of case) withcolor 0.75white;
    trace (point(0.5) of case)--(point(1.5) of case)--(point(2.5) of case)--(point(3.5) of case)--cycle withcolor 0.75white;
    );
    fi;
    if Solution:
    nbmos:=0;
    for p_=#1:
    trace if Type=1:MosaiqueUn[xpart(p_)] else: MosaiqueDeux[xpart(p_)] fi shifted(u*(nbmos mod Largeur,-(nbmos div Largeur)));
    nbmos:=nbmos+1;
    endfor;
    else:
    nbmos:=0;
    for p_=#1:
    trace mosaique shifted(u*(nbmos mod Largeur,-(nbmos div Largeur)));
    if Label:
    label(TEX("\num{"&decimal(ypart(p_))&"}"),center (mosaique  shifted(u*(nbmos mod Largeur,-(nbmos div Largeur)))));
    fi;
    nbmos:=nbmos+1;
    endfor;
    fi;
    trace polygone(A,B,C,D);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={Largeur=\useKV[ClesMosaique]{Largeur};Hauteur=\useKV[ClesMosaique]{Hauteur};Type=\useKV[ClesMosaique]{Type};boolean Solution,Label;Solution=\useKV[ClesMosaique]{Solution};}]
    Label=\useKV[ClesMosaique]{Label};
    input PfCMosaique;
    pair A,B,C,D;
    A=u*(0,1);
    B-A=u*(Largeur,0);
    C-B=u*(0,-Hauteur);
    D-C=A-B;
    picture mosaique;
    path case;
    case=unitsquare scaled 1cm;
    if Type=1:
    mosaique=image(
    trace case withcolor 0.5white;
    trace (point(0) of case)--(point(2) of case) withcolor 0.75white;
    trace (point(1) of case)--(point(3) of case) withcolor 0.75white;
    trace (point(0.5) of case)--(point(2.5) of case) withcolor 0.75white;
    trace (point(1.5) of case)--(point(3.5) of case) withcolor 0.75white;
    );
    else:
    mosaique=image(
    trace case withcolor 0.5white;
    trace (point(0.5) of case)--(point(2.5) of case) withcolor 0.75white;
    trace (point(1.5) of case)--(point(3.5) of case) withcolor 0.75white;
    trace (point(0.5) of case)--(point(1.5) of case)--(point(2.5) of case)--(point(3.5) of case)--cycle withcolor 0.75white;
    );
    fi;
    if Solution:
    nbmos:=0;
    for p_=#1:
    trace if Type=1:MosaiqueUn[xpart(p_)] else: MosaiqueDeux[xpart(p_)] fi shifted(u*(nbmos mod Largeur,-(nbmos div Largeur)));
    nbmos:=nbmos+1;
    endfor;
    else:
    nbmos:=0;
    for p_=#1:
    trace mosaique shifted(u*(nbmos mod Largeur,-(nbmos div Largeur)));
    if Label:
    label(LATEX("\num{"&decimal(ypart(p_))&"}"),center (mosaique  shifted(u*(nbmos mod Largeur,-(nbmos div Largeur)))));
    fi;
    nbmos:=nbmos+1;
    endfor;
    fi;
    trace polygone(A,B,C,D);
  \end{mpost}
  \fi
}%
    
\newtoks\toklistecaseM%
\def\UpdatetoksMosaique#1/#2\nil{\addtotok\toklistecaseM{(#1,#2),}}%

\newcommand\Mosaique[2][]{%
  \useKVdefault[ClesMosaique]%
  \setKV[ClesMosaique]{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeMosaique{#2}%
  \toklistecaseM{}%
  \foreachitem\compteur\in\ListeMosaique{\expandafter\UpdatetoksMosaique\compteur\nil}%
  \DessineMosaiqueComplet{\the\toklistecaseM}%
}%

%%%
% Qui suis-je
%%%
\setKVdefault[Quisuisje]{Solution=false,Largeur=5mm,Colonnes=5,CodePerso=false,TexteA=Lettre,TexteB=R\'esultat du calcul}%

\newcommand\QuisuisjeEnonce{%
  Chaque lettre du mot à découvrir porte un numéro qui correspond à un
  calcul à effectuer. Pour trouver les lettres de ce mot, tu dois donc
  effectuer les calculs proposés. Les résultats que tu auras trouvés
  te donneront, à l'aide du tableau de correspondance ci-dessous, les
  lettres du mot.
}%

\newcommand\QuisuisjeTableau[2][]{%
  \setKV[Quisuisje]{#1}%
  \setsepchar[*]{§*/}\ignoreemptyitems%
  \readlist*\ListeQuisuisje{#2}%
  \begin{NiceTabular}{|l|*{\ListeQuisuisjelen}{m{\useKV[Quisuisje]{Largeur}}|}}%
    \hline
    \useKV[Quisuisje]{TexteA}\xintFor* ##1 in {\xintSeq {1}{\ListeQuisuisjelen}}\do{%
      &\centering\arraybackslash\ListeQuisuisje[##1,1]
    }\\
    \hline
    \useKV[Quisuisje]{TexteB}\xintFor* ##1 in {\xintSeq {1}{\ListeQuisuisjelen}}\do{%
      &\centering\arraybackslash\ListeQuisuisje[##1,2]
    }\\
    \hline
  \end{NiceTabular}%
}%

\newcommand\QuisuisjeCodePerso[3][]{%
  \setKV[Quisuisje]{#1}%
  \setsepchar{ }%
  \readlist*\ListeQuisuisjeCode{#2}%
  \readlist*\ListeQuisuisjeLettres{#3}%
  \par\hfill%
  \begin{NiceTabular}{|*{\ListeQuisuisjeLettreslen}{m{7mm}|}}
    \hline
    \xintFor* ##1 in {\xintSeq {1}{\ListeQuisuisjeLettreslen}}\do{%
      \xintifForFirst{}{&}\ifboolKV[Quisuisje]{Solution}{\hfill\ListeQuisuisjeLettres[##1]}{\phantom{1}}
    }\\
    \xintFor* ##1 in {\xintSeq {1}{\ListeQuisuisjeLettreslen}}\do{%
      \xintifForFirst{}{&}\tiny\ListeQuisuisjeCode[##1]%
    }\\
    \hline
  \end{NiceTabular}%
}%

\newcommand\Quisuisje[3][]{%
  \useKVdefault[Quisuisje]%
  \setKV[Quisuisje]{#1}%
  \ifboolKV[Quisuisje]{CodePerso}{}{%
    \setsepchar{ }%
    \readlist\ListeLettres{#3}%
  }%
  \setsepchar{§}%
  \readlist\ListeCalculs{#2}%
  \ifboolKV[Quisuisje]{CodePerso}{}{%
    \par\hfill%
    \begin{NiceTabular}{|*{\ListeLettreslen}{m{7mm}|}}
      \hline
      \xintFor* ##1 in {\xintSeq {1}{\ListeLettreslen}}\do{%
        \xintifForFirst{}{&} \ifboolKV[Quisuisje]{Solution}{\hfill\ListeLettres[##1]}{\phantom{1}}
      }\\
      \xintFor* ##1 in {\xintSeq {1}{\ListeLettreslen}}\do{%
        \xintifForFirst{}{&}\tiny\num{##1}%
      }\\
      \hline
    \end{NiceTabular}%
  }%
  \par\bigskip\par
  \ifboolKV[Quisuisje]{Solution}{}{%
    \begin{multicols}{\useKV[Quisuisje]{Colonnes}}%
      \begin{enumerate}
        \xintFor* ##1 in {\xintSeq {1}{\ListeCalculslen}}\do{%
        \item\ListeCalculs[##1]
        }
      \end{enumerate}%
    \end{multicols}%
  }%
}%

%%% Dessin Gradue %%%
\setKVdefault[DessinGradue]{Lignes=10,Debut=-5,Fin=5,Pas=10,Solution=false,EcartVertical=1.5,LignesIdentiques,Longueur=10,Echelle=1,Droites=false,DemiDroites=false}

\def\TraceDessinGradue#1#2#3#4#5#6{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    pair La,Lb,Lab[];
    pair A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A',B',C',D',E',F',G',H',I',J',K',L',M',N',O',P',Q',R',S',T',U',V',W',X',Y',Z',A'',B'',C'',D'',E'',F'',G'',H'',I'',J'',K'',L'',M'',N'',O'',P'',Q'',R'',S'',T'',U'',V'',W'',X'',Y'',Z'';
    La=(0,0);
    Lb-La=u*(\useKV[DessinGradue]{Longueur},0);
    boolean Solution;
    Solution=\useKV[DessinGradue]{Solution};
    for k=0 upto #4:
    Lab[k]=(k/#4)[La,Lb];
    endfor;
    picture EnsembleLignes,Lignes;
    Lignes=image(
    if \useKV[DessinGradue]{Droites}:
    drawarrow 1.05[Lb,La]--1.05[La,Lb];
    elseif \useKV[DessinGradue]{DemiDroites}:
    drawarrow La--1.05[La,Lb];
    else:
    trace segment(La,Lb);
    fi;
    for k=0 upto #4:
    trace (Lab[k]+u*(0,-0.1))--(Lab[k]+u*(0,0.1));
    endfor;
    labeloffset:=labeloffset*1.5;
    label.top(TEX("\num{"&decimal(#2)&"}"),La);
    label.top(TEX("\num{"&decimal(#3)&"}"),Lb);
    labeloffset:=labeloffset/1.5;
    );
    EnsembleLignes=image(
    if Solution:
    drawoptions(withcolor 0.5white);
    fi;
    for k=0 upto #1-1:
    trace Lignes shifted(k*u*(0,-\useKV[DessinGradue]{EcartVertical}));
    label(TEX("(\num{"&decimal(k+1)&"})"),La+u*(-1.5,-k*\useKV[DessinGradue]{EcartVertical}));
    endfor;
    drawoptions();
    if Solution:
    n:=0;
    numeric nblignes,nbpas;
    for p_=#5:
    n:=n+1;
    if (n mod 3)=1:
    nblignes:=p_;
    elseif (n mod 3)=2:
    nbpas:=p_;
    elseif (n mod 3)=0:
    p_=(nbpas/#4)[La,Lb] shifted(u*(0,(nblignes-1)*(-\useKV[DessinGradue]{EcartVertical})));
    fi;
    endfor;
    for p_=#6:
    trace p_ withpen pencircle scaled 1.5;
    endfor;
    fi;
    );
    trace EnsembleLignes scaled \useKV[DessinGradue]{Echelle};
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric LongueurLigne; LongueurLigne=\useKV[DessinGradue]{Longueur};numeric EcartVertical; EcartVertical=\useKV[DessinGradue]{EcartVertical}; numeric Echelle; Echelle=\useKV[DessinGradue]{Echelle}; boolean Solution,Droites,DemiDroites; Solution=\useKV[DessinGradue]{Solution};Droites=\useKV[DessinGradue]{Droites};DemiDroites=\useKV[DessinGradue]{DemiDroites};}]
    pair La,Lb,Lab[];
    pair A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A',B',C',D',E',F',G',H',I',J',K',L',M',N',O',P',Q',R',S',T',U',V',W',X',Y',Z',A'',B'',C'',D'',E'',F'',G'',H'',I'',J'',K'',L'',M'',N'',O'',P'',Q'',R'',S'',T'',U'',V'',W'',X'',Y'',Z'';
    La=(0,0);
    Lb-La=u*(LongueurLigne,0);
    for k=0 upto #4:
    Lab[k]=(k/#4)[La,Lb];
    endfor;
    picture EnsembleLignes,Lignes;
    Lignes=image(
    if Droites:
    drawarrow 1.05[Lb,La]--1.05[La,Lb];
    elseif DemiDroites:
    drawarrow La--1.05[La,Lb];
    else:
    trace segment(La,Lb);
    fi;
    for k=0 upto #4:
    trace (Lab[k]+u*(0,-0.1))--(Lab[k]+u*(0,0.1));
    endfor;
    labeloffset:=labeloffset*1.5;
    label.top(LATEX("\num{"&decimal(#2)&"}"),La);
    label.top(LATEX("\num{"&decimal(#3)&"}"),Lb);
    labeloffset:=labeloffset/1.5;
    );
    EnsembleLignes=image(
    if Solution:
    drawoptions(withcolor 0.5white);
    fi;
    for k=0 upto #1-1:
    trace Lignes shifted(k*u*(0,-EcartVertical));
    label(LATEX("(\num{"&decimal(k+1)&"})"),La+u*(-1.5,-k*EcartVertical));
    endfor;
    drawoptions();
    if Solution:
    n:=0;
    numeric nblignes,nbpas;
    for p_=#5:
    n:=n+1;
    if (n mod 3)=1:
    nblignes:=p_;
    elseif (n mod 3)=2:
    nbpas:=p_;
    elseif (n mod 3)=0:
    p_=(nbpas/#4)[La,Lb] shifted(u*(0,(nblignes-1)*(-EcartVertical)));
    fi;
    endfor;
    for p_=#6:
    trace p_ withpen pencircle scaled 1.5;
    endfor;
    fi;
    );
    trace EnsembleLignes scaled Echelle;
  \end{mpost}
  \fi
}

\def\TraceDessinGradueMul#1#2#3{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    pair La,Lb,Lab[];
    La=(0,0);
    pair A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A',B',C',D',E',F',G',H',I',J',K',L',M',N',O',P',Q',R',S',T',U',V',W',X',Y',Z',A'',B'',C'',D'',E'',F'',G'',H'',I'',J'',K'',L'',M'',N'',O'',P'',Q'',R'',S'',T'',U'',V'',W'',X'',Y'',Z'';
    Lb-La=u*(\useKV[DessinGradue]{Longueur},0);
    EcartVertical=\useKV[DessinGradue]{EcartVertical};
    boolean Solution;
    Solution=\useKV[DessinGradue]{Solution};
    picture EnsembleLignes,Lignes;
    EnsembleLignes=image(
    if Solution:
    drawoptions(withcolor 0.5white);
    fi;
    n:=0;
    m:=0;
    for p_=#1:
    n:=n+1;
    if \useKV[DessinGradue]{Droites}:
    drawarrow (1.05[Lb,La]--1.05[La,Lb]) shifted((n-1)*u*(0,-EcartVertical));
    elseif \useKV[DessinGradue]{DemiDroites}:
    drawarrow (La--1.05[La,Lb]) shifted((n-1)*u*(0,-EcartVertical));
    else:
    trace segment(La,Lb) shifted((n-1)*u*(0,-EcartVertical));
    fi;
    label(TEX("(\num{"&decimal(n)&"})"),La+u*(-1.5,-(n-1)*EcartVertical));
    for k=0 upto bluepart(p_):
    m:=bluepart(p_);
    retienspas[n]:=m;
    Lab[k]:=(k/m)[La,Lb];
    trace ((Lab[k]+u*(0,-0.1))--(Lab[k]+u*(0,0.1))) shifted((n-1)*u*(0,-EcartVertical));
    endfor;
    labeloffset:=labeloffset*1.5;
    label.top(TEX("\num{"&decimal(redpart(p_))&"}"),La shifted((n-1)*u*(0,-EcartVertical)));
    label.top(TEX("\num{"&decimal(greenpart(p_))&"}"),Lb shifted((n-1)*u*(0,-EcartVertical)));
    labeloffset:=labeloffset/1.5;
    endfor;
    drawoptions();
    if Solution:
    n:=0;
    numeric nblignes,nbpas;
    for p_=#2:
    n:=n+1;
    if (n mod 3)=1:
    nblignes:=p_;
    elseif (n mod 3)=2:
    nbpas:=p_;
    elseif (n mod 3)=0:
    p_=(nbpas/retienspas[nblignes])[La,Lb] shifted(u*(0,(nblignes-1)*(-\useKV[DessinGradue]{EcartVertical})));
    fi;
    endfor;
    %Differents traces
    for p_=#3:
    trace p_ withpen pencircle scaled 1.5;
    endfor;
    fi;
    );
    trace EnsembleLignes scaled \useKV[DessinGradue]{Echelle};
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric LongueurLigne; LongueurLigne=\useKV[DessinGradue]{Longueur};numeric EcartVertical; EcartVertical=\useKV[DessinGradue]{EcartVertical}; numeric Echelle; Echelle=\useKV[DessinGradue]{Echelle}; boolean Solution,Droites,DemiDroites; Solution=\useKV[DessinGradue]{Solution}; Droites=\useKV[DessinGradue]{Droites}; DemiDroites=\useKV[DessinGradue]{DemiDroites};}]
    pair La,Lb,Lab[];
    La=(0,0);
    pair A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A',B',C',D',E',F',G',H',I',J',K',L',M',N',O',P',Q',R',S',T',U',V',W',X',Y',Z',A'',B'',C'',D'',E'',F'',G'',H'',I'',J'',K'',L'',M'',N'',O'',P'',Q'',R'',S'',T'',U'',V'',W'',X'',Y'',Z'';
    Lb-La=u*(LongueurLigne,0);
    picture EnsembleLignes,Lignes;
    EnsembleLignes=image(
    if Solution:
    drawoptions(withcolor 0.5white);
    fi;
    n:=0;
    m:=0;
    for p_=#1:
    n:=n+1;
    if Droites:
    drawarrow (1.05[Lb,La]--1.05[La,Lb]) shifted((n-1)*u*(0,-EcartVertical));
    elseif DemiDroites:
    drawarrow (La--1.05[La,Lb]) shifted((n-1)*u*(0,-EcartVertical));
    else:
    trace segment(La,Lb) shifted((n-1)*u*(0,-EcartVertical));
    fi;
    label(LATEX("(\num{"&decimal(n)&"})"),La+u*(-1.5,-(n-1)*EcartVertical));
    for k=0 upto bluepart(p_):
    m:=bluepart(p_);
    retienspas[n]:=m;
    Lab[k]:=(k/m)[La,Lb];
    trace ((Lab[k]+u*(0,-0.1))--(Lab[k]+u*(0,0.1))) shifted((n-1)*u*(0,-EcartVertical));
    endfor;
    labeloffset:=labeloffset*1.5;
    label.top(LATEX("\num{"&decimal(redpart(p_))&"}"),La shifted((n-1)*u*(0,-EcartVertical)));
    label.top(LATEX("\num{"&decimal(greenpart(p_))&"}"),Lb shifted((n-1)*u*(0,-EcartVertical)));
    labeloffset:=labeloffset/1.5;
    endfor;
    drawoptions();
    if Solution:
    n:=0;
    numeric nblignes,nbpas;
    for p_=#2:
    n:=n+1;
    if (n mod 3)=1:
    nblignes:=p_;
    elseif (n mod 3)=2:
    nbpas:=p_;
    elseif (n mod 3)=0:
    p_=(nbpas/retienspas[nblignes])[La,Lb] shifted(u*(0,(nblignes-1)*(-EcartVertical)));
    fi;
    endfor;
    %Differents traces
    for p_=#3:
    trace p_ withpen pencircle scaled 1.5;
    endfor;
    fi;
    );
    trace EnsembleLignes scaled Echelle;
  \end{mpost}
  \fi
}

\def\UpdateLignes#1/#2/#3\nil{\addtotok\toklisteptsgrad{#1,#3,#2,}}
\def\UpdateTraces#1\nil{\addtotok\toklistetracesgrad{#1,}}
\def\UpdateDefLignes#1/#2/#3\nil{\addtotok\toklistedefligne{(#1,#2,#3),}}
\def\UpdateDefDroites#1/#2/#3/#4\nil{\addtotok\toklistedefligne{(#1,#2,#3),#4,}}

\newcommand\DessinGradue[4][]{%
  \useKVdefault[DessinGradue]%
  \setKV[DessinGradue]{#1}%
  \ifboolKV[DessinGradue]{LignesIdentiques}{%
    \newtoks\toklisteptsgrad%
    \newtoks\toklistetracesgrad%
    \ifboolKV[DessinGradue]{Solution}{%
      \setsepchar[*]{,*/}%
      \readlist\ListePG{#3}%
      \setsepchar[*]{§*/}%
      \readlist\ListeTraces{#4}%
      \foreachitem\compteur\in\ListePG{\expandafter\UpdateLignes\compteur\nil}%
      \foreachitem\compteur\in\ListeTraces{\expandafter\UpdateTraces\compteur\nil}%
    }{}%
    \TraceDessinGradue{\useKV[DessinGradue]{Lignes}}{\useKV[DessinGradue]{Debut}}{\useKV[DessinGradue]{Fin}}{\useKV[DessinGradue]{Pas}}{\the\toklisteptsgrad}{\the\toklistetracesgrad}%
  }{%
    \setsepchar[*]{,*/}%
    \readlist\ListeDefLigne{#2}%
    \xdef\toklistedefligne{}%
    \foreachitem\compteur\in\ListeDefLigne{%
      \xdef\toklistedefligne{\toklistedefligne (\ListeDefLigne[\compteurcnt,1],\ListeDefLigne[\compteurcnt,2],\ListeDefLigne[\compteurcnt,3]),}%
    }%
    \newtoks\toklisteptsgrad%
    \newtoks\toklistetracesgrad%
    \ifboolKV[DessinGradue]{Solution}{%
      \setsepchar[*]{,*/}%
      \readlist\ListePG{#3}%
      \setsepchar[*]{§*/}%
      \readlist\ListeTraces{#4}%
      \foreachitem\compteur\in\ListePG{\expandafter\UpdateLignes\compteur\nil}%
      \foreachitem\compteur\in\ListeTraces{\expandafter\UpdateTraces\compteur\nil}%
    }{}%
    \TraceDessinGradueMul{\toklistedefligne}{\the\toklisteptsgrad}{\the\toklistetracesgrad}%
  }%
}%

%%% Autonomie %%%
\setKVdefault[Autonomie]{AfficheMarge=false,TitreEnigme=Enigme,TitreAtoi=\`A toi,Enigme=false,TexteCorrection=\bfseries Correction,ARemplir=false,Deux=false,Landscape=false}%

\newcommand\Autonomie[3][]{%
  \useKVdefault[Autonomie]%
  \setKV[Autonomie]{#1}%
  \setsepchar[*]{§*/}%
  \readlist*\ListeAutoQ{#2}%
  % \setsepchar{§}
  % \readlist*\ListeAutoR{#3}%
  \setsepchar[*]{§*/}%
  \readlist*\ListeAutoEn{#3}%
  \clearpage
  \begin{tikzpicture}[remember picture,overlay]%
    \ifboolKV[Autonomie]{AfficheMarge}{%
      \node[xshift=5mm,yshift=-5mm,circle] (PfCA) at (current page.north west) {};%
      \node[xshift=-5mm,yshift=5mm] (PfCB) at (current page.south east) {};%
      \draw[blue,dashed] (PfCA) rectangle (PfCB);%
    }{}%
    \foreach \i in {1,...,3}{%
      \coordinate[xshift=\i*0.25*\paperwidth] (A\i) at (current page.north west);%
      \coordinate[xshift=\i*0.25*\paperwidth] (B\i) at (current page.south west);%
    }%
    \foreach \i in{1,...,4}{%
      \coordinate[yshift=-\i*0.25*\paperheight] (C\i) at (current page.north west);%
      \coordinate[yshift=-\i*0.25*\paperheight] (F\i) at (current page.north east);%
      \coordinate[yshift=-\i*0.25*\paperheight] (D\i) at (A1);%
      \coordinate[yshift=-\i*0.25*\paperheight] (E\i) at (A3);%
    }%
    \ifboolKV[Autonomie]{Deux}{%
      \draw (C2) to (D2);%
      \draw (E2) to (F2);%
    }{%
      \foreach\i in{1,...,4}{%
        \draw (C\i) to (D\i);%
        \draw (E\i) to (F\i);%
      }%
    }%
    \coordinate (O1) at ($(D1)!0.5!(D2)$);
    \coordinate (O2) at ($(D3)!0.5!(D4)$);
    \coordinate (O3) at ($(E1)!0.5!(E2)$);
    \coordinate (O4) at ($(E3)!0.5!(E4)$);
    \coordinate (Q1) at ($(F1)!0.5!(A3)$);%
    \coordinate (Q2) at ($(F2)!0.5!(E1)$);%
    \coordinate (Q3) at ($(F3)!0.5!(E2)$);%
    \coordinate (Q4) at ($(F4)!0.5!(E3)$);%
    \coordinate (Q5) at ($(C1)!0.5!(A1)$);%
    \coordinate (Q6) at ($(C2)!0.5!(D1)$);%
    \coordinate (Q7) at ($(C3)!0.5!(D2)$);%
    \coordinate (Q8) at ($(C4)!0.5!(D3)$);%
    \ifboolKV[Autonomie]{Landscape}{%
      \draw[dashed] (C1) to (F1);
      \draw[dashed] (C3) to (F3);
      \draw (A2) to (B2);%
    }{%
      \ifboolKV[Autonomie]{Deux}{%
        \draw (C2) to (D2);
        \draw (E2) to (F2);
      }{%
        \foreach\i in{1,...,4}{%
          \draw (C\i) to (D\i);
          \draw (E\i) to (F\i);
        }%
      }%
      \draw[dashed] (A1) to (B1);%
      \draw[dashed] (A3) to (B3);%
    }%
    %\draw[dashed] (A1) to (B1);%
    %\draw[dashed] (A3) to (B3);%
    \ifboolKV[Autonomie]{ARemplir}{%
      \ifboolKV[Autonomie]{Landscape}{%
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (O1) {\ListeAutoQ[1,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (O2) {\ListeAutoQ[2,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (O3) {\ListeAutoQ[3,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (O4) {\ListeAutoQ[4,1]};
      }{%
        \ifboolKV[Autonomie]{Deux}{%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] (Test1) at ($(Q1)!0.5!(Q2)$) {\ListeAutoQ[1,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] (Test2) at ($(Q3)!0.5!(Q4)$) {\ListeAutoQ[2,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] (Test3) at ($(Q5)!0.5!(Q6)$) {\ListeAutoQ[3,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] (Test4) at ($(Q7)!0.5!(Q8)$) {\ListeAutoQ[4,1]};%
        }{%
          \foreach \i in {1,...,4}{%
            \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] (Test\i) at (Q\i) {\ListeAutoQ[\i,1]};%
          }%
          \foreach \i in {5,...,8}{%
            \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] (Test\i) at (Q\i) {\ListeAutoQ[\i,1]};%
          }%
        }%
      }%
    }{%
      \foreach \i in {1,...,4}{%
        \node[xshift=-5mm,align=justify,anchor=center,text width=0.8*0.25\textwidth] (Test\i) at (Q\i) {\ding{\fpeval{171+\i}}~\ListeAutoQ[\i,1]};%
      }%
      \foreach \i in {5,...,8}{%
        \node[align=justify,anchor=center,text width=0.8*0.25\textwidth] (Test\i) at (Q\i) {\ding{\fpeval{171+\i}}~\ListeAutoQ[\i,1]};%
      }%
    }%
  \end{tikzpicture}%
  \clearpage%
  \begin{tikzpicture}[remember picture,overlay]%
    \ifboolKV[Autonomie]{AfficheMarge}{%
      \node[xshift=5mm,yshift=-5mm,circle] (PfCA) at (current page.north west) {};%
      \node[xshift=-5mm,yshift=5mm] (PfCB) at (current page.south east) {};%
      \draw[blue,dashed] (PfCA) rectangle (PfCB);%
    }{}%
    \foreach \i in {1,...,3}{%
      \coordinate[xshift=\i*0.25*\paperwidth] (A\i) at (current page.north west);%
      \coordinate[xshift=\i*0.25*\paperwidth] (B\i) at (current page.south west);%
    }%
    \foreach \i in{1,...,4}{%
      \coordinate[yshift=-\i*0.25*\paperheight] (C\i) at (current page.north west);%
      \coordinate[yshift=-\i*0.25*\paperheight] (F\i) at (current page.north east);%
      \coordinate[yshift=-\i*0.25*\paperheight] (D\i) at (A1);%
      \coordinate[yshift=-\i*0.25*\paperheight] (G\i) at (A2);%
      \coordinate[yshift=-\i*0.25*\paperheight] (E\i) at (A3);%
    }%
    \ifboolKV[Autonomie]{Deux}{%
      \draw (C2) to (F2);%
    }{%
      \foreach \i in{1,...,4}{%
        \draw (C\i) to (F\i);%
      }%
    }%
    \coordinate (T1) at ($(current page.north west)!0.5!(A1)$);%
    \coordinate (T2) at ($(C1)!0.5!(D1)$);%
    \coordinate (T3) at ($(C2)!0.5!(D2)$);%
    \coordinate (T4) at ($(C3)!0.5!(D3)$);%
    \coordinate (T5) at ($(current page.north east)!0.5!(A3)$);%
    \coordinate (T6) at ($(E1)!0.5!(F1)$);%
    \coordinate (T7) at ($(E2)!0.5!(F2)$);%
    \coordinate (T8) at ($(E3)!0.5!(F3)$);%
    \coordinate (U1) at ($(C1)!0.5!(D1)$);%
    \coordinate (U2) at ($(C2)!0.5!(D2)$);%
    \coordinate (U3) at ($(C3)!0.5!(D3)$);%
    \coordinate (U4) at ($(current page.south west)!0.5!(B1)$);%
    \coordinate (U5) at ($(E1)!0.5!(F1)$);%
    \coordinate (U6) at ($(E2)!0.5!(F2)$);%
    \coordinate (U7) at ($(E3)!0.5!(F3)$);%
    \coordinate (U8) at ($(B3)!0.5!(current page.south east)$);%
    \coordinate (R1) at ($(D1)!0.5!(A2)$);%
    \coordinate (R2) at ($(D2)!0.5!(G1)$);%
    \coordinate (R3) at ($(D3)!0.5!(G2)$);%
    \coordinate (R4) at ($(D4)!0.5!(G3)$);%
    \coordinate (R5) at ($(E1)!0.5!(A2)$);%
    \coordinate (R6) at ($(E2)!0.5!(G1)$);%
    \coordinate (R7) at ($(E3)!0.5!(G2)$);%
    \coordinate (R8) at ($(E4)!0.5!(G3)$);%
    \coordinate (S1) at ($(A1)!0.5!(D1)$);%
    \coordinate (S2) at ($(D1)!0.5!(D2)$);%
    \coordinate (S3) at ($(D2)!0.5!(D3)$);%
    \coordinate (S4) at ($(D3)!0.5!(B1)$);%
    \coordinate (S5) at ($(R1)!0.5!(R5)$);%
    \coordinate (S6) at ($(R2)!0.5!(R6)$);%
    \coordinate (S7) at ($(R3)!0.5!(R7)$);%
    \coordinate (S8) at ($(R4)!0.5!(R8)$);%
    \coordinate (V1) at ($(T1)!0.5!(U1)$);%
    \coordinate (V2) at ($(T2)!0.5!(U2)$);%
    \coordinate (V3) at ($(T3)!0.5!(U3)$);%
    \coordinate (V4) at ($(T4)!0.5!(U4)$);%
    \coordinate (V5) at ($(T5)!0.5!(U5)$);%
    \coordinate (V6) at ($(T6)!0.5!(U6)$);%
    \coordinate (V7) at ($(T7)!0.5!(U7)$);%
    \coordinate (V8) at ($(T8)!0.5!(U8)$);%
    \coordinate (W1) at ($(A3)!0.5!(E1)$);
    \coordinate (W2) at ($(E1)!0.5!(E2)$);
    \coordinate (W3) at ($(E2)!0.5!(E3)$);
    \coordinate (W4) at ($(E3)!0.5!(E4)$);
    \coordinate (W5) at ($(A1)!0.5!(D1)$);
    \coordinate (W6) at ($(D1)!0.5!(D2)$);
    \coordinate (W7) at ($(D2)!0.5!(D3)$);
    \coordinate (W8) at ($(D3)!0.5!(D4)$);
    \ifboolKV[Autonomie]{Landscape}{%
      \draw[dashed] (C1) to (F1);%
      \draw[dashed] (C3) to (F3);
      \draw (A2) to (B2);%
    }{%
      \draw[dashed] (A1) to (B1);%
      \draw[dashed] (A2) to (B2);
      \draw[dashed] (A3) to (B3);%
    }%
    %\draw[dashed] (A1) to (B1);%
    %\draw[dashed] (A2) to (B2);%
    %\draw[dashed] (A3) to (B3);%
    \ifboolKV[Autonomie]{ARemplir}{%
      \ifboolKV[Autonomie]{Landscape}{%
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W2) {\ListeAutoEn[4,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W4) {\ListeAutoEn[3,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W6) {\ListeAutoEn[2,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W8) {\ListeAutoEn[1,1]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W1) {\ListeAutoQ[4,2]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W3) {\ListeAutoQ[3,2]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W5) {\ListeAutoQ[2,2]};
        \node[align=justify,anchor=center,text width=0.9*0.5\textwidth] at (W7) {\ListeAutoQ[1,2]};
      }{%
        \ifboolKV[Autonomie]{Deux}{%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(V1)!0.5!(V2)$) {\ListeAutoEn[1,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(V3)!0.5!(V4)$) {\ListeAutoEn[2,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(V5)!0.5!(V6)$) {\ListeAutoEn[3,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(V7)!0.5!(V8)$) {\ListeAutoEn[4,1]};%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(R1)!0.5!(R2)$) {\ListeAutoQ[1,2]};%%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(R3)!0.5!(R4)$) {\ListeAutoQ[2,2]};%%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(R5)!0.5!(R6)$) {\ListeAutoQ[3,2]};%%
          \node[align=justify,anchor=center,text width=0.9*0.25\textwidth] at ($(R7)!0.5!(R8)$) {\ListeAutoQ[4,2]};%%
        }{%
          \foreach \i in {1,...,8}{%
            \node[text width=0.9*0.25\paperwidth] at (V\i) {\ListeAutoQ[\i,2]};%
            \node[text width=0.9*0.25\paperwidth] at (R\i) {\ListeAutoEn[\i,1]};%
          }%
        }%
      }%
    }{%
      \foreach \i in {1,...,8}{%
        \node[rotate=90,anchor=north] (Cor\i) at (S\i) {\useKV[Autonomie]{TexteCorrection}};%
        \node[anchor=west,xshift=2em,text width=0.8*0.25\paperwidth] (Test\i)
        at (S\i) {\ListeAutoQ[\i,2]};%
        \node[anchor=north,yshift=-1em,text width=0.85*0.25\paperwidth] (TestEn\i)
        at (T\i) {\textbf{\useKV[Autonomie]{TitreAtoi}} \ListeAutoEn[\i,1]};%
        \ifboolKV[Autonomie]{Enigme}{%
          \node[anchor=south,yshift=1em,text width=0.85*0.25\paperwidth] (TestREn\i)
          at (U\i) {%
            \ListeAutoEn[\i,2] : \pointilles\\%
            Lettre \ding{\fpeval{171+\i}} : \pointilles%
          };%
        }{%
          \node[anchor=south,yshift=1em,text width=0.85*0.25\paperwidth] (TestREn\i)
          at (U\i) {%
            \ListeAutoEn[\i,2]%
          };%
        }%
      }%
    }%
  \end{tikzpicture}%
}%

%%%
% Calculatrice
%%%
%https://tex.stackexchange.com/questions/290321/mimicking-a-calculator-inputs-and-screen
\definecolor{lightorange}{rgb}{0.9,0.4,0}%
\definecolor{lightestorange}{rgb}{1,0.8,0.5}%
\definecolor{darkorange}{rgb}{0.2,0.1,0}%

\colorlet{blackened}{black!90!white}%
\colorlet{blackish}{black!70!white}%
\colorlet{greyish}{black!60!white}%
\colorlet{whiteish}{white}%
\colorlet{orangeish}{yellow!90!red}%
\colorlet{greenish}{green!16!gray}%
\colorlet{redish}{red!80!black}%

\tcbset{calbackground/.style={
    enhanced,
    leftright skip=0.25cm,beforeafter skip=0pt,
    toptitle=0mm,bottomtitle=0mm,
    right=2mm,left=2mm,
    top=1pt,
    bottom=0.25cm,
    boxsep=0pt,
    boxrule=0mm,
    sharp corners,
    sidebyside,
    sidebyside gap=2mm,
    lefthand ratio=0.6,
    bicolor,
    colback=black!10!white,
    colbacklower=greenish,
    colframe=white,
    autoparskip,
  }}%

\newtcbox{\KY}[1][]{
  enhanced,
  on line,
  arc=2pt,outer arc=2pt,
  boxrule=0pt,bottomrule=0.25mm,rightrule=0.2mm,
  boxsep=0pt,left=0pt,right=0pt,top=1pt,bottom=1pt,
  interior style={top color=blackish,bottom color=blackened},
  colframe=greyish,
  width=2.5em,
  tcbox width=forced center,
  equal height group=K,
  valign=center,
  fontupper=\footnotesize\sffamily,
  coltext=orangeish,
  before upper=\vrule width 0pt height 2ex depth 1ex\relax,
}%

\newtcbox{\KYm}[1][]{
  enhanced,
  on line,
  arc=2pt,outer arc=2pt,
  boxrule=0pt,bottomrule=0.25mm,rightrule=0.2mm,
  boxsep=0pt,left=0pt,right=0pt,top=1pt,bottom=1pt,
  interior style={top color=blackish,bottom color=blackened},
  colframe=greyish,
  width=2.5em,
  tcbox width=forced center,
  equal height group=K,
  valign=center,
  fontupper=\footnotesize\sffamily,
  coltext=orangeish,
  before upper=\vrule width 0pt height 2ex depth 1ex\relax$,
  after upper=$,
}%

\newtcbox{\KN}{
  enhanced,
  on line,
  arc=2pt,outer arc=2pt,
  boxrule=0pt,bottomrule=0.25mm,rightrule=0.2mm,
  boxsep=0pt,left=0pt,right=0pt,top=1pt,bottom=1pt,
  interior style={top color=blackish,bottom color=blackened},
  colframe=greyish,
  width=1.5em,
  tcbox width=forced center,
  equal height group=K,
  valign=center,
  fontupper=\footnotesize\sffamily,
  coltext=whiteish,
  before upper=\vrule width 0pt height 2ex depth 1ex\relax,
}%

\newtcolorbox{calc}[1][]{%
  enhanced,bicolor,
  boxsep=0pt,
  boxrule=0pt,
  top=6pt,bottom=0pt,left=6pt,right=0pt,
  sharp corners,
  frame empty,
  colback=black!10,
  colbacklower=greenish,
  sidebyside,
  sidebyside align=top seam,
  sidebyside gap=0pt,
  righthand width=50.7mm,
  before lower=\begin{tabular}{@{}l@{}},
  after lower=\end{tabular},
  overlay={\node[inner sep=0pt, outer sep=0pt, text height=5pt, text
    depth=1pt, text width=50.7mm, fill=greenish, anchor=north
    east, font=\sffamily\tiny\bfseries, align=flush right]
    at (frame.north east) {#1};}
}

\def\MPCalculatrice#1#2#3{
  % #1 Calcul %2 r\'eponse
  \ifluatex
  \mplibforcehmode%
  \begin{mplibcode}%
    input PfCCalculatrice;
    LCD(#1)(#2)(#3);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={input PfCCalculatrice;}]
    LCD(#1)(#2)(#3);    
  \end{mpost}
  \fi
}

\setKVdefault[ClesCalculatrice]{Ecran=false,NbLignes=0,BL=0.775}

\newcommand\Calculatrice[2][]{%
  \setstackgap{L}{\useKV[ClesCalculatrice]{BL}\baselineskip}%
  \useKVdefault[ClesCalculatrice]%
  \setKV[ClesCalculatrice]{#1}%
  \ifboolKV[ClesCalculatrice]{Ecran}{%
    \setsepchar[*]{,*/}%
    \readlist\ListeCalc{#2}%
    \MPCalculatrice{\ListeCalc[1,1]}{\ListeCalc[1,2]}{\useKV[ClesCalculatrice]{NbLignes}}%
  }{%
    \setsepchar[*]{,*/}%
    \readlist\ListeCalc{#2}%
    \foreachitem\compteur\in\ListeCalc{\xintifboolexpr{\listlen\ListeCalc[\compteurcnt]==2}{\Longstack{{\tiny\ListeCalc[\compteurcnt,1]} \KN{\ListeCalc[\compteurcnt,2]}}}{\Longstack{{\tiny\ListeCalc[\compteurcnt,2]} \KY{\ListeCalc[\compteurcnt,3]}}}%
    }%
  }%
  \setstackgap{L}{\baselineskip}%
}%

%%%
% Questions Flash
%%%
\tcbset{Expression/.style={colback=white,valign=center,left=0mm,right=0mm,top=1mm,bottom=1mm,colframe=white}}%
\tcbset{ExpressionSerie1/.style={colback=\useKV[ClesFlash]{Couleur1},left=0mm,right=0mm,top=1mm,bottom=1mm}}%
\tcbset{ExpressionSerie2/.style={colback=\useKV[ClesFlash]{Couleur2},left=0mm,right=0mm,top=1mm,bottom=1mm}}%
\tcbset{ExpressionSerie3/.style={colback=\useKV[ClesFlash]{Couleur3},left=0mm,right=0mm,top=1mm,bottom=1mm}}
\tcbset{ExpressionSerie4/.style={colback=\useKV[ClesFlash]{Couleur4},left=0mm,right=0mm,top=1mm,bottom=1mm}}
\tcbset{BoiteExpression/.style={enhanced,nobeforeafter,tcbox raise base,colback=white,right=3.5mm,left=3.5mm,halign=center,colframe=black}}
\newtcolorbox{CadreNombre}[1][]{%
  Expression,#1}

\newcommand\BoiteFlash[2][40pt]{%
  \ifx\bla#2\bla%
  \tcbox[BoiteExpression]{\hbox to#1{\phantom{A}}}%
  \else
  \tcbox[BoiteExpression]{#2}%
  \fi
}

\setKVdefault[ClesFlash]{Hauteur=0.2\textheight,Simple=false,Intrus=false,Kahout=false,Daily=false,Expression=false,Mental=false,Mesure=false,Heure=false,Decimal=false,Operation=Multiplie,Numeration=false,Evaluation=false,Pause=false,Couleur1=blue!10,Couleur2=orange!10,Couleur3=green!10,Couleur4=yellow!10,Numerique=false,Seul=false}

\newlength{\HauteurFlash}

\def\MPAfficheur#1#2#3{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=0.5u;
    draw Afficheur(#1 div10,0);
    draw Afficheur(#1 mod10,0) shifted(u*(1,0));
    draw Afficheur(10,0) shifted(u*(2,0));
    draw Afficheur(#2 div10,0) shifted(u*(3,0));
    draw Afficheur(#2 mod10,0) shifted(u*(4,0));
    draw Afficheur(10,0) shifted(u*(5,0));
    draw Afficheur(#3 div10,0) shifted(u*(6,0));
    draw Afficheur(#3 mod10,0) shifted(u*(7,0));
  \end{mplibcode}
  \else
  \begin{mpost}
    u:=0.5u;
    draw Afficheur(#1 div10,0);
    draw Afficheur(#1 mod10,0) shifted(u*(1,0));
    draw Afficheur(10,0) shifted(u*(2,0));
    draw Afficheur(#2 div10,0) shifted(u*(3,0));
    draw Afficheur(#2 mod10,0) shifted(u*(4,0));
    draw Afficheur(10,0) shifted(u*(5,0));
    draw Afficheur(#3 div10,0) shifted(u*(6,0));
    draw Afficheur(#3 mod10,0) shifted(u*(7,0));
  \end{mpost}
  \fi
}

\def\MPHorloge#1#2#3{
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
  marque_horloge=1;
  save Hor;
  picture Hor;
  path gdeaig,pteaig,trot;
  pair centrehorloge;
  centrehorloge=(0,0);
  path tourhorloge;
  tourhorloge=cercles(centrehorloge,marque_horloge*cm);
  Hor=image(
  %% dessin de l'horloge
  draw tourhorloge;
  for i=0 upto 59:
  if (i mod 5)=0:
  if (i mod 15)=0:
  draw pointarc(tourhorloge,6*i)--(pointarc(tourhorloge,6*i) shifted (7*unitvector(centrehorloge-pointarc(tourhorloge,6*i)))) withpen pencircle scaled 2bp;
  else:
  draw pointarc(tourhorloge,6*i)--(pointarc(tourhorloge,6*i) shifted (5*unitvector(centrehorloge-pointarc(tourhorloge,6*i)))) withpen pencircle scaled 1.5bp;
  fi;
  else:
  draw pointarc(tourhorloge,6*i)--(pointarc(tourhorloge,6*i) shifted (3*unitvector(centrehorloge-pointarc(tourhorloge,6*i))));
  fi;
  endfor;
  path graduhorloge;
  graduhorloge=cercles(centrehorloge,marque_horloge*cm+5*abs(unitvector(centrehorloge-pointarc(tourhorloge,0))));
  % 
  marque_p:="plein";
  pointe(centrehorloge);
  marque_p:="rien";
  %% placement des aiguilles
  gdeaig=centrehorloge--(pointarc(tourhorloge,0) shifted (7*unitvector(centrehorloge-pointarc(tourhorloge,0))));
  pteaig=centrehorloge--(pointarc(tourhorloge,0) shifted (18*unitvector(centrehorloge-pointarc(tourhorloge,0))));
  trot=centrehorloge--(pointarc(tourhorloge,0) shifted (10*unitvector(centrehorloge-pointarc(tourhorloge,0))));
  draw rotation(trot,centrehorloge,90-6*#3) withpen pencircle scaled0.4;
  draw rotation(gdeaig,centrehorloge,90-6*#2) withpen pencircle scaled1.25;
  draw rotation(pteaig,centrehorloge,90-30*(#1+#2/60)) withpen pencircle scaled 2bp;
  );
  draw Hor;
  \end{mplibcode}
\else
  \begin{mpost}[mpsettings={input PfCGeometrie;}]
    marque_horloge=1;
    save Hor;
    picture Hor;
    path gdeaig,pteaig,trot;
    pair centrehorloge;
    centrehorloge=(0,0);
    path tourhorloge;
    tourhorloge=cercles(centrehorloge,marque_horloge*cm);
    Hor=image(
    %% dessin de l'horloge
    draw tourhorloge;
    for i=0 upto 59:
    if (i mod 5)=0:
    if (i mod 15)=0:
    draw pointarc(tourhorloge,6*i)--(pointarc(tourhorloge,6*i) shifted (7*unitvector(centrehorloge-pointarc(tourhorloge,6*i)))) withpen pencircle scaled 2bp;
    else:
    draw pointarc(tourhorloge,6*i)--(pointarc(tourhorloge,6*i) shifted (5*unitvector(centrehorloge-pointarc(tourhorloge,6*i)))) withpen pencircle scaled 1.5bp;
    fi;
    else:
    draw pointarc(tourhorloge,6*i)--(pointarc(tourhorloge,6*i) shifted (3*unitvector(centrehorloge-pointarc(tourhorloge,6*i))));
    fi;
    endfor;
    path graduhorloge;
    graduhorloge=cercles(centrehorloge,marque_horloge*cm+5*abs(unitvector(centrehorloge-pointarc(tourhorloge,0))));
    %
    marque_p:="plein";
    pointe(centrehorloge);
    marque_p:="rien";
    %% placement des aiguilles
    gdeaig=centrehorloge--(pointarc(tourhorloge,0) shifted (7*unitvector(centrehorloge-pointarc(tourhorloge,0))));
    pteaig=centrehorloge--(pointarc(tourhorloge,0) shifted (18*unitvector(centrehorloge-pointarc(tourhorloge,0))));
    trot=centrehorloge--(pointarc(tourhorloge,0) shifted (10*unitvector(centrehorloge-pointarc(tourhorloge,0))));
    draw rotation(trot,centrehorloge,90-6*#3) withpen pencircle scaled0.4;
    draw rotation(gdeaig,centrehorloge,90-6*#2) withpen pencircle scaled1.25;
    draw rotation(pteaig,centrehorloge,90-30*(#1+#2/60)) withpen pencircle scaled 2bp;
    );
    draw Hor;
  \end{mpost}
  \fi
}

\newcommand\QFNumeration{%
  \begin{CadreNombre}
    {\Large LE NOMBRE DU JOUR est : }
    \tcbox[BoiteExpression]{\num{\ListeFlash[1,1]}}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie1]
      $\square$ \textbf{Le chiffre des \ListeFlash[1,2] est :}
      \tcbox[BoiteExpression]{\phantom{1500000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie2]
      $\square$ \textbf{Le chiffre \ListeFlash[1,3] repr\'esente le
        chiffre des :}
      \tcbox[BoiteExpression]{\phantom{1500000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie3]
      $\square$ \textbf{Le nombre de \ListeFlash[1,4] est :}
      \tcbox[BoiteExpression]{\phantom{1500000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie4]
      $\square$ \textbf{\ListeFlash[1,5] est le nombre des :}
      \tcbox[BoiteExpression]{\phantom{1500000}}
    \end{tcolorbox}
  \end{CadreNombre}
}

\newcommand\QFHeure{%
  \begin{CadreNombre}
    {\Large L'HEURE DU JOUR est : }\ifboolKV[ClesFlash]{Numerique}{\raisebox{-0.3cm}{\MPAfficheur{\NbHeures}{\NbMinutes}{\NbSecondes}}}{\raisebox{-0.9cm}{{\MPHorloge{\NbHeures}{\NbMinutes}{\NbSecondes}}}}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie1]
      $\square$ \textbf{\ListeFlash[1,2] :}
      \tcbox[BoiteExpression]{\phantom{1500000000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie2]
      $\square$ \textbf{\ListeFlash[1,3] :}
      \tcbox[BoiteExpression]{\phantom{1500000000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie3]
      $\square$ \textbf{\ListeFlash[1,4] :}
      \tcbox[BoiteExpression]{\phantom{\hbox to4.5em{15}}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie4]
      $\square$ \textbf{\ListeFlash[1,5] :}
      \tcbox[BoiteExpression]{\phantom{\hbox to4.5em{1500000}}}
    \end{tcolorbox}
  \end{CadreNombre}
}

\newcommand\QFMesure{%
  \begin{CadreNombre}
    {\Large LA MESURE DU JOUR est : }
    \tcbox[BoiteExpression]{\ListeFlash[1,1]}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie1]
      $\square$ \textbf{Convertis-la en \ListeFlash[1,2] :}
      \tcbox[BoiteExpression]{\phantom{1500000000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie2]
      $\square$ \textbf{Elle peut aussi s'\'ecrire \ListeFlash[1,3] }
      \tcbox[BoiteExpression]{\phantom{1500000000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie3]
      $\square$ \textbf{Ajoute-lui \ListeFlash[1,4] :}
      \tcbox[BoiteExpression]{\phantom{\hbox to5em{1500000}}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie4]
      $\square$ \textbf{Enl\`eve-lui \ListeFlash[1,5] :}
      \tcbox[BoiteExpression]{\phantom{\hbox to5em{1500000}}}
    \end{tcolorbox}
  \end{CadreNombre}
}

\tikzset{
  arrow/.style={
    draw,
    minimum height=1.25cm,
    inner sep=0.25em,
    shape=signal,
    signal from=west,
    signal to=east,
    signal pointer angle=150,
  }
}

\newcommand\QFDaily{%
  \begin{tikzpicture}%
    \begin{scope}[start chain=transition going right,node distance=-\pgflinewidth]%
      \foreach \s in {1,...,\ListeFlashlen}{%
        \xintifboolexpr{\s == 1}{%
          \node[arrow,on chain] {\Huge\bfseries\ListeFlash[\s]};%
          \ifboolKV[ClesFlash]{Pause}{\pause}{}%
        }{%
          \xintifboolexpr{\s == \ListeFlashlen}{%
            \node[arrow,on chain] {\Huge\bfseries?};%
          }{%
            \node[arrow,on chain] {\ListeFlash[\s]};%
            \ifboolKV[ClesFlash]{Pause}{\pause}{}%
          }%
        }%
      }%
    \end{scope}%
  \end{tikzpicture}%
}%

\newcommand\QFDecimal{%
  \begin{CadreNombre}
    {\Large LE NOMBRE DU JOUR est : }
    \tcbox[BoiteExpression]{\num{\ListeFlash[1,1]}}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie1]
      $\square$ \textbf{\'Ecris-le en fraction d\'ecimale :}
      \tcbox[BoiteExpression]{$\dfrac{\phantom{1000000}}{\phantom{1000000}}$}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie2]
      $\square$ \begin{tabular}{c}
        \textbf{Partie}\\
        \textbf{enti\`ere}
      \end{tabular} \textbf{: }
      \tcbox[BoiteExpression]{\phantom{100000}}\hfill%
      $\square$ \begin{tabular}{c}
        \textbf{Partie}\\
        \textbf{d\'ecimale}
      \end{tabular} \textbf{: }
      \tcbox[BoiteExpression]{\phantom{100000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie3]
      $\square$ \textbf{\useKV[ClesFlash]{Operation}-le par
        \ListeFlash[1,2] :} \tcbox[BoiteExpression]{\phantom{1000000000}}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie4]
      $\square$ \textbf{Trouve le nombre entier le plus proche :} \tcbox[BoiteExpression]{\phantom{10000000}}
    \end{tcolorbox}
  \end{CadreNombre}
}

\newcommand\QFMental{%
  \begin{CadreNombre}
    {\Large LE NOMBRE DU JOUR est : }
    \tcbox[BoiteExpression]{\ListeFlash[1,1]}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie1]
      $\square$ \textbf{Ajoute-lui}
      \tcbox[BoiteExpression]{\ListeFlash[1,2]}\hfill$\square$
      \textbf{Soustrais-lui} \tcbox[BoiteExpression]{\ListeFlash[1,3]}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie2]
      $\square$ \textbf{Multiplie-le par }
      \tcbox[BoiteExpression]{\ListeFlash[1,4]}\hfill$\square$
      \textbf{Divise-le par } \tcbox[BoiteExpression]{\ListeFlash[1,5]}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie3]
      $\square$ \textbf{Trouve}
      \tcbox[BoiteExpression]{\ListeFlash[1,6]}
      \textbf{\% de ce nombre.}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie4]
      $\square$ \textbf{Trouve } \tcbox[BoiteExpression]{\ListeFlash[1,7]}
      \textbf{de ce nombre.}
    \end{tcolorbox}
  \end{CadreNombre}
}

\newcommand\QFExpression{%
  \begin{CadreNombre}
    {\Large L'EXPRESSION DU JOUR est : }
    \tcbox[BoiteExpression]{\ListeFlash[1,1]}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie1]
      $\square$ \textbf{Ajoute-lui}
      \tcbox[BoiteExpression]{\ListeFlash[1,2]}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie2]
      $\square$ \textbf{Soustrais-lui}
      \tcbox[BoiteExpression]{\ListeFlash[1,3]}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie3]
      $\square$ \textbf{Multiplie-la par}
      \tcbox[BoiteExpression]{\ListeFlash[1,4]}
    \end{tcolorbox}
    \ifboolKV[ClesFlash]{Pause}{\pause}{}
    \begin{tcolorbox}[ExpressionSerie4]
      $\square$ \textbf{\'Evalue-la lorsque} \tcbox[BoiteExpression]{\ListeFlash[1,5]}
    \end{tcolorbox}
  \end{CadreNombre}
}



\newcommand\QFVide{%
  \begin{CadreNombre}
    {\ListeFlash[1]}
    \xintFor* ##1 in {\xintSeq {1}{\ListeFlashlen-1}}\do{%
      \ifboolKV[ClesFlash]{Pause}{\pause}{}
      \begin{tcolorbox}[ExpressionSerie##1]
        \ListeFlash[1+##1]
      \end{tcolorbox}
    }
  \end{CadreNombre}
}

\newcommand\QFlash[2][]{%
  \useKVdefault[ClesFlash]%
  \setKV[ClesFlash]{#1}%
  \setlength{\HauteurFlash}{\useKV[ClesFlash]{Hauteur}}%
  \colorlet{CouleurUn}{\useKV[ClesFlash]{Couleur1}}%
  \colorlet{CouleurDeux}{\useKV[ClesFlash]{Couleur2}}%
  \colorlet{CouleurTrois}{\useKV[ClesFlash]{Couleur3}}%
  \colorlet{CouleurQuatre}{\useKV[ClesFlash]{Couleur4}}%
  \ifboolKV[ClesFlash]{Evaluation}{%
    \ifboolKV[ClesFlash]{Seul}{%
      \setsepchar[*]{/}%
      \readlist*\ListeFlash{#2}%
      \QFVide%
    }{%
      \ifboolKV[ClesFlash]{Numeration}{%
        \setsepchar[*]{,*/}%
        \readlist*\ListeFlash{#2}%
        \QFNumeration%
      }{%
        \ifboolKV[ClesFlash]{Heure}{%
          \setsepchar[*]{,*/}%
          \readlist*\ListeFlash{#2}%
          \StrMid{\ListeFlash[1,1]}{1}{2}[\NbHeures]%
          \StrMid{\ListeFlash[1,1]}{3}{4}[\NbMinutes]%
          \StrMid{\ListeFlash[1,1]}{5}{6}[\NbSecondes]%
          \QFHeure%
        }{%
          \ifboolKV[ClesFlash]{Mesure}{%
            \setsepchar[*]{,*/}%
            \readlist*\ListeFlash{#2}%
            \QFMesure%
          }{%
            \ifboolKV[ClesFlash]{Daily}{%
              \setsepchar[*]{/}%
              \readlist*\ListeFlash{#2}%
              \QFDaily%
            }{%
              \ifboolKV[ClesFlash]{Decimal}{%
                \setsepchar[*]{,*/}%
                \readlist*\ListeFlash{#2}%
                \QFDecimal%
              }{%
                \ifboolKV[ClesFlash]{Mental}{%
                  \setsepchar[*]{,*/}%
                  \readlist*\ListeFlash{#2}%
                  \QFMental%
                }{%
                  \ifboolKV[ClesFlash]{Expression}{%
                    \setsepchar[*]{,*/}%
                    \readlist*\ListeFlash{#2}%
                    \QFExpression%
                  }{%
                    \setsepchar[*]{/}%
                    \readlist*\ListeFlash{#2}%
                    \ifboolKV[ClesFlash]{Simple}{%
                      \ListeFlash[1]
                      \begin{tcolorbox}[valign=center]
                        \ListeFlash[2]
                      \end{tcolorbox}
                    }{%
                      \setsepchar[*]{*/}%
                      \readlist*\ListeFlash{#2}%
                      \ifboolKV[ClesFlash]{Kahout}{%
                        \setsepchar[*]{*/}%
                        \readlist*\ListeFlash{#2}%
                        \begin{tcolorbox}[halign=center,valign=center]
                          \ListeFlash[1,1]
                        \end{tcolorbox}
                        % \par
                        \begin{multicols}{4}
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurUn!150,colback=CouleurUn,halign=center,valign=center]
                            \ListeFlash[1,2]
                          \end{tcolorbox}
                          % \hfill%
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurDeux!150,colback=CouleurDeux,halign=center,valign=center]
                            \ListeFlash[1,3]
                          \end{tcolorbox}
                          % \hfill%
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurTrois!150,colback=CouleurTrois,halign=center,valign=center]
                            \ListeFlash[1,4]
                          \end{tcolorbox}
                          % \hfill%
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurQuatre!150,colback=CouleurQuatre,halign=center,valign=center]
                            \ListeFlash[1,5]
                          \end{tcolorbox}
                        \end{multicols}
                      }{%
                        \setsepchar[*]{*/}%
                        \readlist*\ListeFlash{#2}%
                        \begin{tcolorbox}[halign=center,valign=center]
                          \ListeFlash[1,1]
                        \end{tcolorbox}
                        \begin{multicols}{4}
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurUn!150,colback=white,boxrule=1mm,halign=center,valign=center]
                            \ListeFlash[1,2]
                          \end{tcolorbox}
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurDeux!150,colback=white,boxrule=1mm,halign=center,valign=center]
                            \ListeFlash[1,3]
                          \end{tcolorbox}
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurTrois!150,boxrule=1mm,colback=white,halign=center,valign=center]
                            \ListeFlash[1,4]
                          \end{tcolorbox}
                          \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurQuatre!150,colback=white,boxrule=1mm,halign=center,valign=center]
                            \ListeFlash[1,5]
                          \end{tcolorbox}
                        \end{multicols}
                      }%
                    }%
                  }%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }{%
    \ifboolKV[ClesFlash]{Seul}{%
      \setsepchar[*]{/}%
      \readlist*\ListeFlash{#2}%
      \begin{frame}
        \QFVide%
      \end{frame}
    }{%
      \ifboolKV[ClesFlash]{Numeration}{%
        \setsepchar[*]{,*/}%
        \readlist*\ListeFlash{#2}%
        \begin{frame}
          \QFNumeration%
        \end{frame}
      }{%
        \ifboolKV[ClesFlash]{Heure}{%
          \setsepchar[*]{,*/}%
          \readlist*\ListeFlash{#2}%
          \StrMid{\ListeFlash[1,1]}{1}{2}[\NbHeures]%
          \StrMid{\ListeFlash[1,1]}{3}{4}[\NbMinutes]%
          \StrMid{\ListeFlash[1,1]}{5}{6}[\NbSecondes]%
          \begin{frame}
            \QFHeure%
          \end{frame}
        }{%
          \ifboolKV[ClesFlash]{Mesure}{%
            \setsepchar[*]{,*/}%
            \readlist*\ListeFlash{#2}%
            \begin{frame}
              \QFMesure%
            \end{frame}
          }{%
            \ifboolKV[ClesFlash]{Daily}{%
              \setsepchar[*]{/}%
              \readlist*\ListeFlash{#2}%
              \begin{frame}
                \QFDaily%
              \end{frame}
            }{%
              \ifboolKV[ClesFlash]{Decimal}{%
                \setsepchar[*]{,*/}%
                \readlist*\ListeFlash{#2}%
                \begin{frame}
                  \QFDecimal%
                \end{frame}
              }{%
                \ifboolKV[ClesFlash]{Mental}{%
                  \setsepchar[*]{,*/}%
                  \readlist*\ListeFlash{#2}%
                  \begin{frame}
                    \QFMental%
                  \end{frame}
                }{%
                  \ifboolKV[ClesFlash]{Expression}{%
                    \setsepchar[*]{,*/}%
                    \readlist*\ListeFlash{#2}%
                    \begin{frame}
                      \QFExpression%
                    \end{frame}
                  }{%
                    \setsepchar[*]{/}%
                    \readlist*\ListeFlash{#2}%
                    \ifboolKV[ClesFlash]{Simple}{%
                      \begin{frame}
                        \ListeFlash[1]
                        \begin{tcolorbox}[valign=center]
                          \ListeFlash[2]
                        \end{tcolorbox}
                      \end{frame}
                    }{%
                      \setsepchar[*]{,*/}%
                      \readlist*\ListeFlash{#2}%
                      \ifboolKV[ClesFlash]{Kahout}{%
                        \setsepchar[*]{*/}%
                        \readlist*\ListeFlash{#2}%
                        \begin{frame}
                          \begin{tcolorbox}[valign=center]
                            \ListeFlash[1,1]
                          \end{tcolorbox}
                          \vfill
                          \ifboolKV[ClesFlash]{Pause}{\pause}{}
                          \begin{columns}[T]
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurUn!150,colback=CouleurUn,halign=center,valign=center]
                                \ListeFlash[1,2]
                              \end{tcolorbox}
                            \end{column}
                            \ifboolKV[ClesFlash]{Pause}{\pause}{}
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurDeux!150,colback=CouleurDeux,halign=center,valign=center]
                                \ListeFlash[1,3]
                              \end{tcolorbox}
                            \end{column}
                          \end{columns}
                          \bigskip
                          \ifboolKV[ClesFlash]{Pause}{\pause}{}
                          \begin{columns}[T]
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurTrois!150,colback=CouleurTrois,halign=center,valign=center]
                                \ListeFlash[1,4]
                              \end{tcolorbox}
                            \end{column}
                            \ifboolKV[ClesFlash]{Pause}{\pause}{}
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurQuatre!150,colback=CouleurQuatre,halign=center,valign=center]
                                \ListeFlash[1,5]
                              \end{tcolorbox}
                            \end{column}
                          \end{columns}
                        \end{frame}
                      }{%
                        \setsepchar[*]{*/}%
                        \readlist*\ListeFlash{#2}%
                        \begin{frame}
                          \begin{tcolorbox}[valign=center]
                            \ListeFlash[1,1]
                          \end{tcolorbox}
                          \vfill
                          \ifboolKV[ClesFlash]{Pause}{\pause}{}
                          \begin{columns}[T]
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurUn!150,colback=white,boxrule=1mm,halign=center,valign=center]
                                \ListeFlash[1,2]
                              \end{tcolorbox}
                            \end{column}
                            \ifboolKV[ClesFlash]{Pause}{\pause}{}
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurDeux!150,colback=white,boxrule=1mm,halign=center,valign=center]
                                \ListeFlash[1,3]
                              \end{tcolorbox}
                            \end{column}
                          \end{columns}
                          \bigskip
                          \ifboolKV[ClesFlash]{Pause}{\pause}{}
                          \begin{columns}[T]
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurTrois!150,boxrule=1mm,colback=white,halign=center,valign=center]
                                \ListeFlash[1,4]
                              \end{tcolorbox}
                            \end{column}
                            \ifboolKV[ClesFlash]{Pause}{\pause}{}
                            \begin{column}{0.45\linewidth}
                              \begin{tcolorbox}[height=\HauteurFlash,colframe=CouleurQuatre!150,colback=white,boxrule=1mm,halign=center,valign=center]
                                \ListeFlash[1,5]
                              \end{tcolorbox}
                            \end{column}
                          \end{columns}
                        \end{frame}
                      }%
                    }%
                  }%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

%%%
% Rapido
%%%
%% D'après https://www.facebook.com/groups/994675223903586/user/100017057226847
%% et une programmation de Laurent Lassale-Carrere
\newcounter{PfCnexo}
\newtcolorbox[use counter=PfCnexo,number format=\arabic]{RapidoBox}{%
  % Titre
  colbacktitle=white,
  fonttitle=\color{black}\Large\bfseries,
  toptitle=1mm,
  bottomtitle=1mm,
  bottom=1mm,
  title={\useKV[ClesRapido]{Titre}},
  %% Cadre principal
  enhanced,
  width=\WidthRapido,
  colback=white,
  valign=top,
  drop lifted shadow
}
\newtcolorbox{QuestionBox}{enhanced,nobeforeafter,size=small,sidebyside adapt=left}
\newtcolorbox{QuestionReponse}{enhanced,nobeforeafter,upperbox=invisible,colback=white,width=1.5cm,grow to left by=3mm,grow to right by=3mm,height=10mm}

\setKVdefault[ClesRapido]{Debut=false,Largeur=0.9\linewidth,Titre={Rapido n°\thetcbcounter\hfill Date :\hspace*{2.5cm}}}%
\defKV[ClesRapido]{Numero=\setKV[ClesRapido]{Debut=true}}

\newlength{\WidthRapido}

\newcommand\Rapido[2][]{% numéro
\useKVdefault[ClesRapido]%
\setKV[ClesRapido]{#1}%
%
\ifboolKV[ClesRapido]{Debut}{%
  \setcounter{PfCnexo}{\fpeval{\useKV[ClesRapido]{Numero}-1}}
}{}%
\setlength{\WidthRapido}{\useKV[ClesRapido]{Largeur}}%
%
\setsepchar[*]{§*/}%
\readlist*\ListeRapido{#2}%
\begin{RapidoBox}
  \xintFor* ##1 in {\xintSeq {1}{\ListeRapidolen}}\do{%
    \tcbsidebyside[%
    sidebyside adapt=right,
    bicolor,
    colback=white,colbacklower=yellow!10!white,
    nobeforeafter,
    top=0mm,left=1mm,
    grow to left by=3mm,
    grow to right by=3mm,
    bottom=0mm
    ]{%
      \ListeRapido[##1,1]
    }{%
      \ListeRapido[##1,2]
    }
  }%
\end{RapidoBox}
}%

\newcommand\BoiteRapido[1]{%
  \ifx\bla#1\bla%
  \tcbox[BoiteExpression]{\phantom{100000}}%
  \else%
  \tcbox[BoiteExpression]{#1}%
  \fi
}%

%%%
% Fractions
%%%
\setKVdefault[ClesFraction]{Rayon=2cm,Disque,Regulier=false,Segment=false,Rectangle=false,Longueur=5cm,Largeur=2cm,Cotes=5,Triangle=false,Parts=3,Couleur=green,Reponse=false,Multiple=1,Hachures=false,Epaisseur=1}

\def\MPFractionTriangle#1#2#3#4#5{%
  % #1 longueur du c\^ot\'e
  % #2 partage sur le c\^ot\'e
  % #3 num
  % #4 d\'eno (attention : = #2^2)
  % #5 couleur
  \ifluatex
   \mplibforcehmode
   \begin{mplibcode}
     nbtriangle=0;

     vardef Ligne(expr longueur)=
     for k=0 upto 2*(longueur-1):
     nbtriangle:=nbtriangle+1;
     if (k mod 2)=0:
     M[nbtriangle]=(Tria shifted(0.5*k*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     else:
     M[nbtriangle]=(Trir shifted(0.5*(k-1)*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     fi;
     endfor;
     enddef;

     pair A,B,C;
     A=u*(0.5,0.5);
     B-A=(#1,0);
     C=rotation(B,A,60);

     nbparts:=#2;

     path M[];

     path Tria,Trir;
     Tria=polygone(A,(1/nbparts)[A,B],(1/nbparts)[A,C]);
     Trir=symetrie(Tria,(1/nbparts)[A,B],(1/nbparts)[A,C]);

     for k=nbparts downto 1:
     Ligne(k);
     endfor;
     
     m:=#3 div #4;

     drawoptions(shifted(m*(#1+1cm,0)));
     for l=1 upto (#3 mod #4):
     fill M[l] withcolor #5;
     for k=1 upto nbparts:
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]);
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]);
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]);
     endfor;
     endfor;
     
     for l=0 upto (m-1):
     drawoptions(shifted(l*(#1+1cm,0)));
     remplis polygone(A,B,C) withcolor #5;
     for k=1 upto nbparts:
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]);
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]);
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]);
     endfor;
     endfor;
   \end{mplibcode}
     \else
     \begin{mpost}
            nbtriangle=0;

     vardef Ligne(expr longueur)=
     for k=0 upto 2*(longueur-1):
     nbtriangle:=nbtriangle+1;
     if (k mod 2)=0:
     M[nbtriangle]=(Tria shifted(0.5*k*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     else:
     M[nbtriangle]=(Trir shifted(0.5*(k-1)*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     fi;
     endfor;
     enddef;

     pair A,B,C;
     A=u*(0.5,0.5);
     B-A=(#1,0);
     C=rotation(B,A,60);

     nbparts:=#2;

     path M[];

     path Tria,Trir;
     Tria=polygone(A,(1/nbparts)[A,B],(1/nbparts)[A,C]);
     Trir=symetrie(Tria,(1/nbparts)[A,B],(1/nbparts)[A,C]);

     for k=nbparts downto 1:
     Ligne(k);
     endfor;
     
     m:=#3 div #4;

     drawoptions(shifted(m*(#1+1cm,0)));
     for l=1 upto (#3 mod #4):
     fill M[l] withcolor #5;
     for k=1 upto nbparts:
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]);
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]);
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]);
     endfor;
     endfor;
     
     for l=0 upto (m-1):
     drawoptions(shifted(l*(#1+1cm,0)));
     remplis polygone(A,B,C) withcolor #5;
     for k=1 upto nbparts:
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]);
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]);
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]);
     endfor;
     endfor;
     \end{mpost}
   \fi
 }

 \def\MPFractionTriangleH#1#2#3#4#5#6{
  % #1 longueur du c\^ot\'e
  % #2 partage sur le c\^ot\'e
  % #3 num
  % #4 d\'eno (attention : = #2^2)
  % #5 couleur
  % #6 \'epaisseur
  \ifluatex
   \mplibforcehmode
   \begin{mplibcode}
          nbtriangle=0;

     vardef Ligne(expr longueur)=
     for k=0 upto 2*(longueur-1):
     nbtriangle:=nbtriangle+1;
     if (k mod 2)=0:
     M[nbtriangle]=(Tria shifted(0.5*k*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     else:
     M[nbtriangle]=(Trir shifted(0.5*(k-1)*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     fi;
     endfor;
     enddef;

     pair A,B,C;
     A=u*(0.5,0.5);
     B-A=(#1,0);
     C=rotation(B,A,60);

     nbparts:=#2;

     path M[];

     path Tria,Trir;
     Tria=polygone(A,(1/nbparts)[A,B],(1/nbparts)[A,C]);
     Trir=symetrie(Tria,(1/nbparts)[A,B],(1/nbparts)[A,C]);

     for k=nbparts downto 1:
     Ligne(k);
     endfor;
     
     m:=#3 div #4;

     for l=1 upto (#3 mod #4):
     drawoptions(withpen pencircle scaled #6);
     trace hachurage(M[l] shifted(m*(#1+1cm,0)),90,0.2,0) withcolor #5;%M[l] withcolor #5;
     for k=1 upto nbparts:
     drawoptions(withpen pencircle scaled #6);
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]) shifted(m*(#1+1cm,0));
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]) shifted(m*(#1+1cm,0));
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]) shifted(m*(#1+1cm,0));
     endfor;
     endfor;
     
     for l=0 upto (m-1):
     drawoptions(shifted(l*(#1+1cm,0)) withpen pencircle scaled #6);
     trace hachurage(polygone(A,B,C),90,0.2,0) withcolor #5;%polygone(A,B,C) withcolor #5;
          drawoptions(shifted(l*(#1+1cm,0)) withpen pencircle scaled #6);
     for k=1 upto nbparts:
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]);
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]);
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]);
     endfor;
     endfor;
   \end{mplibcode}
     \else
     \begin{mpost}
       nbtriangle=0;

     vardef Ligne(expr longueur)=
     for k=0 upto 2*(longueur-1):
     nbtriangle:=nbtriangle+1;
     if (k mod 2)=0:
     M[nbtriangle]=(Tria shifted(0.5*k*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     else:
     M[nbtriangle]=(Trir shifted(0.5*(k-1)*(1/nbparts)*(B-A)))  shifted((nbparts-longueur)*(1/nbparts)*(C-A));
     fi;
     endfor;
     enddef;

     pair A,B,C;
     A=u*(0.5,0.5);
     B-A=(#1,0);
     C=rotation(B,A,60);

     nbparts:=#2;

     path M[];

     path Tria,Trir;
     Tria=polygone(A,(1/nbparts)[A,B],(1/nbparts)[A,C]);
     Trir=symetrie(Tria,(1/nbparts)[A,B],(1/nbparts)[A,C]);

     for k=nbparts downto 1:
     Ligne(k);
     endfor;

     diversite=floor(uniformdeviate(#2**2-#3-1));
     
     for k=(1+diversite) upto (#3+diversite):
     drawoptions(withpen pencircle scaled #6);
     trace hachurage(M[k],90,0.2,0) withcolor #5;
     endfor;
     drawoptions(withpen pencircle scaled #6);
     
     for k=1 upto nbparts:
     trace segment((k/nbparts)[A,B],(k/nbparts)[A,C]);
     trace segment((k/nbparts)[B,A],(k/nbparts)[B,C]);
     trace segment((k/nbparts)[C,A],(k/nbparts)[C,B]);
     endfor;
     \end{mpost}
   \fi
 }

\def\MPFractionRegulier#1#2#3#4#5{%
  % #1 rayon, #2 nb c\^ot\'es, #3 num, #4 deno, #5 couleur
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair O,A[],B[];
    O=u*(0,0);
    path cc,cd;
    cc=cercles(O,#1);
    for k=0 upto #2:
    A[k]=pointarc(cc,k*(360/#2));
    endfor;
    cd=polygone(A0 for k=1 upto #2-1:,A[k] endfor);
    for k=0 upto #4-1:
    B[k]=point(k*(#2/#4)) of cd;
    endfor;
    picture fondcolore;
    fondcolore=image(
    remplis O--arccercle(B[0],B[#3 mod #4],O)--cycle withcolor #5;
    clip currentpicture to cd;
    for k=0 upto #4-1:
    draw segment(O,B[k]) cutafter cd;
    endfor;
    trace cd;
    );
    currentpicture:=nullpicture;
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    fill cd shifted(l*(#1*2+0.5cm,0)) withcolor #5;
    trace cd shifted(l*(#1*2+0.5cm,0));
    if #4>1:
    for k=0 upto #4-1:
    draw (segment(O,B[k]) cutafter cd) shifted(l*(#1*2+0.5cm,0));
    endfor;
    fi;
    endfor;
    fi;
    draw fondcolore shifted(m*(#1*2+0.5cm,0));
    draw cd shifted(m*(#1*2+0.5cm,0));
    if #4>1:
    for k=0 upto #4-1:
    draw (segment(O,B[k]) cutafter cd) shifted(m*(#1*2+0.5cm,0));
    endfor;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}
        pair O,A[],B[];
    O=u*(0,0);
    path cc,cd;
    cc=cercles(O,#1);
    for k=0 upto #2:
    A[k]=pointarc(cc,k*(360/#2));
    endfor;
    cd=polygone(A0 for k=1 upto #2-1:,A[k] endfor);
    for k=0 upto #4-1:
    B[k]=point(k*(#2/#4)) of cd;
    endfor;
    picture fondcolore;
    fondcolore=image(
    remplis O--arccercle(B[0],B[#3 mod #4],O)--cycle withcolor #5;
    clip currentpicture to cd;
    for k=0 upto #4-1:
    draw segment(O,B[k]) cutafter cd;
    endfor;
    trace cd;
    );
    currentpicture:=nullpicture;
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    fill cd shifted(l*(#1*2+0.5cm,0)) withcolor #5;
    trace cd shifted(l*(#1*2+0.5cm,0));
    if #4>1:
    for k=0 upto #4-1:
    draw (segment(O,B[k]) cutafter cd) shifted(l*(#1*2+0.5cm,0));
    endfor;
    fi;
    endfor;
    fi;
    draw fondcolore shifted(m*(#1*2+0.5cm,0));
    draw cd shifted(m*(#1*2+0.5cm,0));
    if #4>1:
    for k=0 upto #4-1:
    draw (segment(O,B[k]) cutafter cd) shifted(m*(#1*2+0.5cm,0));
    endfor;
    fi;
  \end{mpost}
  \fi
}

\def\MPFractionRegulierH#1#2#3#4#5#6{%
  % #1 rayon, #2 nb c\^ot\'es, #3 num, #4 deno, #5 couleur, #6 épaisseur
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair O,A[],B[];
    O=u*(0,0);
    path cc,cd;
    cc=cercles(O,#1);
    for k=0 upto #2:
    A[k]=pointarc(cc,k*(360/#2));
    endfor;
    cd=polygone(A0 for k=1 upto #2-1:,A[k] endfor);
    for k=0 upto #4-1:
    B[k]=point(k*(#2/#4)) of cd;
    endfor;
    picture fondcolore;
    fondcolore=image(%
    drawoptions(withpen pencircle scaled #6);
    trace hachurage(O--arccercle(B[0],B[#3 mod #4],O)--cycle,1.5*360/#2,0.25,0) withcolor #5;
    clip currentpicture to cd;
    drawoptions(withpen pencircle scaled #6);
    for k=0 upto #4-1:
    draw segment(O,B[k]) cutafter cd;
    endfor;
    trace cd;
    );
    currentpicture:=nullpicture;
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    drawoptions(withpen pencircle scaled #6);
    trace hachurage(cd shifted(l*(#1*2+0.5cm,0)),1.5*360/#2,0.25,0) withcolor #5;
    drawoptions(withpen pencircle scaled #6);
    trace cd shifted(l*(#1*2+0.5cm,0));
    if #4>1:
    for k=0 upto #4-1:
    drawoptions(withpen pencircle scaled #6);
    draw (segment(O,B[k]) cutafter cd) shifted(l*(#1*2+0.5cm,0));
    endfor;
    fi;
    endfor;
    fi;
    draw fondcolore shifted(m*(#1*2+0.5cm,0));
    drawoptions(withpen pencircle scaled #6);
    draw cd shifted(m*(#1*2+0.5cm,0));
    if #4>1:
    drawoptions(withpen pencircle scaled #6);
    for k=0 upto #4-1:
    draw (segment(O,B[k]) cutafter cd) shifted(m*(#1*2+0.5cm,0));
    endfor;
    fi;
  \end{mplibcode}
  \else
\begin{mpost}
    pair O,A[],B[];
    O=u*(0,0);
    path cc,cd;
    cc=cercles(O,#1);
    for k=0 upto #2:
    A[k]=pointarc(cc,k*(360/#2));
    endfor;
    cd=polygone(A0 for k=1 upto #2-1:,A[k] endfor);
    for k=0 upto #4-1:
    B[k]=point(k*(#2/#4)) of cd;
    endfor;
    picture fondcolore;
    fondcolore=image(%
    drawoptions(withpen pencircle scaled #6);
    trace hachurage(O--arccercle(B[0],B[#3 mod #4],O)--cycle,1.5*360/#2,0.25,0) withcolor #5;
    clip currentpicture to cd;
    drawoptions(withpen pencircle scaled #6);
    for k=0 upto #4-1:
    draw segment(O,B[k]) cutafter cd;
    endfor;
    trace cd;
    );
    currentpicture:=nullpicture;
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    drawoptions(withpen pencircle scaled #6);
    trace hachurage(cd shifted(l*(#1*2+0.5cm,0)),1.5*360/#2,0.25,0) withcolor #5;
    drawoptions(withpen pencircle scaled #6);
    trace cd shifted(l*(#1*2+0.5cm,0));
    if #4>1:
    for k=0 upto #4-1:
    drawoptions(withpen pencircle scaled #6);
    draw (segment(O,B[k]) cutafter cd) shifted(l*(#1*2+0.5cm,0));
    endfor;
    fi;
    endfor;
    fi;
    draw fondcolore shifted(m*(#1*2+0.5cm,0));
    drawoptions(withpen pencircle scaled #6);
    draw cd shifted(m*(#1*2+0.5cm,0));
    if #4>1:
    drawoptions(withpen pencircle scaled #6);
    for k=0 upto #4-1:
    draw (segment(O,B[k]) cutafter cd) shifted(m*(#1*2+0.5cm,0));
    endfor;
    fi;
  \end{mpost}
  \fi
}

\def\MPFractionRectangle#1#2#3#4#5#6{%
  % #1 longueur, #2 largeur, #3 num, #4 deno, #5 couleur, #6 multiple
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair A,B,C,D,M[],N[],R[],S[];
    A=(1,1);
    B-A=(#1,0);
    C-B=(0,#2);
    D-C=A-B;
    numeric parts;
    parts=(#4 div #6);
    for k=0 upto parts:
    M[k]=(k/parts)[A,B];
    N[k]=(k/parts)[D,C];
    endfor;
    if #6>1:
    for k=0 upto #6:
    R[k]=(k/#6)[A,D];
    S[k]=(k/#6)[B,C];
    endfor;
    fi;
    picture FondRectangle;
    FondRectangle=image(%
    draw polygone(A,B,C,D);
    for k=1 upto (parts-1):
    draw segment(M[k],N[k]);
    endfor;
    if #6>1:
    for k=1 upto (#6-1):
    draw segment(R[k],S[k]);
    endfor;
    fi;
    );
    picture FondRectangleColorie;
    FondRectangleColorie=image(%
    if #6=1:
    remplis polygone(A,M[#3 mod #4],N[#3 mod #4],D) withcolor #5;
    else:
    DDiv=(#3 mod #4) div parts;
    MMod=(#3 mod #4) mod parts;
    remplis polygone(A,B,S[DDiv],R[DDiv]) withcolor #5;
    remplis polygone(R[DDiv],(xpart(M[MMod]),ypart(R[DDiv])),(xpart(M[MMod]),ypart(R[DDiv+1])),R[DDiv+1]) withcolor #5;
    fi;
    );    
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto m-1:
    remplis (polygone(A,B,C,D) shifted(l*(#1+1cm,0))) withcolor #5;
    trace FondRectangle shifted(l*(#1+1cm,0));
    endfor;
    fi;
    if (#3 mod #4)<>0:
    trace FondRectangleColorie shifted(m*(#1+1cm,0));
    else:
    remplis (polygone(A,B,C,D) shifted(m*(#1+1cm,0))) withcolor #5;
    fi;
    trace FondRectangle shifted(m*(#1+1cm,0));
  \end{mplibcode}
  \else
\begin{mpost}
      pair A,B,C,D,M[],N[],R[],S[];
    A=(1,1);
    B-A=(#1,0);
    C-B=(0,#2);
    D-C=A-B;
    numeric parts;
    parts=(#4 div #6);
    for k=0 upto parts:
    M[k]=(k/parts)[A,B];
    N[k]=(k/parts)[D,C];
    endfor;
    if #6>1:
    for k=0 upto #6:
    R[k]=(k/#6)[A,D];
    S[k]=(k/#6)[B,C];
    endfor;
    fi;
    picture FondRectangle;
    FondRectangle=image(%
    draw polygone(A,B,C,D);
    for k=1 upto (parts-1):
    draw segment(M[k],N[k]);
    endfor;
    if #6>1:
    for k=1 upto (#6-1):
    draw segment(R[k],S[k]);
    endfor;
    fi;
    );
    picture FondRectangleColorie;
    FondRectangleColorie=image(%
    if #6=1:
    remplis polygone(A,M[#3 mod #4],N[#3 mod #4],D) withcolor #5;
    else:
    DDiv=(#3 mod #4) div parts;
    MMod=(#3 mod #4) mod parts;
    remplis polygone(A,B,S[DDiv],R[DDiv]) withcolor #5;
    remplis polygone(R[DDiv],(xpart(M[MMod]),ypart(R[DDiv])),(xpart(M[MMod]),ypart(R[DDiv+1])),R[DDiv+1]) withcolor #5;
    fi;
    );    
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto m-1:
    remplis (polygone(A,B,C,D) shifted(l*(#1+1cm,0))) withcolor #5;
    trace FondRectangle shifted(l*(#1+1cm,0));
    endfor;
    fi;
    if (#3 mod #4)<>0:
    trace FondRectangleColorie shifted(m*(#1+1cm,0));
    else:
    remplis (polygone(A,B,C,D) shifted(m*(#1+1cm,0))) withcolor #5;
    fi;
    trace FondRectangle shifted(m*(#1+1cm,0));
  \end{mpost}
  \fi
}

\def\MPFractionRectangleH#1#2#3#4#5#6#7{%
  % #1 longueur, #2 largeur, #3 num, #4 deno, #5 couleur, #6 multiple
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair A,B,C,D,M[],N[],R[],S[];
    A=(1,1);
    B-A=(#1,0);
    C-B=(0,#2);
    D-C=A-B;
    numeric parts;
    parts=(#4 div #6);
    for k=0 upto parts:
    M[k]=(k/parts)[A,B];
    N[k]=(k/parts)[D,C];
    endfor;
    if #6>1:
    for k=0 upto #6:
    R[k]=(k/#6)[A,D];
    S[k]=(k/#6)[B,C];
    endfor;
    fi;
    picture FondRectangle;
    FondRectangle=image(%
    draw polygone(A,B,C,D);
    for k=1 upto (parts-1):
    draw segment(M[k],N[k]);
    endfor;
    if #6>1:
    for k=1 upto (#6-1):
    draw segment(R[k],S[k]);
    endfor;
    fi;
    );
    picture FondRectangleColorie;
    FondRectangleColorie=image(%
    if #6=1:
    drawoptions(withpen pencircle scaled#7);
    trace hachurage(polygone(A,M[#3 mod #4],N[#3 mod #4],D),45,0.25,0) withcolor #5;
    else:
    DDiv=(#3 mod #4) div parts;
    MMod=(#3 mod #4) mod parts;
    drawoptions(withpen pencircle scaled#7);
    trace hachurage(polygone(A,B,S[DDiv],R[DDiv]),45,0.25,0) withcolor #5;
        drawoptions(withpen pencircle scaled#7);
    trace hachurage(polygone(R[DDiv],(xpart(M[MMod]),ypart(R[DDiv])),(xpart(M[MMod]),ypart(R[DDiv+1])),R[DDiv+1]),45,0.25,0) withcolor #5;
    fi;
    );    
    m=#3 div #4;
    if (#3 mod #4)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto m-1:
        drawoptions(withpen pencircle scaled#7);
        trace hachurage(polygone(A,B,C,D) shifted(l*(#1+1cm,0)),45,0.25,0) withcolor #5;
            drawoptions(withpen pencircle scaled#7);
    trace FondRectangle shifted(l*(#1+1cm,0));
    endfor;
    fi;
    if (#3 mod #4)<>0:
        drawoptions(withpen pencircle scaled#7);
    trace FondRectangleColorie shifted(m*(#1+1cm,0));
    else:
        drawoptions(withpen pencircle scaled#7);
    trace hachurage(polygone(A,B,C,D) shifted(m*(#1+1cm,0)),45,0.25,0) withcolor #5;
    fi;
        drawoptions(withpen pencircle scaled#7);
    trace FondRectangle shifted(m*(#1+1cm,0));
  \end{mplibcode}
  \else
\begin{mpost}
    pair A,B,C,D,M[],N[],R[],S[];
    A=(1,1);
    B-A=(#1,0);
    C-B=(0,#2);
    D-C=A-B;
    numeric parts;
    parts=(#4 div #6);
    for k=0 upto parts:
    M[k]=(k/parts)[A,B];
    N[k]=(k/parts)[D,C];
    endfor;
    if #6>1:
    for k=0 upto #6:
    R[k]=(k/#6)[A,D];
    S[k]=(k/#6)[B,C];
    endfor;
    fi;
    if #6=1:
    drawoptions(withpen pencircle scaled#7);
    draw hachurage(polygone(A,M[#3],N[#3],D),45,0.25,0) withcolor #5;
    else:
    DDiv=#3 div parts;
    MMod=#3 mod parts;
    drawoptions(withpen pencircle scaled#7);
    draw hachurage(polygone(A,B,S[DDiv],R[DDiv]),45,0.25,0) withcolor #5;
    drawoptions(withpen pencircle scaled#7);
    draw hachurage(polygone(R[DDiv],(xpart(M[MMod]),ypart(R[DDiv])),(xpart(M[MMod]),ypart(R[DDiv+1])),R[DDiv+1]),45,0.25,0) withcolor #5;
    fi;
    drawoptions(withpen pencircle scaled#7);
    draw polygone(A,B,C,D);
    for k=1 upto (parts-1):
    draw segment(M[k],N[k]);
    endfor;
    if #6>1:
    for k=1 upto (#6-1):
    draw segment(R[k],S[k]);
    endfor;
    drawoptions();
    fi;
  \end{mpost}
  \fi
}

\def\MPFractionDisque#1#2#3#4{%
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair A,B[];
    A=(0,0);
    path cc;
    cc=cercles(A,#1);
    for k=0 upto #3:
    B[k]=pointarc(cc,(360/#3)*k);
    endfor;
    m=(#2 div #3);
    if (#2 mod #3)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    fill cc shifted(l*(2*#1+1cm,0)) withcolor #4;
    endfor;
    fi;
    fill ((A--B0--arccercle(B[0],B[#2 mod #3],A)--cycle) shifted (m*(2*#1+1cm,0))) withcolor #4;
    for l=0 upto m:
    draw cc shifted(l*(2*#1+1cm,0));
    for k=0 upto (#3-1):
    draw segment(A,B[k]) shifted(l*(2*#1+1cm,0));
    endfor;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}
    pair A,B[];
    A=(0,0);
    path cc;
    cc=cercles(A,#1);
    for k=0 upto #3:
    B[k]=pointarc(cc,(360/#3)*k);
    endfor;
    m=#2 div #3;
    if (#2 mod #3)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    fill cc shifted(l*(2*#1+1cm,0)) withcolor #4;
    endfor;
    fi;
    fill ((A--B0--arccercle(B[0],B[#2 mod #3],A)--cycle) shifted (m*(2*#1+1cm,0))) withcolor #4;
    for l=0 upto m:
    draw cc shifted(l*(2*#1+1cm,0));
    for k=0 upto (#3-1):
    draw segment(A,B[k]) shifted(l*(2*#1+1cm,0));
    endfor;
    endfor;
  \end{mpost}
  \fi
}

\def\MPFractionDisqueH#1#2#3#4#5{%
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair A,B[];
    A=(0,0);
    path cc;
    cc=cercles(A,#1);
    for k=0 upto #3:
    B[k]=pointarc(cc,(360/#3)*k);
    endfor;
    m=#2 div #3;
    if (#2 mod #3)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    drawoptions(withpen pencircle scaled#5);
    draw hachurage(cc shifted(l*(2*#1+1cm,0)),1.5*360/#3,0.25,0) withcolor #4;
    endfor;
    fi;
    drawoptions(withpen pencircle scaled#5);
    draw hachurage((A--B0--arccercle(B[0],B[#2 mod #3],A)--cycle) shifted(m*(2*#1+1cm,0)),1.5*360/#3,0.25,0) withcolor #4;
    drawoptions(withpen pencircle scaled#5);
    for l=0 upto m:
    draw cc shifted(l*(2*#1+1cm,0));
    for k=0 upto (#3-1):
    draw segment(A,B[k]) shifted(l*(2*#1+1cm,0));
    endfor;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}
    pair A,B[];
    A=(0,0);
    path cc;
    cc=cercles(A,#1);
    for k=0 upto #3:
    B[k]=pointarc(cc,(360/#3)*k);
    endfor;
    m=#2 div #3;
    if (#2 mod #3)=0:m:=m-1; fi;
    if m>0:
    for l=0 upto (m-1):
    drawoptions(withpen pencircle scaled#5);
    draw hachurage(cc shifted(l*(2*#1+1cm,0)),1.5*360/#3,0.25,0) withcolor #4;
    endfor;
    fi;
    drawoptions(withpen pencircle scaled#5);
    draw hachurage((A--B0--arccercle(B[0],B[#2 mod #3],A)--cycle) shifted(m*(2*#1+1cm,0)),1.5*360/#3,0.25,0) withcolor #4;
    drawoptions(withpen pencircle scaled#5);
    for l=0 upto m:
    draw cc shifted(l*(2*#1+1cm,0));
    for k=0 upto (#3-1):
    draw segment(A,B[k]) shifted(l*(2*#1+1cm,0));
    endfor;
    endfor;
  \end{mpost}
  \fi
}

\def\MPFractionSegment#1#2#3#4{
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair A,C,B[];
    A=(0,0);
    C-A=(#1,0);
    for k=0 upto #3:
    B[k]=(k/#3)[A,C];
    endfor;
    m=#2 div #3;
    if m>0:
    for l=0 upto (m-1):
    draw (segment(B[0],B[#3]) shifted(l*(#1+1cm,0))) withpen pencircle scaled 2 withcolor #4;
    endfor;
    fi;
    if (#2 mod #3)<>0:
    draw (segment(B[0],B[#2 mod #3]) shifted(m*(#1+1cm,0))) withpen pencircle scaled 2 withcolor #4;
    draw segment(A,C) shifted(m*(#1+1cm,0));
    fi;
    marque_p:="tiretv";
    for l=0 upto m-1:
    for k=0 upto #3:
    pointe(B[k] shifted(l*(#1+1cm,0)));
    endfor;
    endfor;
    if (#2 mod #3)<>0:
    for k=0 upto #3:
    pointe(B[k] shifted(m*(#1+1cm,0)));
    endfor;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}
        pair A,C,B[];
    A=(0,0);
    C-A=(#1,0);
    for k=0 upto #3:
    B[k]=(k/#3)[A,C];
    endfor;
    m=#2 div #3;
    if m>0:
    for l=0 upto (m-1):
    draw (segment(B[0],B[#3]) shifted(l*(#1+1cm,0))) withpen pencircle scaled 2 withcolor #4;
    endfor;
    fi;
    if (#2 mod #3)<>0:
    draw (segment(B[0],B[#2 mod #3]) shifted(m*(#1+1cm,0))) withpen pencircle scaled 2 withcolor #4;
    draw segment(A,C) shifted(m*(#1+1cm,0));
    fi;
    marque_p:="tiretv";
    for l=0 upto m-1:
    for k=0 upto #3:
    pointe(B[k] shifted(l*(#1+1cm,0)));
    endfor;
    endfor;
    if (#2 mod #3)<>0:
    for k=0 upto #3:
    pointe(B[k] shifted(m*(#1+1cm,0)));
    endfor;
    fi;
  \end{mpost}
  \fi
}

\def\MPFractionSegmentH#1#2#3#4#5{%
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    pair A,C,B[];
    A=(0,0);
    C-A=(#1,0);
    for k=0 upto #3:
    B[k]=(k/#3)[A,C];
    endfor;
    m=#2 div #3;
    if m>0:
    for l=0 upto (m-1):
    drawoptions(withpen pencircle scaled#5);
    draw hachurage(polygone(B[0]+u*(0,-0.15),B[#3]+u*(0,-0.15),B[#3]+u*(0,0.15),B[0]+u*(0,0.15)) shifted(l*(#1+1cm,0)),120,0.2,0) withcolor #4;
    drawoptions(withpen pencircle scaled#5);
    draw segment(A,C) shifted(l*(#1+1cm,0));
    endfor;
    fi;
    if (#2 mod #3)<>0:
    drawoptions(withpen pencircle scaled#5);
    draw hachurage(polygone(B[0]+u*(0,-0.15),B[#2 mod #3]+u*(0,-0.15),B[#2 mod #3]+u*(0,0.15),B[0]+u*(0,0.15)) shifted(m*(#1+1cm,0)),120,0.2,0) withcolor #4;
            drawoptions(withpen pencircle scaled#5);
    draw segment(A,C) shifted(m*(#1+1cm,0));
    fi;
    marque_p:="tiretv";
    for l=0 upto m-1:
    for k=0 upto #3:
    pointe(B[k] shifted(l*(#1+1cm,0)));
    endfor;
    endfor;
    if (#2 mod #3)<>0:
    for k=0 upto #3:
    pointe(B[k] shifted(m*(#1+1cm,0)));
    endfor;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}
        pair A,C,B[];
    A=(0,0);
    C-A=(#1,0);
    for k=0 upto #3:
    B[k]=(k/#3)[A,C];
    endfor;
    m=#2 div #3;
    if m>0:
    for l=0 upto (m-1):
    drawoptions(withpen pencircle scaled#5);
    draw hachurage(polygone(B[0]+u*(0,-0.15),B[#3]+u*(0,-0.15),B[#3]+u*(0,0.15),B[0]+u*(0,0.15)) shifted(l*(#1+1cm,0)),120,0.2,0) withcolor #4;
    drawoptions(withpen pencircle scaled#5);
    draw segment(A,C) shifted(l*(#1+1cm,0));
    endfor;
    fi;
    if (#2 mod #3)<>0:
    drawoptions(withpen pencircle scaled#5);
    draw hachurage(polygone(B[0]+u*(0,-0.15),B[#2 mod #3]+u*(0,-0.15),B[#2 mod #3]+u*(0,0.15),B[0]+u*(0,0.15)) shifted(m*(#1+1cm,0)),120,0.2,0) withcolor #4;
            drawoptions(withpen pencircle scaled#5);
    draw segment(A,C) shifted(m*(#1+1cm,0));
    fi;
    marque_p:="tiretv";
    for l=0 upto m-1:
    for k=0 upto #3:
    pointe(B[k] shifted(l*(#1+1cm,0)));
    endfor;
    endfor;
    if (#2 mod #3)<>0:
    for k=0 upto #3:
    pointe(B[k] shifted(m*(#1+1cm,0)));
    endfor;
    fi;
  \end{mpost}
  \fi
}

\newcommand\Fraction[2][]{%
  \useKVdefault[ClesFraction]%
  \setKV[ClesFraction]{#1}%
  \setsepchar[*]{/}%
  \readlist*\ListeFraction{#2}%
  \ifboolKV[ClesFraction]{Triangle}{%
    \ifboolKV[ClesFraction]{Reponse}{}{\setKV[ClesFraction]{Couleur=white}}%
      \ifboolKV[ClesFraction]{Hachures}{%
        \MPFractionTriangleH{\useKV[ClesFraction]{Longueur}}{\useKV[ClesFraction]{Parts}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}{\useKV[ClesFraction]{Epaisseur}}%
      }{%
        \MPFractionTriangle{\useKV[ClesFraction]{Longueur}}{\useKV[ClesFraction]{Parts}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}%
      }%
  }{%
    \ifboolKV[ClesFraction]{Regulier}{%
      \ifboolKV[ClesFraction]{Reponse}{}{\setKV[ClesFraction]{Couleur=white}}%
      \ifboolKV[ClesFraction]{Hachures}{%
        \MPFractionRegulierH{\useKV[ClesFraction]{Rayon}}{\useKV[ClesFraction]{Cotes}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}{\useKV[ClesFraction]{Epaisseur}}%
      }{%
        \MPFractionRegulier{\useKV[ClesFraction]{Rayon}}{\useKV[ClesFraction]{Cotes}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}%
      }%
    }{%
      \ifboolKV[ClesFraction]{Segment}{%
        \ifboolKV[ClesFraction]{Reponse}{}{\setKV[ClesFraction]{Couleur=white}}%
        \ifboolKV[ClesFraction]{Hachures}{%
          \MPFractionSegmentH{\useKV[ClesFraction]{Longueur}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}{\useKV[ClesFraction]{Epaisseur}}%
        }{%
          \MPFractionSegment{\useKV[ClesFraction]{Longueur}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}%
        }%
      }{%
        \ifboolKV[ClesFraction]{Rectangle}{%rectangle
          \ifboolKV[ClesFraction]{Reponse}{}{\setKV[ClesFraction]{Couleur=white}}%
          \ifboolKV[ClesFraction]{Hachures}{%
            \MPFractionRectangleH{\useKV[ClesFraction]{Longueur}}{\useKV[ClesFraction]{Largeur}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}{\useKV[ClesFraction]{Multiple}}{\useKV[ClesFraction]{Epaisseur}}%
          }{%
            \MPFractionRectangle{\useKV[ClesFraction]{Longueur}}{\useKV[ClesFraction]{Largeur}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}{\useKV[ClesFraction]{Multiple}}%
          }%
        }{%disque
          \ifboolKV[ClesFraction]{Reponse}{}{\setKV[ClesFraction]{Couleur=white}}%
          \ifboolKV[ClesFraction]{Hachures}{%
            \MPFractionDisqueH{\useKV[ClesFraction]{Rayon}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}{\useKV[ClesFraction]{Epaisseur}}% 
          }{%
            \MPFractionDisque{\useKV[ClesFraction]{Rayon}}{\ListeFraction[1]}{\ListeFraction[2]}{\useKV[ClesFraction]{Couleur}}%
          }%
        }%
      }%
    }%
  }%
}%

%%%
% R\'eponses \`a relier
%%%
\setKVdefault[ClesRelie]{Solution=false,LargeurG=5cm,LargeurD=2cm,Stretch=1.5,Ecart=2cm,Couleur=black}

\newcommand\Relie[2][]{%
  \useKVdefault[ClesRelie]%
  \setKV[ClesRelie]{#1}%
  \setsepchar[*]{,*/}%
  \readlist*\ListeRelie{#2}%
  \buildtabrelie%
  \ifboolKV[ClesRelie]{Solution}{%
    \colorlet{PfCRelieCouleurTrace}{\useKV[ClesRelie]{Couleur}}%
    \xintFor* ##1 in {\xintSeq {1}{\ListeRelielen}}\do{%
      \itemtomacro\ListeRelie[##1,1]\untest
      \ifx\bla\untest\bla%
      \else
      \tikz[remember picture,overlay]{\draw[PfCRelieCouleurTrace] (RelieG-##1) -- (RelieD-\ListeRelie[##1,3]);}%
      \fi
    }%
  }{%
  }%
}

\newcounter{NbRelie}

\def\buildtabrelie{%
  \setcounter{NbRelie}{0}%
  \renewcommand{\arraystretch}{\useKV[ClesRelie]{Stretch}}%
  \begin{tabular}{p{\useKV[ClesRelie]{LargeurG}}cp{\useKV[ClesRelie]{Ecart}}>{\tikz[remember
    picture]{\node[name=RelieD-\theNbRelie,inner
    sep=0pt]{};\fill[] (RelieD-\theNbRelie) circle[radius=1.5pt]}}cp{\useKV[ClesRelie]{LargeurD}}}%
    \xintFor* ##1 in {\xintSeq {1}{\ListeRelielen}}\do{\ListeRelie[##1,1]\itemtomacro\ListeRelie[##1,1]\untest%
\ifx\bla\untest\bla%                                       
    \uppercase{&}\stepcounter{NbRelie}%
      \else
      \uppercase{&}\stepcounter{NbRelie}\tikz[remember
                   picture,overlay]{\node[name=RelieG-\theNbRelie,inner
                   sep=0pt]{};\fill[]
                   (RelieG-\theNbRelie) circle[radius=1.5pt];}
\fi&&&\ListeRelie[##1,2]\\}%
  \end{tabular}%
  \setcounter{NbRelie}{0}%
}%

\def\buildtabrelieold{%
  \setcounter{NbRelie}{0}%
  \renewcommand{\arraystretch}{\useKV[ClesRelie]{Stretch}}%
  \begin{tabular}{p{\useKV[ClesRelie]{LargeurG}}cp{\useKV[ClesRelie]{Ecart}}>{\tikz[remember
    picture,baseline]{\node[name=RelieD-\theNbRelie]{\Large\textbullet};}}cp{\useKV[ClesRelie]{LargeurD}}}%
    \xintFor* ##1 in {\xintSeq {1}{\ListeRelielen}}\do{\ListeRelie[##1,1]\itemtomacro\ListeRelie[##1,1]\untest%
\ifx\bla\untest\bla%                                       
    \uppercase{&}\stepcounter{NbRelie}%
      \else
      \uppercase{&}\stepcounter{NbRelie}\tikz[remember picture,baseline]{\node[name=RelieG-\theNbRelie]{\Large\textbullet};}
\fi&&&\ListeRelie[##1,2]\\}%
  \end{tabular}%
  \setcounter{NbRelie}{0}%
}%

%%%
% QCM
%%%
\setKVdefault[ClesQCM]{Reponses=3,Solution=false,Stretch=1,Largeur=2cm,Couleur=gray!15,Titre=false,Nom=R\'eponse,NomV=Vrai,NomF=Faux,Alph=false,AlphT=false,VF=false,Depart=1,Alterne=false,Noms={A/B/C},Multiple=false}%
\newlength{\LargeurQCM}%
\newlength{\PfCLargeurQCM}%
\newcounter{QuestionQCM}%
\newcounter{TitreQCM}%
\ifdef{\QCM}{%
  \PackageWarning{ProfCollege}{La commande \noexpand\QCM étant définie par la classe du document, ProfCollege modifie sa commande \noexpand\QCM en \noexpand\QCMPfC.}%
  \newcommand\QCMPfC[2][]{%
    \useKVdefault[ClesQCM]%
    \setKV[ClesQCM]{#1}%
    \setcounter{QuestionQCM}{\fpeval{\useKV[ClesQCM]{Depart}-1}}%
    \setcounter{TitreQCM}{0}
    \setsepchar[*]{§*&}\ignoreemptyitems%
    \readlist*\ListeQCM{#2}%
    \ifboolKV[ClesQCM]{Multiple}{%
      \renewcommand{\arraystretch}{\useKV[ClesQCM]{Stretch}}%
      \setlength{\LargeurQCM}{\fpeval{(\linewidth-\useKV[ClesQCM]{Reponses}*(3*\tabcolsep+\useKV[ClesQCM]{Largeur}))}pt}%
      \xdef\NBcases{\fpeval{\useKV[ClesQCM]{Reponses}+1}}%
      \xdef\ListeNom{\useKV[ClesQCM]{Noms}}%
      \setsepchar[*]{/}%
      \readlist*\ListeNomsMul{\ListeNom}%
      \begin{tabular}{|p{\LargeurQCM}|*{\useKV[ClesQCM]{Reponses}}{>{\centering\arraybackslash}p{\useKV[ClesQCM]{Largeur}}|}}%
        \cline{2-\NBcases}%
        \multicolumn{1}{c|}{}\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
        &\ListeNomsMul[##2]}%
        \\
        \hline%
        \xintFor* ##1 in {\xintSeq {1}{\ListeQCMlen}}\do{%
        \stepcounter{QuestionQCM}\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Alph}{\textbf{\Alph{QuestionQCM}}/}{\textbf{\theQuestionQCM/}}~\ListeQCM[##1,1]\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
        &\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Solution}{\xintifboolexpr{\ListeQCM[##1,\fpeval{##2+1}]==1}{$\boxtimes$}{$\square$}}{$\square$}%
          }\\
        }%
        \hline%
      \end{tabular}%
    }{%
      \ifboolKV[ClesQCM]{VF}{%
        \setKV[ClesQCM]{Reponses=2}%
        \setlength{\PfCLargeurQCM}{\useKV[ClesQCM]{Largeur}}%
        \setlength{\LargeurQCM}{\linewidth-6\tabcolsep-2\PfCLargeurQCM-4\arrayrulewidth}%
        \renewcommand{\arraystretch}{\useKV[ClesQCM]{Stretch}}%
        \setlength{\LargeurQCM}{\fpeval{(\linewidth-\useKV[ClesQCM]{Reponses}*(3*\tabcolsep+\useKV[ClesQCM]{Largeur}))}pt}%
        \xdef\NBcases{\fpeval{\useKV[ClesQCM]{Reponses}+1}}%
        \begin{tabular}{|p{\LargeurQCM}|*{\useKV[ClesQCM]{Reponses}}{>{\centering\arraybackslash}p{\useKV[ClesQCM]{Largeur}}|}}%
          \cline{2-\NBcases}%
          \multicolumn{1}{c|}{}&\useKV[ClesQCM]{NomV}&\useKV[ClesQCM]{NomF}\\
          \hline%
          \xintFor* ##1 in {\xintSeq {1}{\ListeQCMlen}}\do{%
          \stepcounter{QuestionQCM}\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Alph}{\textbf{\Alph{QuestionQCM}}/}{\textbf{\theQuestionQCM/}}~\ListeQCM[##1,1]\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
                               &\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Solution}{\xintifboolexpr{##2==\ListeQCM[##1,2]}{$\boxtimes$}{$\square$}}{$\square$}%
                                 }\\
          }%
          \hline%
        \end{tabular}
      }{%
        \renewcommand{\arraystretch}{\useKV[ClesQCM]{Stretch}}%
        \setlength{\LargeurQCM}{\fpeval{(\linewidth-\useKV[ClesQCM]{Reponses}*(3*\tabcolsep+\useKV[ClesQCM]{Largeur}))}pt}%
        \xdef\NBcases{\fpeval{\useKV[ClesQCM]{Reponses}+1}}%
        \begin{tabular}{|p{\LargeurQCM}|*{\useKV[ClesQCM]{Reponses}}{>{\centering\arraybackslash}p{\useKV[ClesQCM]{Largeur}}|}}%
          \ifboolKV[ClesQCM]{Titre}{\cline{2-\NBcases}%
          \multicolumn{1}{c|}{}\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
          &\stepcounter{TitreQCM}\useKV[ClesQCM]{Nom} \ifboolKV[ClesQCM]{AlphT}{\Alph{TitreQCM}}{##2}}%
          \\
          }{}
          \hline%
          \xintFor* ##1 in {\xintSeq {1}{\ListeQCMlen}}\do{%
          \stepcounter{QuestionQCM}\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Alph}{\textbf{\Alph{QuestionQCM}}/}{\textbf{\theQuestionQCM/}}~\ListeQCM[##1,1]\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
          &\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Solution}{\xdef\NumeroReponse{\fpeval{\useKV[ClesQCM]{Reponses}+2}}\xintifboolexpr{##2==\ListeQCM[##1,\NumeroReponse]}{\cellcolor{\useKV[ClesQCM]{Couleur}}}{}}{}\ListeQCM[##1,##2+1]%
            }\\
          }%
          \hline%
        \end{tabular}%
      }%
    }%
    \renewcommand{\arraystretch}{1}%
  }%
}{%
  \newcommand\QCM[2][]{%
    \useKVdefault[ClesQCM]%
    \setKV[ClesQCM]{#1}%
    \setcounter{QuestionQCM}{\fpeval{\useKV[ClesQCM]{Depart}-1}}%
    \setcounter{TitreQCM}{0}
    \setsepchar[*]{,*&}\ignoreemptyitems%
    \readlist*\ListeQCM{#2}%
    \ifboolKV[ClesQCM]{Multiple}{%
      \renewcommand{\arraystretch}{\useKV[ClesQCM]{Stretch}}%
      \setlength{\LargeurQCM}{\fpeval{(\linewidth-\useKV[ClesQCM]{Reponses}*(3*\tabcolsep+\useKV[ClesQCM]{Largeur}))}pt}%
      \xdef\NBcases{\fpeval{\useKV[ClesQCM]{Reponses}+1}}%
      \xdef\ListeNom{\useKV[ClesQCM]{Noms}}%
      \setsepchar[*]{/}%
      \readlist*\ListeNomsMul{\ListeNom}%
      \begin{tabular}{|p{\LargeurQCM}|*{\useKV[ClesQCM]{Reponses}}{>{\centering\arraybackslash}p{\useKV[ClesQCM]{Largeur}}|}}%
        \cline{2-\NBcases}%
        \multicolumn{1}{c|}{}\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
        &\ListeNomsMul[##2]}%
        \\
        \hline%
        \xintFor* ##1 in {\xintSeq {1}{\ListeQCMlen}}\do{%
        \stepcounter{QuestionQCM}\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Alph}{\textbf{\Alph{QuestionQCM}}/}{\textbf{\theQuestionQCM/}}~\ListeQCM[##1,1]\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
        &\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Solution}{\xintifboolexpr{\ListeQCM[##1,\fpeval{##2+1}]==1}{$\boxtimes$}{$\square$}}{$\square$}%
          }\\
        }%
        \hline%
      \end{tabular}%
      \renewcommand{\arraystretch}{1}%
    }{%
      \ifboolKV[ClesQCM]{VF}{%
        \setKV[ClesQCM]{Reponses=2}%
        \renewcommand{\arraystretch}{\useKV[ClesQCM]{Stretch}}%
        \setlength{\PfCLargeurQCM}{\useKV[ClesQCM]{Largeur}}%
        \setlength{\LargeurQCM}{\linewidth-6\tabcolsep-2\PfCLargeurQCM-4\arrayrulewidth}%
        \xdef\NBcases{\fpeval{\useKV[ClesQCM]{Reponses}+1}}%
        \begin{tabular}{|p{\LargeurQCM}|*{\useKV[ClesQCM]{Reponses}}{>{\centering\arraybackslash}p{\useKV[ClesQCM]{Largeur}}|}}%
          \cline{2-\NBcases}%
          \multicolumn{1}{c|}{}&\useKV[ClesQCM]{NomV}&\useKV[ClesQCM]{NomF}\\
          \hline%
          \xintFor* ##1 in {\xintSeq {1}{\ListeQCMlen}}\do{%
          \stepcounter{QuestionQCM}\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Alph}{\textbf{\Alph{QuestionQCM}}/}{\textbf{\theQuestionQCM/}}~\ListeQCM[##1,1]\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
                               &\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Solution}{\xintifboolexpr{##2==\ListeQCM[##1,2]}{$\boxtimes$}{$\square$}}{$\square$}%
                                 }\\
          }%
          \hline%
        \end{tabular}
      }{%
        \renewcommand{\arraystretch}{\useKV[ClesQCM]{Stretch}}%
        \setlength{\LargeurQCM}{\fpeval{(\linewidth-\useKV[ClesQCM]{Reponses}*(3*\tabcolsep+\useKV[ClesQCM]{Largeur}))}pt}%
        \xdef\NBcases{\fpeval{\useKV[ClesQCM]{Reponses}+1}}%
        \begin{tabular}{|p{\LargeurQCM}|*{\useKV[ClesQCM]{Reponses}}{>{\centering\arraybackslash}p{\useKV[ClesQCM]{Largeur}}|}}%
          \ifboolKV[ClesQCM]{Titre}{\cline{2-\NBcases}%
          \multicolumn{1}{c|}{}\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
          &\stepcounter{TitreQCM}\useKV[ClesQCM]{Nom} \ifboolKV[ClesQCM]{AlphT}{\Alph{TitreQCM}}{##2}}%
          \\
          }{}
          \hline%
          \xintFor* ##1 in {\xintSeq {1}{\ListeQCMlen}}\do{%
          \stepcounter{QuestionQCM}\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Alph}{\textbf{\Alph{QuestionQCM}}/}{\textbf{\theQuestionQCM/}}~\ListeQCM[##1,1]\xintFor* ##2 in {\xintSeq {1}{\useKV[ClesQCM]{Reponses}}}\do{%
          &\ifboolKV[ClesQCM]{Alterne}{\modulo{\theQuestionQCM}{2}\ifnum\remainder=0\cellcolor{gray!15}\fi}{}\ifboolKV[ClesQCM]{Solution}{\xdef\NumeroReponse{\fpeval{\useKV[ClesQCM]{Reponses}+2}}\xintifboolexpr{##2==\ListeQCM[##1,\NumeroReponse]}{\cellcolor{\useKV[ClesQCM]{Couleur}}}{}}{}\ListeQCM[##1,##2+1]%
            }\\
          }%
          \hline%
        \end{tabular}%
      }%
    }%
    \renewcommand{\arraystretch}{1}%
  }%
}

%%%
% Somme des angles
%%%
\setKVdefault[ClesSommeAngle]{Detail=true,Isocele=false,Rectangle=false,Figure=false,FigureSeule=false,Angle=0,Perso=false,Echelle=1cm}%

\def\MPFigureSommeAngle#1#2#3#4#5{%
    % #1 Premier sommet
    % #2 Deuxi\`eme sommet
    % #3 Troisi\`eme sommet
    % #4 1er angle
    % #5 2eme angle
  \ifluatex
  %\mplibcodeinherit{enable}
  \mplibforcehmode
  \begin{mplibcode}
    pair A,B,C,O,I;%
    u:=\useKV[ClesSommeAngle]{Echelle};
    Angle:=\useKV[ClesSommeAngle]{Angle};
    boolean Rectangle,Isocele;
    Rectangle=\useKV[ClesSommeAngle]{Rectangle};%
    Isocele=\useKV[ClesSommeAngle]{Isocele};
    A=u*(1,1);
    B-A=u*(4,0);
    if Rectangle:
    C=3/5[B,rotation(A,B,-90)];
    else:
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    fi;
    O=CentreCercleC(A,B,C);
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=rotation(A,O,Angle);
    B:=rotation(B,O,Angle);
    C:=rotation(C,O,Angle);
    % On d\'efinit le centre du cercle inscrit
    I=CentreCercleI(A,B,C);
    % on dessine \`a main lev\'ee :)
    path triangle;
    triangle=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)}--B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)}--C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)}--cycle;
    % pour marquer les angles
    path cc;
    cc=fullcircle scaled 1u;
    picture MAngle;
    path cd; pair M[];
    MAngle=image(%
    if Isocele:%
    if Rectangle:
    trace codeperp(A,B,C,5);
    cd=A--(A+B+C)/3;
    M1=cd intersectionpoint (cc shifted A);
    trace 9/10[A,M1]--11/10[A,M1];
    cd:=C--(A+B+C)/3;
    M1:=cd intersectionpoint (cc shifted C);
    trace 9/10[C,M1]--11/10[C,M1];
    else:
    cd=B--(A+B+C)/3;
    M1=cd intersectionpoint (cc shifted B);
    trace 9/10[B,M1]--11/10[B,M1];
    cd:=C--(A+B+C)/3;
    M1:=cd intersectionpoint (cc shifted C);
    trace 9/10[C,M1]--11/10[C,M1];
    fi;
    fi;
    if Rectangle:
    trace codeperp(A,B,C,5);
    else:
    draw (cc shifted B);
    fi;
    draw (cc shifted A);
    draw (cc shifted C);
    );
    draw MAngle;
    clip currentpicture to triangle;
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    % on labelise
    label(btex #1 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #3 etex,1.2[O,C]);
    % Codage
    if Isocele:
    marque_s:=marque_s/2;
    if Rectangle:
    draw Codelongueur(A,B,B,C,2);
    else:
    draw Codelongueur(A,B,A,C,2);
    fi;
    marque_s:=marque_s*2;
    fi;
    % Affichage des angles:
    if Isocele:
    if Rectangle:
    label(btex ? etex,A+0.95u*unitvector(I-A));
    else:
    if #4>#5:%Cas où b est vide donc on affiche la mesure commune
    label(btex $\ang{#4}$ etex,A+0.95u*unitvector(I-A));
    label(btex ? etex,B+0.95u*unitvector(I-B));
    else:
    label(btex $\ang{#5}$ etex,B+0.95u*unitvector(I-B));
    label(btex ? etex,A+0.95u*unitvector(I-A));
    fi;
    fi;
    else:
    if Rectangle:
    if #4>#5:
    label(btex $\ang{#4}$ etex,C+0.95u*unitvector(I-C));
    else:
    label(btex $\ang{#5}$ etex,C+0.95u*unitvector(I-C));
    fi;
    else:
    label(btex $\ang{#4}$ etex,B+0.95u*unitvector(I-B));
    label(btex $\ang{#5}$ etex,C+0.95u*unitvector(I-C));
    fi;
    label(btex ? etex,A+0.95u*unitvector(I-A));
    fi;
  \end{mplibcode}
  %\mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesSommeAngle]{Echelle};boolean Rectangle,Isocele;
      Rectangle=\useKV[ClesSommeAngle]{Rectangle};Isocele=\useKV[ClesSommeAngle]{Isocele};Angle:=\useKV[ClesSommeAngle]{Angle};}]
    pair A,B,C,O,I;%
    A=u*(1,1);
    B-A=u*(4,0);
    if Rectangle:
    C=3/5[B,rotation(A,B,-90)];
    else:
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    fi;
    O=CentreCercleC(A,B,C);
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=rotation(A,O,Angle);
    B:=rotation(B,O,Angle);
    C:=rotation(C,O,Angle);
    % On d\'efinit le centre du cercle inscrit
    I=CentreCercleI(A,B,C);
    % on dessine \`a main lev\'ee :)
    path triangle;
    triangle=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)}--B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)}--C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)}--cycle;
    % pour marquer les angles
    path cc;
    cc=fullcircle scaled 1u;
    picture MAngle;
    path cd; pair M[];
    MAngle=image(%
    if Isocele:%
    if Rectangle:
    trace codeperp(A,B,C,5);
    cd=A--(A+B+C)/3;
    M1=cd intersectionpoint (cc shifted A);
    trace 9/10[A,M1]--11/10[A,M1];
    cd:=C--(A+B+C)/3;
    M1:=cd intersectionpoint (cc shifted C);
    trace 9/10[C,M1]--11/10[C,M1];
    else:
    cd=B--(A+B+C)/3;
    M1=cd intersectionpoint (cc shifted B);
    trace 9/10[B,M1]--11/10[B,M1];
    cd:=C--(A+B+C)/3;
    M1:=cd intersectionpoint (cc shifted C);
    trace 9/10[C,M1]--11/10[C,M1];
    fi;
    fi;
    if Rectangle:
    trace codeperp(A,B,C,5);
    else:
    draw (cc shifted B);
    fi;
    draw (cc shifted A);
    draw (cc shifted C);
    );
    draw MAngle;
    clip currentpicture to triangle;
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    % on labelise
    label(btex #1 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #3 etex,1.2[O,C]);
    % Codage
    if Isocele:
    marque_s:=marque_s/2;
    if Rectangle:
    draw Codelongueur(A,B,B,C,2);
    else:
    draw Codelongueur(A,B,A,C,2);
    fi;
    marque_s:=marque_s*2;
    fi;
    % Affichage des angles:
    if Isocele:
    if Rectangle:
    label(btex ? etex,A+0.95u*unitvector(I-A));
    else:
    if #4>#5:%Cas où b est vide donc on affiche la mesure commune
    label(btex $\ang{#4}$ etex,A+0.95u*unitvector(I-A));
    label(btex ? etex,B+0.95u*unitvector(I-B));
    else:
    label(btex $\ang{#5}$ etex,B+0.95u*unitvector(I-B));
    label(btex ? etex,A+0.95u*unitvector(I-A));
    fi;
    fi;
    else:
    if Rectangle:
    if #4>#5:
    label(btex $\ang{#4}$ etex,C+0.95u*unitvector(I-C));
    else:
    label(btex $\ang{#5}$ etex,C+0.95u*unitvector(I-C));
    fi;
    else:
    label(btex $\ang{#4}$ etex,B+0.95u*unitvector(I-B));
    label(btex $\ang{#5}$ etex,C+0.95u*unitvector(I-C));
    fi;
    label(btex ? etex,A+0.95u*unitvector(I-A));
    fi;
  \end{mpost}
  \fi
}

\xdef\RedactionSomme{}

\newcommand\RedactionSom[4][]{%
  % #1 : nom du triangle pA pB pC
  % #2 : mesure de l'angle pApBpC
  % #3 : mesure de l'angle pBpCpA
  \useKVdefault[ClesSommeAngle]%
  \setKV[ClesSommeAngle]{#1}%
  % On r\'ecup\`ere les noms des sommets.
  \StrMid{#2}{1}{1}[\NomA]%
  \StrMid{#2}{2}{2}[\NomB]%
  \StrMid{#2}{3}{3}[\NomC]%
  \xdef\NomTriangle{\NomA\NomB\NomC}%
  \xdef\NomSommetB{\NomB}%
  \xdef\NomSommetA{\NomA}%
  \xdef\NomSommetC{\NomC}%
  % On r\'edige
  \ifboolKV[ClesSommeAngle]{Perso}{\RedactionSomme}{Dans le triangle $\NomA\NomB\NomC$, \ifboolKV[ClesSommeAngle]{Rectangle}{ rectangle \ifboolKV[ClesSommeAngle]{Isocele}{isocèle }{}en $\NomB$, }{\ifboolKV[ClesSommeAngle]{Isocele}{ isoc\`ele en $\NomA$, }}%
    on a :}%
  \ifboolKV[ClesSommeAngle]{Rectangle}{%
    \ifboolKV[ClesSommeAngle]{Isocele}{%
      \ifx\bla#3\bla%
      \begin{align*}
        2\times\widehat{\NomB\NomA\NomC}&=\ang{90}\\%
        \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomB\NomA\NomC}&=\frac{\ang{90}}{2}\\}{\widehat{\NomA\NomB\NomC}&=\ang{45}}%
      \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomB\NomA\NomC}&=\ang{45}}{}%
      \end{align*}
      \fi
    }{%
      \ifx\bla#3\bla%
      \begin{align*}
        \widehat{\NomB\NomA\NomC}+\widehat{\NomB\NomC\NomA}&=\ang{90}\\%
        \widehat{\NomB\NomA\NomC}+\ang{#4}&=\ang{90}\\%
        \xdef\totalangle{\fpeval{90-#4}}\ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomB\NomA\NomC}&=\ang{90}-\ang{#4}\\}{\widehat{\NomB\NomA\NomC}&=\ang{\totalangle}}%
      \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomB\NomA\NomC}&=\ang{\totalangle}}{}%
      \end{align*}
      \fi
    }%
  }{%
    \ifboolKV[ClesSommeAngle]{Isocele}{%
      \ifx\bla#4\bla%
      \begin{align*}%
        \widehat{\NomA\NomB\NomC}+\widehat{\NomB\NomC\NomA}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        2\times\ang{#3}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        \xdef\sommeangle{\fpeval{2*#3}}\xdef\totalangle{\fpeval{180-\sommeangle}}\ang{\sommeangle}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomC\NomA\NomB}&=\ang{180}-\ang{\sommeangle}\\}{\widehat{\NomC\NomA\NomB}&=\ang{\totalangle}}%
                                                                                                                               \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomC\NomA\NomB}&=\ang{\totalangle}}{}%
      \end{align*}%
      \xdef\ResultatAngle{\totalangle}%
      \else%
      \begin{align*}%
        \widehat{\NomA\NomB\NomC}+\widehat{\NomB\NomC\NomA}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        2\times\widehat{\NomA\NomB\NomC}+\ang{#4}&=\ang{180}\\%
        \xdef\totalangle{\fpeval{180-#4}}%
        \ifboolKV[ClesSommeAngle]{Detail}{2\times\widehat{\NomA\NomB\NomC}&=\ang{180}-\ang{#4}\\}{2\times\widehat{\NomA\NomB\NomC}&=\ang{\totalangle}\\}%
        \ifboolKV[ClesSommeAngle]{Detail}{2\times\widehat{\NomA\NomB\NomC}&=\ang{\totalangle}\\}{\widehat{\NomA\NomB\NomC}&=\frac{\ang{\totalangle}}{2}\\}%
        \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomA\NomB\NomC}&=\frac{\ang{\totalangle}}{2}\\}{\widehat{\NomA\NomB\NomC}&=\ang{\fpeval{0.5*(180-#4)}}}%\\
        \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomA\NomB\NomC}&=\ang{\fpeval{0.5*(180-#4)}}\\}{}%
      \end{align*}%
      \xdef\ResultatAngle{\fpeval{0.5*(180-#4)}}%
      \fi%
    }{%
      \begin{align*}%
        \widehat{\NomA\NomB\NomC}+\widehat{\NomB\NomC\NomA}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        \ang{#3}+\ang{#4}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        \xdef\sommeangle{\fpeval{#3+#4}}\xdef\totalangle{\fpeval{180-\sommeangle}}\ang{\sommeangle}+\widehat{\NomC\NomA\NomB}&=\ang{180}\\%
        \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomC\NomA\NomB}&=\ang{180}-\ang{\sommeangle}\\}{\widehat{\NomC\NomA\NomB}&=\ang{\totalangle}}%\\
        \ifboolKV[ClesSommeAngle]{Detail}{\widehat{\NomC\NomA\NomB}&=\ang{\totalangle}}{}%
      \end{align*}%
      \xdef\ResultatAngle{\totalangle}%
    }%
  }%
}%

\newcommand\SommeAngles[4][]{% Macro calculant la mesure de l'angle pCpApB
  % #1 : nom du triangle pA pB pC
  % #2 : mesure de l'angle pApBpC
  % #3 : mesure de l'angle pBpCpA
  \useKVdefault[ClesSommeAngle]%obligatoire car la macro n'est pas dans un groupe.
  \setKV[ClesSommeAngle]{#1}%lit les arguments optionnels
  % On r\'ecup\`ere les noms des sommets.
  \StrMid{#2}{1}{1}[\NomA]%
  \StrMid{#2}{2}{2}[\NomB]%
  \StrMid{#2}{3}{3}[\NomC]%
  % Figure ou pas ?
  \ifboolKV[ClesSommeAngle]{FigureSeule}{%
    \ifx\bla#3\bla%
    \MPFigureSommeAngle{\NomA}{\NomB}{\NomC}{#4}{0}%
    \else%
    \ifx\bla#4\bla%
    \MPFigureSommeAngle{\NomA}{\NomB}{\NomC}{0}{#3}%
    \else%
    \MPFigureSommeAngle{\NomA}{\NomB}{\NomC}{#3}{#4}%
    \fi%
    \fi%
  }{%
    \ifboolKV[ClesSommeAngle]{Figure}{%
      \begin{multicols}{2}%
        {\em La figure est donn\'ee \`a titre indicatif.}%
        \ifx\bla#3\bla%
        \[\MPFigureSommeAngle{\NomA}{\NomB}{\NomC}{#4}{0}\]%
        \else%
        \ifx\bla#4\bla%
        \[\MPFigureSommeAngle{\NomA}{\NomB}{\NomC}{0}{#3}\]%
        \else%
        \[\MPFigureSommeAngle{\NomA}{\NomB}{\NomC}{#3}{#4}\]%
        \fi%
        \fi%
        \par\columnbreak\par%
        \RedactionSom[#1]{#2}{#3}{#4}%
      \end{multicols}%
    }{% on r\'edige
      \RedactionSom[#1]{#2}{#3}{#4}%
    }%
  }%
}%

%%%
% Le th\'eor\`eme de Pythagore
%%%
\setKVdefault[ClesPythagore]{Exact=false,AvantRacine=false,Racine=false,Entier=false,Egalite=false,Precision=2,Soustraction=false,Figure=false,FigureSeule=false,Angle=0,Echelle=1cm,Reciproque=false,ReciColonnes=false,Faible=false,Unite=cm,EnchaineA=false,EnchaineB=false,EnchaineC=false,ValeurA=0,ValeurB=0,ValeurC=0,Perso=false,AllPerso=false,SansMots=false}

% On d\'efinit les figures \`a utiliser
\def\MPFigurePytha#1#2#3#4#5#6{%
  % #1 Premier sommet
  % #2 Sommet de l'angle droit
  % #3 troisi\`eme sommet
  % #4 1ere longueur
  % #5 2eme longueur
  % #6 angle de rotation de la figure
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesPythagore]{Echelle};
    pair A,B,C,O,D,E,F;%B est le sommet de l'angle droit
    O=u*(2.5,2.5);
    path cc;
    cc=(fullcircle scaled 4u) shifted O;
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.9*length cc) of cc;
    B=A rotatedabout(O,-120);
    C=2[A,O];
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % On d\'efinit l'angle droit
    D-B=7*unitvector(C-B);
    F-B=7*unitvector(A-B);
    E-D=F-B;
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    draw D--E--F;
    numeric decalage;
    decalage=3mm;
    if (#4<#5) or (#4=#5) :
    if ypart(B)>ypart(O) :
        label(btex \num{#4} etex,1/2[C,B]-decalage*(unitvector(A-B)));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
     else:
        label(btex \num{#4} etex,1/2[C,B]-decalage*(unitvector(A-B)));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
     fi
    else:
      if ypart(B)>ypart(O) :
        label(btex \num{#4} etex,1/2[C,A]-decalage*(unitvector(C-A) rotated 90));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
        else:
        label(btex \num{#4} etex,1/2[A,C]+decalage*(unitvector(A-C)
        rotated 90));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
      fi;
    fi;
    label(btex #3 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #1 etex,1.2[O,C]);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesPythagore]{Echelle};}]
    pair A,B,C,O,D,E,F;%B est le sommet de l'angle droit
    O=u*(2.5,2.5);
    path cc;
    cc=(fullcircle scaled 4u) shifted O;
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.9*length cc) of cc;
    B=A rotatedabout(O,-120);
    C=2[A,O];
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % On d\'efinit l'angle droit
    D-B=7*unitvector(C-B);
    F-B=7*unitvector(A-B);
    E-D=F-B;
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};    
    draw D--E--F;
    decalage=3mm;
    if (#4<#5) or (#4=#5) :
    if ypart(B)>ypart(O) :
        label(btex \num{#4} etex,1/2[C,B]-decalage*(unitvector(A-B)));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
     else:
        label(btex \num{#4} etex,1/2[C,B]-decalage*(unitvector(A-B)));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
     fi
    else:
      if ypart(B)>ypart(O) :
      label(btex \num{#4} etex,1/2[C,A]-decalage*(unitvector(C-A) rotated 90));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
        else:
        label(btex \num{#4} etex,1/2[A,C]+decalage*(unitvector(A-C)
        rotated 90));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
      fi;
    fi;
    label(btex #3 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #1 etex,1.2[O,C]);
  \end{mpost}
  \fi
}

\def\MPFigureReciPytha#1#2#3#4#5#6#7{%
  % #1 Premier sommet
    % #2 Sommet de l'angle droit
    % #3 troisi\`eme sommet
    % #4 1ere longueur
    % #5 2eme longueur
    % #6 3eme longueur
    % #7 angle de rotation de la figure
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesPythagore]{Echelle};
    pair A,B,C,O,D,E,F;%B est le sommet de l'angle droit
    O=u*(2.5,2.5);
    path cc;
    cc=(fullcircle scaled 4u) shifted O;
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.8*length cc) of cc;
    B=A rotatedabout(O,-100);
    C=2[A,O];
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#7);
    B:=B rotatedabout(O,#7);
    C:=C rotatedabout(O,#7);
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};    
    decalage=3mm;
    if ypart(B)>ypart(O) :
    label(btex \num{#4} etex,1/2[C,A]-decalage*(unitvector(C-A) rotated 90));
    label(btex \num{#5} etex,1/2[C,B]-decalage*(unitvector(C-B)));
    label(btex \num{#6} etex,1/2[A,B]-decalage*(unitvector(C-B)));
    else:
    label(btex \num{#4} etex,1/2[A,C]+decalage*(unitvector(A-C) rotated 90));
    label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
    label(btex \num{#6} etex,1/2[C,B]-decalage*(unitvector(A-B)));
    fi;
    label(btex #1 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #3 etex,1.2[O,C]);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesPythagore]{Echelle};}]
    pair A,B,C,O,D,E,F;%B est le sommet de l'angle droit
    O=u*(2.5,2.5);
    path cc;
    cc=(fullcircle scaled 4u) shifted O;
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.8*length cc) of cc;
    B=A rotatedabout(O,-100);
    C=2[A,O];
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#7);
    B:=B rotatedabout(O,#7);
    C:=C rotatedabout(O,#7);
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};    
    decalage=3mm;
    if ypart(B)>ypart(O) :
    label(LATEX("\num{"&decimal(#4)&"}") rotated angle(C-A),1/2[C,A]-decalage*(unitvector(C-A) rotated 90));
    label(LATEX("\num{"&decimal(#5)&"}") rotated(angle(C-B)),1/2[C,B]-decalage*(unitvector(C-B)));
    label(LATEX("\num{"&decimal(#6)&"}") rotated(angle(B-A)),1/2[A,B]-decalage*(unitvector(C-B)));
    else:
    label(LATEX("\num{"&decimal(#4)&"}") rotated angle(A-C),1/2[A,C]+decalage*(unitvector(A-C) rotated 90));
    label(LATEX("\num{"&decimal(#5)&"}") rotated(angle(A-B)),1/2[A,B]-decalage*(unitvector(C-B)));
    label(LATEX("\num{"&decimal(#6)&"}") rotated angle(C-B),1/2[C,B]-decalage*(unitvector(A-B)));
    fi;
    label(btex #1 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #3 etex,1.2[O,C]);
  \end{mpost}
  \fi
}

\def\MPFigurePythaSansMots#1#2#3#4#5#6{%
  % #1 Premier sommet
  % #2 Sommet de l'angle droit
  % #3 troisi\`eme sommet
  % #4 1ere longueur
  % #5 2eme longueur
  % #6 angle de rotation de la figure
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesPythagore]{Echelle};
    pair A,B,C,O,D,E,F,L[],M[],N[];%B est le sommet de l'angle droit
    O=u*(2.5,2.5);
    path cc;
    cc=(fullcircle scaled 4u) shifted O;
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.9*length cc) of cc;
    B=A rotatedabout(O,-120);
    C=2[A,O];
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % On d\'efinit l'angle droit
    D-B=7*unitvector(C-B);
    F-B=7*unitvector(A-B);
    E-D=F-B;
    trace polygone(A,B,C);
    draw D--E--F;
    L1=rotation(B,A,90);
    L2-L1=B-A;
    trace chemin(A,L1,L2,B);
    M1=rotation(C,B,90);
    M2-M1=C-B;
    trace chemin(B,M1,M2,C);
    N1=rotation(A,C,90);
    N2-N1=A-C;
    trace chemin(C,N1,N2,A);    
    numeric decalage;
    decalage=3mm;
    if (#4<#5) or (#4=#5) :
    if ypart(B)>ypart(O) :
        label(btex \num{#4} etex,1/2[C,B]+decalage*(unitvector(A-B)));
        label(btex \num{#5} etex,1/2[A,B]+decalage*(unitvector(C-B)));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#5}\times\num{#5}$\\$\num{\fpeval{#5*#5}}$\\\end{tabular}"),iso(A,L2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#4}\times\num{#4}$\\$\num{\fpeval{#4*#4}}$\\\end{tabular}"),iso(B,M2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{\fpeval{#4*#4}}+\num{\fpeval{#5*#5}}$\\$\num{\fpeval{#4*#4+#5*#5}}$\\\end{tabular}"),iso(C,N2));
     else:
        label(btex \num{#4} etex,1/2[C,B]+decalage*(unitvector(A-B)));
        label(btex \num{#5} etex,1/2[A,B]+decalage*(unitvector(C-B)));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#5}\times\num{#5}$\\$\num{\fpeval{#5*#5}}$\\\end{tabular}"),iso(A,L2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#4}\times\num{#4}$\\$\num{\fpeval{#4*#4}}$\\\end{tabular}"),iso(B,M2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{\fpeval{#4*#4}}+\num{\fpeval{#5*#5}}$\\$\num{\fpeval{#4*#4+#5*#5}}$\\\end{tabular}"),iso(C,N2));
        drawarrow 2/10[iso(A,L2),iso(C,N2)]--8/10[iso(A,L2),iso(C,N2)];
        drawarrow 2/10[iso(B,M2),iso(C,N2)]--8/10[iso(B,M2),iso(C,N2)];
     fi
    else:
      if ypart(B)>ypart(O) :
        label(btex \num{#4} etex,1/2[C,A]-decalage*(unitvector(C-A) rotated 90));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#5}\times\num{#5}$\\$\num{\fpeval{#5*#5}}$\\\end{tabular}"),iso(A,L2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#4}\times\num{#4}$\\$\num{\fpeval{#4*#4}}$\\\end{tabular}"),iso(C,N2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{\fpeval{#4*#4}}-\num{\fpeval{#5*#5}}$\\$\num{\fpeval{#4*#4-#5*#5}}$\\\end{tabular}"),iso(B,M2));
        drawarrow 2/10[iso(A,L2),iso(B,M2)]--8/10[iso(A,L2),iso(B,M2)];
        drawarrow 2/10[iso(C,N2),iso(B,M2)]--8/10[iso(C,N2),iso(B,M2)];
        else:
        label(btex \num{#4} etex,1/2[A,C]+decalage*(unitvector(A-C) rotated 90));
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#5}\times\num{#5}$\\$\num{\fpeval{#5*#5}}$\\\end{tabular}"),iso(A,L2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{#4}\times\num{#4}$\\$\num{\fpeval{#4*#4}}$\\\end{tabular}"),iso(C,N2));
        label(TEX("\begin{tabular}{c}Aire\\$\num{\fpeval{#4*#4}}-\num{\fpeval{#5*#5}}$\\$\num{\fpeval{#4*#4-#5*#5}}$\\\end{tabular}"),iso(B,M2));
        drawarrow 2/10[iso(A,L2),iso(B,M2)]--8/10[iso(A,L2),iso(B,M2)];
        drawarrow 2/10[iso(C,N2),iso(B,M2)]--8/10[iso(C,N2),iso(B,M2)];
      fi;
    fi;
    label(btex #3 etex,1.2[O,A]);
    label(btex #2 etex,1.2[O,B]);
    label(btex #1 etex,1.2[O,C]);
  \end{mplibcode}
  \fi
}

\newcommand\RedactionPythagore{}%
\newcommand\RedactionReciPythagore{}%
\newcommand\RedactionCalculsPythagore{}%
\newcommand\RedactionCalculsReciPythagore{}%
\newcommand\RedactionConclusionReciPythagore{}%

% \newcommand\Pythagore[5][]{%
\NewDocumentCommand\Pythagore{o m m m m}{%
  % #1 Param\`etres sous forme de cl\'es
  % #2 Nom "complet" du triangle : ABC par exemple
  % #3 Premi\`ere longueur
  % #4 Deuxi\`eme longueur
  % #5 Troisi\`eme longueur (\'eventuellement vide)
  \useKVdefault[ClesPythagore]%obligatoire car la macro n'est pas dans un groupe.
  \setKV[ClesPythagore]{#1}%On lit les arguments optionnels
  \DeclareSIUnit{\PfCPythaUnit}{\useKV[ClesPythagore]{Unite}}%
  \ifboolKV[ClesPythagore]{Reciproque}{%
    % On retient les noms des sommets
    \StrMid{#2}{1}{1}[\NomA]%
    \StrMid{#2}{2}{2}[\NomB]%
    \StrMid{#2}{3}{3}[\NomC]%
    \xdef\NomTriangle{\NomA\NomB\NomC}%
    % on stocke les valeurs donn\'ees
    \opcopy{#3}{A1}%
    \opcopy{#4}{A2}%
    \opcopy{#5}{A3}%
    \xdef\GrandCote{#3}%
    \xdef\PetitCote{#4}%
    \xdef\MoyenCote{#5}%
    % On trace une figure ou pas ?
    \ifboolKV[ClesPythagore]{FigureSeule}{%
      \MPFigureReciPytha{\NomA}{\NomB}{\NomC}{#3}{#4}{#5}{\useKV[ClesPythagore]{Angle}}%
    }{%
      \ifboolKV[ClesPythagore]{Figure}{%Utilisation obligatoire de l'option --shell-escape de la compilation
        \begin{multicols}{2}
          {\em La figure est donn\'ee \`a titre indicatif.}%
          \[\MPFigureReciPytha{\NomA}{\NomB}{\NomC}{#3}{#4}{#5}{\useKV[ClesPythagore]{Angle}}\]%
          \par\columnbreak\par%
          \ifboolKV[ClesPythagore]{AllPerso}{%
            \RedactionReciPythagore%
            \RedactionCalculsReciPythagore%
            \RedactionConclusionReciPythagore%
          }{%
            % on r\'edige
            \ifboolKV[ClesPythagore]{Perso}{%
              \RedactionReciPythagore%
            }{%
              Dans le triangle $#2$, $[\NomA\NomC]$ est le plus grand c\^ot\'e.%
            }
            \ifboolKV[ClesPythagore]{ReciColonnes}{%
              \[
                \begin{array}{cccc|cccc}
                  &&\NomA\NomC^2&&&\NomA\NomB^2&+&\NomB\NomC^2\\
                  &&\opexport{A1}{\Aun}\num{\Aun}^2&&&\opexport{A2}{\Adeux}\num{\Adeux}^2&+&\opexport{A3}{\Atrois}\num{\Atrois}^2\\
                  &&\opmul*{A1}{A1}{a1}&&&\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}&+&\opmul*{A3}{A3}{a3}\opexport{a3}{\Atrois}\num{\Atrois}\\
                  &&\opexport{a1}{\Aun}\num{\Aun}&&&\multicolumn{3}{c}{\opadd*{a2}{a3}{a4}\opexport{a4}{\Aquatre}\num{\Aquatre}}\\
                \end{array}
              \]
            }{%
              \[\left.
                  \begin{array}{l}
                    \NomA\NomC^2=\opexport{A1}{\Aun}\num{\Aun}^2=\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}\\
                    \\
                    \NomA\NomB^2+\NomB\NomC^2=\opexport{A2}{\Adeux}\num{\Adeux}^2+\opexport{A3}{\Atrois}\num{\Atrois}^2=\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}+\opmul*{A3}{A3}{a3}\opexport{a3}{\Atrois}\num{\Atrois}=\opadd*{a2}{a3}{a4}\opexport{a4}{\Aquatre}\num{\Aquatre}\\
                  \end{array}
                \right\}\opcmp{a1}{a4}\ifopeq\NomA\NomC^2=\NomA\NomB^2+\NomB\NomC^2\fi\opcmp{a1}{a4}\ifopneq\NomA\NomC^2\not=\NomA\NomB^2+\NomB\NomC^2\fi
              \]
            }
            \ifboolKV[ClesPythagore]{Egalite}{%
              \opcmp{a1}{a4}\ifopeq Comme $\NomA\NomC^2=\NomA\NomB^2+\NomB\NomC^2$, alors l'\'egalit\'e de Pythagore est v\'erifi\'ee. Donc le triangle $#2$ est rectangle en $\NomB$.\fi%
              \opcmp{a1}{a4}\ifopneq Comme $\NomA\NomC^2\not=\NomA\NomB^2+\NomB\NomC^2$, alors l'\'egalit\'e de Pythagore n'est pas v\'erifi\'ee. Donc le triangle $#2$ n'est pas rectangle.\fi%
            }{%
              \opcmp{a1}{a4}\ifopeq Comme $\NomA\NomC^2=\NomA\NomB^2+\NomB\NomC^2$, alors le triangle $#2$ est rectangle
              en $\NomB$ d'apr\`es la r\'eciproque du th\'eor\`eme de Pythagore.\fi%
              \opcmp{a1}{a4}\ifopneq Comme $\NomA\NomC^2\not=\NomA\NomB^2+\NomB\NomC^2$, alors le
              triangle $#2$ n'est pas rectangle\ifboolKV[ClesPythagore]{Faible}{.}{ d'apr\`es la contrapos\'ee du th\'eor\`eme de Pythagore.}\fi%
            }
          }
        \end{multicols}
      }{%
        \ifboolKV[ClesPythagore]{AllPerso}{%
          \RedactionReciPythagore%
          \RedactionCalculsReciPythagore%
          \RedactionConclusionReciPythagore%
        }{%
          \ifboolKV[ClesPythagore]{Perso}{\RedactionReciPythagore}{%
            Dans le triangle $#2$, $[\NomA\NomC]$ est le plus grand c\^ot\'e.%
          }
          \ifboolKV[ClesPythagore]{ReciColonnes}{%
            \[
              \begin{array}{cccc|cccc}
                &&\NomA\NomC^2&&&\NomA\NomB^2&+&\NomB\NomC^2\\
                &&\opexport{A1}{\Aun}\num{\Aun}^2&&&\opexport{A2}{\Adeux}\num{\Adeux}^2&+&\opexport{A3}{\Atrois}\num{\Atrois}^2\\
                &&\opmul*{A1}{A1}{a1}&&&\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}&+&\opmul*{A3}{A3}{a3}\opexport{a3}{\Atrois}\num{\Atrois}\\
                &&\opexport{a1}{\Aun}\num{\Aun}&&&\multicolumn{3}{c}{\opadd*{a2}{a3}{a4}\opexport{a4}{\Aquatre}\num{\Aquatre}}\\
              \end{array}
            \]
          }{%
            \[\left.
                \begin{array}{l}
                  \NomA\NomC^2=\opexport{A1}{\Aun}\num{\Aun}^2=\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}\\
                  \\
                  \NomA\NomB^2+\NomB\NomC^2=\opexport{A2}{\Adeux}\num{\Adeux}^2+\opexport{A3}{\Atrois}\num{\Atrois}^2=\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}+\opmul*{A3}{A3}{a3}\opexport{a3}{\Atrois}\num{\Atrois}=\opadd*{a2}{a3}{a4}\opexport{a4}{\Aquatre}\num{\Aquatre}\\
                \end{array}
              \right\}\opcmp{a1}{a4}\ifopeq\NomA\NomC^2=\NomA\NomB^2+\NomB\NomC^2\fi\opcmp{a1}{a4}\ifopneq\NomA\NomC^2\not=\NomA\NomB^2+\NomB\NomC^2\fi
            \]
          }%
          \ifboolKV[ClesPythagore]{Egalite}{%
            \opcmp{a1}{a4}\ifopeq Comme $\NomA\NomC^2=\NomA\NomB^2+\NomB\NomC^2$, alors l'\'egalit\'e de Pythagore est v\'erifi\'ee. Donc le triangle $#2$ est rectangle en $\NomB$.\fi%
            \opcmp{a1}{a4}\ifopneq Comme $\NomA\NomC^2\not=\NomA\NomB^2+\NomB\NomC^2$, alors l'\'egalit\'e de Pythagore n'est pas v\'erifi\'ee. Donc le triangle $#2$ n'est pas rectangle.\fi%
          }{%
            \opcmp{a1}{a4}\ifopeq Comme $\NomA\NomC^2=\NomA\NomB^2+\NomB\NomC^2$, alors le triangle $#2$ est rectangle
            en $\NomB$ d'apr\`es la r\'eciproque du th\'eor\`eme de Pythagore.\fi%
            \opcmp{a1}{a4}\ifopneq Comme $\NomA\NomC^2\not=\NomA\NomB^2+\NomB\NomC^2$, alors le
            triangle $#2$ n'est pas rectangle\ifboolKV[ClesPythagore]{Faible}{.}{ d'apr\`es la contrapos\'ee du th\'eor\`eme de Pythagore.}\fi%
          }%
        }%
      }%
    }%
  }{%
    % [xlop] param\`etres de calcul
    \opcopy{#3}{A1}%
    \opcopy{#4}{A2}%
    \opcopy{\useKV[ClesPythagore]{Precision}}{pres}%
    \xintifboolexpr{#3<#4 || #3==#4}{
      \xdef\PetitCote{#3}%
      \xdef\MoyenCote{#4}%
      \xdef\GrandCote{}%
    }{%
      \xdef\GrandCote{#3}%
      \xdef\MoyenCote{#4}%
      \xdef\PetitCote{}% Pour la personnalisation
    }
    % On retient les noms des sommets
    \StrMid{#2}{1}{1}[\NomA]%
    \StrMid{#2}{2}{2}[\NomB]%
    \StrMid{#2}{3}{3}[\NomC]%
    \xdef\NomTriangle{\NomA\NomB\NomC}%
    \xdef\NomAngleDroit{\NomB}%
    \xdef\NomSommetA{\NomA}%
    \xdef\NomSommetC{\NomC}%
    % On trace une figure ou pas ?
    \ifboolKV[ClesPythagore]{FigureSeule}{%
      \xintifboolexpr{#3<#4 || #3==#4}{%\ifnum#3<#4%
        \xdef\ResultatPytha{\fpeval{round(sqrt(#3^2+#4^2),\useKV[ClesPythagore]{Precision})}}%
      }{%
        \xdef\ResultatPytha{\fpeval{round(sqrt(#3^2-#4^2),\useKV[ClesPythagore]{Precision})}}%
      }%
      \MPFigurePytha{\NomA}{\NomB}{\NomC}{#3}{#4}{\useKV[ClesPythagore]{Angle}}
    }{%
      \ifboolKV[ClesPythagore]{Figure}{%Utilisation obligatoire de l'option --shell-escape de la compilation
        \begin{multicols}{2}%
          {\em La figure est donn\'ee \`a titre indicatif.}%
          \[\MPFigurePytha{\NomA}{\NomB}{\NomC}{#3}{#4}{\useKV[ClesPythagore]{Angle}}\]
          \par\columnbreak\par%
          % On d\'emarre la r\'esolution
          \ifboolKV[ClesPythagore]{AllPerso}{%
            \RedactionPythagore%
            \RedactionCalculsPythagore%
          }{%
            \ifboolKV[ClesPythagore]{Perso}{%
              \RedactionCalculsPythagore%
            }{%
              \ifboolKV[ClesPythagore]{Egalite}{Comme le triangle $#2$ est rectangle en $\NomB$, alors l'\'egalit\'e de Pythagore est v\'erifi\'ee :}{Dans le triangle $#2$ rectangle en $\NomB$, le th\'eor\`eme de Pythagore permet d'\'ecrire :%
              }%
            }
            \xintifboolexpr{#3<#4 || #3==#4}{%\ifnum#3<#4%
              \xdef\ResultatPytha{\fpeval{round(sqrt(#3^2+#4^2),\useKV[ClesPythagore]{Precision})}}%
              \begin{align*}
                \NomA\NomC^2&=\NomA\NomB^2+\NomB\NomC^2\\
                \NomA\NomC^2&=\ifboolKV[ClesPythagore]{EnchaineA}{\opcopy{\useKV[ClesPythagore]{ValeurA}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opexport{A1}{\Aun}\num{\Aun}^2}+\ifboolKV[ClesPythagore]{EnchaineB}{\opcopy{\useKV[ClesPythagore]{ValeurB}}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}{\opexport{A2}{\Adeux}\num{\Adeux}^2}\\
                \NomA\NomC^2&=\ifboolKV[ClesPythagore]{EnchaineA}{\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}+\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                \NomA\NomC^2&=\opadd*{a1}{a2}{a3}\opexport{a3}{\Atrois}\num{\Atrois}%\\
              \ifboolKV[ClesPythagore]{AvantRacine}{}{%
              \ifboolKV[ClesPythagore]{Entier}{}{\\\NomA\NomC&=\sqrt{\opexport{a3}{\Atrois}\num{\Atrois}}}
                                                               \ifboolKV[ClesPythagore]{Racine}{}{\\\ifboolKV[ClesPythagore]{Exact}{\NomA\NomC&=\opsqrt[maxdivstep=3]{a3}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}{\NomA\NomC&\approx\opsqrt[maxdivstep=5]{a3}{a4}\opround{a4}{pres}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}}%\\
                }%
              \end{align*}
            }{%\else%
              \xdef\ResultatPytha{\fpeval{round(sqrt(#3^2-#4^2),\useKV[ClesPythagore]{Precision})}}%
              \begin{align*}
                \NomA\NomC^2&=\NomA\NomB^2+\NomB\NomC^2\\
                \ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opexport{A1}{\Aun}\num{\Aun}^2}&=\NomA\NomB^2+\ifboolKV[ClesPythagore]{EnchaineB}{\opcopy{\useKV[ClesPythagore]{ValeurB}}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}{\opexport{A2}{\Adeux}\num{\Adeux}^2}\\
                \ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}&=\NomA\NomB^2+\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                \NomA\NomB^2&=\ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}-\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                \NomA\NomB^2&=\opsub*{a1}{a2}{a3}\opexport{a3}{\Atrois}\num{\Atrois}%\\
                \ifboolKV[ClesPythagore]{AvantRacine}{}{%
                \ifboolKV[ClesPythagore]{Entier}{}{\\\NomA\NomB&=\sqrt{\opexport{a3}{\Atrois}\num{\Atrois}}}
                                                                 \ifboolKV[ClesPythagore]{Racine}{}{\\\ifboolKV[ClesPythagore]{Exact}{\NomA\NomB&=\opsqrt[maxdivstep=3]{a3}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}{\NomA\NomB&\approx\opsqrt[maxdivstep=5]{a3}{a4}\opround{a4}{pres}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}}%\\
                }%
              \end{align*}
            }%\fi%
          }
        \end{multicols}
      }{%
        % On d\'emarre la r\'esolution
        \ifboolKV[ClesPythagore]{SansMots}{%
         \MPFigurePythaSansMots{\NomA}{\NomB}{\NomC}{#3}{#4}{\useKV[ClesPythagore]{Angle}}%
        }{%
          \ifboolKV[ClesPythagore]{AllPerso}{%
            \RedactionPythagore%
            \RedactionCalculsPythagore%
          }{%
            \ifboolKV[ClesPythagore]{Perso}{\RedactionPythagore}{\ifboolKV[ClesPythagore]{Egalite}{Comme le triangle $#2$ est rectangle en $\NomB$, alors l'\'egalit\'e de Pythagore est v\'erifi\'ee :}{Dans le triangle $#2$ rectangle en $\NomB$, le th\'eor\`eme de Pythagore permet d'\'ecrire :%
              }}%
            \xintifboolexpr{#3<#4 || #3==#4}{%\ifnum#3<#4%
              \xdef\ResultatPytha{\fpeval{round(sqrt(#3^2+#4^2),\useKV[ClesPythagore]{Precision})}}%
              \begin{align*}
                \NomA\NomC^2&=\NomA\NomB^2+\NomB\NomC^2\\
                \NomA\NomC^2&=\ifboolKV[ClesPythagore]{EnchaineA}{\opcopy{\useKV[ClesPythagore]{ValeurA}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opexport{A1}{\Aun}\num{\Aun}^2}+\ifboolKV[ClesPythagore]{EnchaineB}{\opcopy{\useKV[ClesPythagore]{ValeurB}}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}{\opexport{A2}{\Adeux}\num{\Adeux}^2}\\
                \NomA\NomC^2&=\ifboolKV[ClesPythagore]{EnchaineA}{\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}+\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                \NomA\NomC^2&=\opadd*{a1}{a2}{a3}\opexport{a3}{\Atrois}\num{\Atrois}%\\
                \ifboolKV[ClesPythagore]{AvantRacine}{}{%
                \ifboolKV[ClesPythagore]{Entier}{}{\\\NomA\NomC&=\sqrt{\opexport{a3}{\Atrois}\num{\Atrois}}}
                                                                 \ifboolKV[ClesPythagore]{Racine}{}{\\\ifboolKV[ClesPythagore]{Exact}{\NomA\NomC&=\opsqrt[maxdivstep=3]{a3}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}{\NomA\NomC&\approx\opsqrt[maxdivstep=5]{a3}{a4}\opround{a4}{pres}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}}%\\
                }
              \end{align*}
            }{%\else
              \xdef\ResultatPytha{\fpeval{round(sqrt(#3^2-#4^2),\useKV[ClesPythagore]{Precision})}}%
              \ifboolKV[ClesPythagore]{Soustraction}{%
                \begin{align*}
                  \NomA\NomB^2&=\NomA\NomC^2-\NomB\NomC^2\\
                  \NomA\NomB^2&=\ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opexport{A1}{\Aun}\num{\Aun}^2}-\ifboolKV[ClesPythagore]{EnchaineB}{\opcopy{\useKV[ClesPythagore]{ValeurB}}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}{\opexport{A2}{\Adeux}\num{\Adeux}^2}\\
                  \NomA\NomB^2&=\ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}-\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                  \NomA\NomB^2&=\opsub*{a1}{a2}{a3}\opexport{a3}{\Atrois}\num{\Atrois}%\\
                  \ifboolKV[ClesPythagore]{AvantRacine}{}{%
                  \ifboolKV[ClesPythagore]{Entier}{}{\\\NomA\NomB&=\sqrt{\opexport{a3}{\Atrois}\num{\Atrois}}}
                                                                   \ifboolKV[ClesPythagore]{Racine}{}{\\\ifboolKV[ClesPythagore]{Exact}{\NomA\NomB&=\opsqrt[maxdivstep=3]{a3}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}{\NomA\NomB&\approx\opsqrt[maxdivstep=5]{a3}{a4}\opround{a4}{pres}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}}%\\
                  }
                \end{align*}
              }{%
                \begin{align*}
                  \NomA\NomC^2&=\NomA\NomB^2+\NomB\NomC^2\\
                  \ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opexport{A1}{\Aun}\num{\Aun}^2}&=\NomA\NomB^2+\ifboolKV[ClesPythagore]{EnchaineB}{\opcopy{\useKV[ClesPythagore]{ValeurB}}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}{\opexport{A2}{\Adeux}\num{\Adeux}^2}\\
                  \ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}&=\NomA\NomB^2+\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                  \NomA\NomB^2&=\ifboolKV[ClesPythagore]{EnchaineC}{\opcopy{\useKV[ClesPythagore]{ValeurC}}{a1}\opexport{a1}{\Aun}\num{\Aun}}{\opmul*{A1}{A1}{a1}\opexport{a1}{\Aun}\num{\Aun}}-\ifboolKV[ClesPythagore]{EnchaineB}{\opexport{a2}{\Adeux}\num{\Adeux}}{\opmul*{A2}{A2}{a2}\opexport{a2}{\Adeux}\num{\Adeux}}\\
                  \NomA\NomB^2&=\opsub*{a1}{a2}{a3}\opexport{a3}{\Atrois}\num{\Atrois}%\\
                  \ifboolKV[ClesPythagore]{AvantRacine}{}{%
                  \ifboolKV[ClesPythagore]{Entier}{}{\\\NomA\NomB&=\sqrt{\opexport{a3}{\Atrois}\num{\Atrois}}}%
                                                                   \ifboolKV[ClesPythagore]{Racine}{}{\\\ifboolKV[ClesPythagore]{Exact}{\NomA\NomB&=\opsqrt[maxdivstep=3]{a3}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}{\NomA\NomB&\approx\opsqrt[maxdivstep=5]{a3}{a4}\opround{a4}{pres}{a4}\opunzero{a4}\opexport{a4}{\Aquatre}\SI{\Aquatre}{\PfCPythaUnit}}}%\\
                  }
                \end{align*}
              }%
            }%\fi%
          }%
        }%
      }%
    }%
  }%
}%

%%%
% Distributivit\'e
%%%
% https://tex.stackexchange.com/questions/168972/draw-arrows-to-show-multiplication-pattern-distributive-property/169278?noredirect=1 
\newcommand\Tikzmark[1]{%
  \tikz[remember picture,baseline,inner sep=0pt]{%
    \node[name=Distri-\theNbDistri,anchor=base] {${#1}$};}%
  \stepcounter{NbDistri}%
}%

\newcommand\DrawArrow{%
  \begin{tikzpicture}[overlay,remember picture]
    \draw[-stealth,out=50,in=140,DCFlechesh,transform canvas={yshift=2pt}] (Distri-0.north) to (Distri-2.north);
    \draw[-stealth,out=50,in=140,DCFlechesh!50,transform canvas={yshift=2pt}] (Distri-0.north) to (Distri-3.north);
    \draw[-stealth,out=-50,in=-140,DCFlechesb,transform canvas={yshift=-2pt}] (Distri-1.south) to (Distri-2.south);
    \draw[-stealth,out=-50,in=-140,DCFlechesb!50,transform canvas={yshift=-2pt}] (Distri-1.south) to (Distri-3.south);
  \end{tikzpicture}
}

\newcommand\DrawArrowSimple[1]{%
  \begin{tikzpicture}[overlay,remember picture]
    \draw[-stealth,out=50,in=140,DCFlechesh,transform canvas={yshift=2pt}] (Distri-#1.north) to (Distri-2.north);
    \draw[-stealth,out=50,in=140,DCFlechesh!50,transform canvas={yshift=2pt}] (Distri-#1.north) to (Distri-3.north);
  \end{tikzpicture}
}

\newcommand\DrawArrowSimpleRenverse[1]{%
  \begin{tikzpicture}[overlay,remember picture]
    \draw[-stealth,out=140,in=50,DCFlechesh,transform canvas={yshift=2pt}] (Distri-#1.north) to (Distri-0.north);
    \draw[-stealth,out=140,in=50,DCFlechesh!50,transform canvas={yshift=2pt}] (Distri-#1.north) to (Distri-1.north);
  \end{tikzpicture}
}

\newcounter{NbDistri}%
\setcounter{NbDistri}{0}%

\newcounter{NbCalculDistri}%Pour compter combien de distributivit\'e il
% y a dans un "seul calcul".
\setcounter{NbCalculDistri}{0}

\setKVdefault[ClesDistributivite]{Cours=false,Etape=1,Lettre=x,Fleches=false,AideMul=false,Reduction=false,AideAdda=false,AideAddb=false,CouleurAide=red,CouleurReduction=black,CouleurFH=blue,CouleurFB=red,Somme=false,Difference=false,RAZ=false,Oppose=false,All=false,NomExpression=A,Fin=4,Numerique=false,Remarquable=false,Echange=0,Tuile=false,Vide=false,Impression=false,Tableau=false}%,AideAdd=false:inutile ?

\newcommand\Tuile[4]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    boolean Vide,Print;
    Vide=\useKV[ClesDistributivite]{Vide};
    Print=\useKV[ClesDistributivite]{Impression};
    pair _CoinTuilev;
    _CoinTuilev=(0,0);
    numeric largeur,longueur,ecart;
    largeur=0.75;
    longueur=sqrt(3);
    ecart=0.6;
    pair _CoinTuileh;
    _CoinTuileh=u*(largeur+ecart,ecart);
    vardef tuilev(expr LL,ll,nb,col)(text t)=
    save $; picture $;
    save TT; picture TT;
    TT=image(
    path cc;
    cc=polygone((0,0),u*(LL,0),u*(LL,-ll),u*(0,-ll));
    if Print=false:
    fill cc withcolor col;
    fi;
    trace cc;
    label(TEX(t),iso((0,0),u*(LL,0),u*(LL,-ll),u*(0,-ll)));
    );
    $=image(
    for k=0 upto nb-1:
    trace TT shifted(_CoinTuilev+k*u*(0,-ll));
    endfor;
    _CoinTuilev:=_CoinTuilev shifted(nb*u*(0,-ll));
    );
    $
    enddef;
    vardef tuileh(expr LL,ll,nb,col)(text t)=
    save $; picture $;
    picture TT;
    TT=image(
    path cc;
    cc=polygone((0,0),u*(LL,0),u*(LL,ll),u*(0,ll));
    if Print=false:
    fill cc withcolor col;
    fi;
    trace cc;
    label(TEX(t),iso((0,0),u*(LL,0),u*(LL,ll),u*(0,ll)));
    );
    $=image(
    for k=0 upto nb-1:
    trace TT shifted(_CoinTuileh+k*u*(LL,0));
    endfor;
    _CoinTuileh:=_CoinTuileh shifted(nb*u*(LL,0));
    );
    $
    enddef;
    color ColorLetter,ColorLetterPos,ColorLetterNeg,ColorNum,ColorNumPos,ColorNumNeg,ColorCarrePos,ColorCarreNeg;
    ColorLetter=LightGreen;
    ColorLetterPos=ColorLetter;
    ColorLetterNeg=Tomato;
    ColorNum=Orange;
    ColorNumPos=ColorNum;
    ColorNumNeg=Tomato;
    ColorCarrePos:=LightBlue;
    ColorCarreNeg:=Tomato;
    if #1<0:
    ColorLetter:=Tomato;
    trace tuilev(largeur,longueur,abs(#1),ColorLetter)("$-x$");
    else:
    ColorLetter:=LightGreen;
    trace tuilev(largeur,longueur,abs(#1),ColorLetter)("$x$");
    fi;
    if #2<0:
    ColorNum:=Tomato;
    trace tuilev(largeur,largeur,abs(#2),ColorNum)("$-1$");
    else:
    ColorNum:=Orange;
    trace tuilev(largeur,largeur,abs(#2),ColorNum)("$1$");
    fi;
    if #3<0:
    ColorLetter:=Tomato;
    trace tuileh(longueur,largeur,abs(#3),ColorLetter)("$-x$");
    else:
    ColorLetter:=LightGreen;
    trace tuileh(longueur,largeur,abs(#3),ColorLetter)("$x$");
    fi;
    if #4<0:
    ColorNum:=Tomato;
    trace tuileh(largeur,largeur,abs(#4),ColorNum)("$-1$");
    else:
    ColorNum:=Orange;
    trace tuileh(largeur,largeur,abs(#4),ColorNum)("$1$");
    fi;
    trace u*(largeur+ecart/2,largeur+ecart)--((largeur+ecart/2)*u,ypart(_CoinTuilev)) withpen pencircle scaled2;
    trace u*(0,ecart/2)--(xpart(_CoinTuileh),u*(ecart/2)) withpen pencircle scaled2;
    drawarrow u*(largeur/2,ecart/2){dir90}..{dir0}u*(largeur+ecart/2,largeur/2+ecart) withpen pencircle scaled2;
    labeloffset:=labeloffset*2;
    label.ulft(TEX("$\times$"),iso(u*(largeur/2,ecart/2),u*(largeur+ecart/2,largeur/2+ecart)));
    labeloffset:=labeloffset/2;
    if Vide=false:
    %% tuile a*c
    if #1*#3<>0:
    for k=0 upto (abs(#3)-1):
    for l=0 upto (abs(#1)-1):
    path titi;
    titi=polygone((0,0),u*(longueur,0),u*(longueur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart,0)+(u*(k*longueur,-l*longueur)));
    if Print=false:
    fill titi withcolor if #1*#3>0:ColorCarrePos else: ColorCarreNeg fi;
    fi;
    trace titi;
    if #1*#3>0:
    label(TEX("$x^2$"),iso((0,0),u*(longueur,0),u*(longueur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart,0)+(u*(k*longueur,-l*longueur))));
    else:
    label(TEX("$-x^2$"),iso((0,0),u*(longueur,0),u*(longueur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart,0)+(u*(k*longueur,-l*longueur))));
    fi;
    endfor;
    endfor;
    fi;
    %tuile a*d
    if #1*#4<>0:
    for k=0 upto (abs(#4)-1):
    for l=0 upto (abs(#1)-1):
    path titi;
    titi=polygone((0,0),u*(largeur,0),u*(largeur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart+abs(#3)*longueur,0)+(u*(k*largeur,-l*longueur)));
    if Print=false:
    fill titi withcolor if #1*#4>0:ColorLetterPos else: ColorLetterNeg fi;
    fi;
    trace titi;
    if #1*#4>0:
    label(TEX("$x$"),iso((0,0),u*(largeur,0),u*(largeur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart+abs(#3)*longueur,0)+(u*(k*largeur,-l*longueur))));
    else:
    label(TEX("$-x$"),iso((0,0),u*(largeur,0),u*(largeur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart+abs(#3)*longueur,0)+(u*(k*largeur,-l*longueur))));
    fi;
    endfor;
    endfor;
    fi;
    %tuile b*c
    if #2*#3<>0:
    for k=0 upto (abs(#3)-1):
    for l=0 upto (abs(#2)-1):
    path titi;
    titi=polygone((0,0),u*(longueur,0),u*(longueur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart,-abs(#1)*longueur)+(u*(k*longueur,-l*largeur)));
    if Print=false:
    fill titi withcolor if #2*#3>0:ColorLetterPos else: ColorLetterNeg fi;
    fi;
    trace titi;
    if #2*#3>0:
    label(TEX("$x$"),iso((0,0),u*(longueur,0),u*(longueur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart,-abs(#1)*longueur)+(u*(k*longueur,-l*largeur))));
    else:
    label(TEX("$-x$"),iso((0,0),u*(longueur,0),u*(longueur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart,-abs(#1)*longueur)+(u*(k*longueur,-l*largeur))));
    fi;
    endfor;
    endfor;
    fi;
    %tuile b*d
    if #2*#4<>0:
    for k=0 upto (abs(#4)-1):
    for l=0 upto (abs(#2)-1):
    path titi;
    titi=polygone((0,0),u*(largeur,0),u*(largeur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart+abs(#3)*longueur,-abs(#1)*longueur)+(u*(k*largeur,-l*largeur)));
    if Print=false:
    fill titi withcolor if #2*#4>0:ColorNumPos else: ColorNumNeg fi;
    fi;
    trace titi;
    if #2*#4>0:
    label(TEX("$1$"),iso((0,0),u*(largeur,0),u*(largeur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart+abs(#3)*longueur,-abs(#1)*longueur)+(u*(k*largeur,-l*largeur))));
    else:
    label(TEX("$-1$"),iso((0,0),u*(largeur,0),u*(largeur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart+abs(#3)*longueur,-abs(#1)*longueur)+(u*(k*largeur,-l*largeur))));
    fi;
    endfor;
    endfor;
    fi;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={boolean Vide,Print; Vide=\useKV[ClesDistributivite]{Vide}; Print=\useKV[ClesDistributivite]{Impression};}]
    pair _CoinTuilev;
    _CoinTuilev=(0,0);
    numeric largeur,longueur,ecart;
    largeur=0.75;
    longueur=sqrt(3);
    ecart=0.6;
    pair _CoinTuileh;
    _CoinTuileh=u*(largeur+ecart,ecart);
    vardef tuilev(expr LL,ll,nb,col)(text t)=
    save $; picture $;
    save TT; picture TT;
    TT=image(
    path cc;
    cc=polygone((0,0),u*(LL,0),u*(LL,-ll),u*(0,-ll));
    if Print=false:
    fill cc withcolor col;
    fi;
    trace cc;
    label(LATEX(t),iso((0,0),u*(LL,0),u*(LL,-ll),u*(0,-ll)));
    );
    $=image(
    for k=0 upto nb-1:
    trace TT shifted(_CoinTuilev+k*u*(0,-ll));
    endfor;
    _CoinTuilev:=_CoinTuilev shifted(nb*u*(0,-ll));
    );
    $
    enddef;
    vardef tuileh(expr LL,ll,nb,col)(text t)=
    save $; picture $;
    picture TT;
    TT=image(
    path cc;
    cc=polygone((0,0),u*(LL,0),u*(LL,ll),u*(0,ll));
    if Print=false:
    fill cc withcolor col;
    fi;
    trace cc;
    label(LATEX(t),iso((0,0),u*(LL,0),u*(LL,ll),u*(0,ll)));
    );
    $=image(
    for k=0 upto nb-1:
    trace TT shifted(_CoinTuileh+k*u*(LL,0));
    endfor;
    _CoinTuileh:=_CoinTuileh shifted(nb*u*(LL,0));
    );
    $
    enddef;
    color ColorLetter,ColorLetterPos,ColorLetterNeg,ColorNum,ColorNumPos,ColorNumNeg,ColorCarrePos,ColorCarreNeg;
    ColorLetter=LightGreen;
    ColorLetterPos=ColorLetter;
    ColorLetterNeg=Tomato;
    ColorNum=Orange;
    ColorNumPos=ColorNum;
    ColorNumNeg=Tomato;
    ColorCarrePos:=LightBlue;
    ColorCarreNeg:=Tomato;
    if #1<0:
    ColorLetter:=Tomato;
    trace tuilev(largeur,longueur,abs(#1),ColorLetter)("$-x$");
    else:
    ColorLetter:=LightGreen;
    trace tuilev(largeur,longueur,abs(#1),ColorLetter)("$x$");
    fi;
    if #2<0:
    ColorNum:=Tomato;
    trace tuilev(largeur,largeur,abs(#2),ColorNum)("$-1$");
    else:
    ColorNum:=Orange;
    trace tuilev(largeur,largeur,abs(#2),ColorNum)("$1$");
    fi;
    if #3<0:
    ColorLetter:=Tomato;
    trace tuileh(longueur,largeur,abs(#3),ColorLetter)("$-x$");
    else:
    ColorLetter:=LightGreen;
    trace tuileh(longueur,largeur,abs(#3),ColorLetter)("$x$");
    fi;
    if #4<0:
    ColorNum:=Tomato;
    trace tuileh(largeur,largeur,abs(#4),ColorNum)("$-1$");
    else:
    ColorNum:=Orange;
    trace tuileh(largeur,largeur,abs(#4),ColorNum)("$1$");
    fi;
    trace u*(largeur+ecart/2,largeur+ecart)--((largeur+ecart/2)*u,ypart(_CoinTuilev)) withpen pencircle scaled2;
    trace u*(0,ecart/2)--(xpart(_CoinTuileh),u*(ecart/2)) withpen pencircle scaled2;
    drawarrow u*(largeur/2,ecart/2){dir90}..{dir0}u*(largeur+ecart/2,largeur/2+ecart) withpen pencircle scaled2;
    labeloffset:=labeloffset*2;
    label.ulft(LATEX("$\times$"),iso(u*(largeur/2,ecart/2),u*(largeur+ecart/2,largeur/2+ecart)));
    labeloffset:=labeloffset/2;
    if Vide=false:
    %% tuile a*c
    if #1*#3<>0:
    for k=0 upto (abs(#3)-1):
    for l=0 upto (abs(#1)-1):
    path titi;
    titi=polygone((0,0),u*(longueur,0),u*(longueur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart,0)+(u*(k*longueur,-l*longueur)));
    if Print=false:
    fill titi withcolor if #1*#3>0:ColorCarrePos else: ColorCarreNeg fi;
    fi;
    trace titi;
    if #1*#3>0:
    label(LATEX("$x^2$"),iso((0,0),u*(longueur,0),u*(longueur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart,0)+(u*(k*longueur,-l*longueur))));
    else:
    label(LATEX("$-x^2$"),iso((0,0),u*(longueur,0),u*(longueur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart,0)+(u*(k*longueur,-l*longueur))));
    fi;
    endfor;
    endfor;
    fi;
    %tuile a*d
    if #1*#4<>0:
    for k=0 upto (abs(#4)-1):
    for l=0 upto (abs(#1)-1):
    path titi;
    titi=polygone((0,0),u*(largeur,0),u*(largeur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart+abs(#3)*longueur,0)+(u*(k*largeur,-l*longueur)));
    if Print=false:
    fill titi withcolor if #1*#4>0:ColorLetterPos else: ColorLetterNeg fi;
    fi;
    trace titi;
    if #1*#4>0:
    label(LATEX("$x$"),iso((0,0),u*(largeur,0),u*(largeur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart+abs(#3)*longueur,0)+(u*(k*largeur,-l*longueur))));
    else:
    label(LATEX("$-x$"),iso((0,0),u*(largeur,0),u*(largeur,-longueur),u*(0,-longueur)) shifted (u*(largeur+ecart+abs(#3)*longueur,0)+(u*(k*largeur,-l*longueur))));
    fi;
    endfor;
    endfor;
    fi;
    %tuile b*c
    if #2*#3<>0:
    for k=0 upto (abs(#3)-1):
    for l=0 upto (abs(#2)-1):
    path titi;
    titi=polygone((0,0),u*(longueur,0),u*(longueur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart,-abs(#1)*longueur)+(u*(k*longueur,-l*largeur)));
    if Print=false:
    fill titi withcolor if #2*#3>0:ColorLetterPos else: ColorLetterNeg fi;
    fi;
    trace titi;
    if #2*#3>0:
    label(LATEX("$x$"),iso((0,0),u*(longueur,0),u*(longueur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart,-abs(#1)*longueur)+(u*(k*longueur,-l*largeur))));
    else:
    label(LATEX("$-x$"),iso((0,0),u*(longueur,0),u*(longueur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart,-abs(#1)*longueur)+(u*(k*longueur,-l*largeur))));
    fi;
    endfor;
    endfor;
    fi;
    %tuile b*d
    if #2*#4<>0:
    for k=0 upto (abs(#4)-1):
    for l=0 upto (abs(#2)-1):
    path titi;
    titi=polygone((0,0),u*(largeur,0),u*(largeur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart+abs(#3)*longueur,-abs(#1)*longueur)+(u*(k*largeur,-l*largeur)));
    if Print=false:
    fill titi withcolor if #2*#4>0:ColorNumPos else: ColorNumNeg fi;
    fi;
    trace titi;
    if #2*#4>0:
    label(LATEX("$1$"),iso((0,0),u*(largeur,0),u*(largeur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart+abs(#3)*longueur,-abs(#1)*longueur)+(u*(k*largeur,-l*largeur))));
    else:
    label(LATEX("$-1$"),iso((0,0),u*(largeur,0),u*(largeur,-largeur),u*(0,-largeur)) shifted (u*(largeur+ecart+abs(#3)*longueur,-abs(#1)*longueur)+(u*(k*largeur,-l*largeur))));
    fi;
    endfor;
    endfor;
    fi;
    fi;
  \end{mpost}
  \fi
}

\newcommand\Affichage[4][]{%
  \setKV[ClesDistributivite]{#1}%On lit les arguments optionnels
  \def\LETTRE{\useKV[ClesDistributivite]{Lettre}}%
  \ensuremath{%
    % partie du x^2
    \xintifboolexpr{#2==0}{}{\xintifboolexpr{#2==1}{}{\xintifboolexpr{#2==-1}{-}{\num{#2}}}\LETTRE^2}%
    % partie du x
    \xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{\xintifboolexpr{#2==0}{}{+}\xintifboolexpr{#3==1}{}{\num{#3}}}{%
        \xintifboolexpr{#2==0}{\xintifboolexpr{#3==-1}{-}{\num{#3}}}{\xintifboolexpr{#3==-1}{-}{-\num{\fpeval{abs(#3)}}}}%
      }\LETTRE}%
    % partie du nombre
    \xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{\xintifboolexpr{#2==0}{\xintifboolexpr{#3==0}{}{+}}{+}\num{#4}}{%
        \xintifboolexpr{#2==0}{\xintifboolexpr{#3==0}{\num{#4}}{-\num{\fpeval{abs(#4)}}}}{-\num{\fpeval{abs(#4)}}}}}%
    % 
  }%
}%

\xdef\SommeA{0}%
\xdef\SommeB{0}%
\xdef\SommeC{0}%

\newcommand\Distri[5][]{%
  \useKVdefault[ClesDistributivite]%obligatoire car la macro n'est pas dans un groupe.
  \setKV[ClesDistributivite]{#1}%On lit les arguments optionnels
  \ifboolKV[ClesDistributivite]{RAZ}{\xdef\SommeA{0}\xdef\SommeB{0}\xdef\SommeC{0}%
    \setcounter{NbCalculDistri}{0}%
  }{}%
  \colorlet{DCAide}{\useKV[ClesDistributivite]{CouleurAide}}%
  \colorlet{DCReduction}{\useKV[ClesDistributivite]{CouleurReduction}}%
  \colorlet{DCFlechesh}{\useKV[ClesDistributivite]{CouleurFH}}%
  \colorlet{DCFlechesb}{\useKV[ClesDistributivite]{CouleurFB}}%
  \ifboolKV[ClesDistributivite]{Cours}{%
    \ensuremath{%
      \xintifboolexpr{#2==0}{%
      }{\xintifboolexpr{#3==0}{}{(}}\xintifboolexpr{#2==0}{\Tikzmark{}}{\Tikzmark{a}}
      \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{+(}}{}%
      \xintifboolexpr{#3==0}{\Tikzmark{}}{\xintifboolexpr{#3>0}{\xintifboolexpr{#2==0}{}{+}}{\xintifboolexpr{#3<0}{-}{}}\Tikzmark{b}}%
      \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{)}}{}%
      \xintifboolexpr{#2==0}{}{\xintifboolexpr{#3==0}{}{)}}%
      % 
      \ifboolKV[ClesDistributivite]{AideMul}{\times}{}%on aide dans le cas double
      \xdef\Multi{\fpeval{#4*#5}}%affichage auto si (a+b)xk
      % 
      \xintifboolexpr{\Multi==0}{\times%
        \xintifboolexpr{#4<0}{(}{\xintifboolexpr{#5<0}{(}{}}}{(}%
      \Tikzmark{c}%
      \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{+(}}{}%
      \xintifboolexpr{#5>0}{\xintifboolexpr{#4==0}{}{+}}{\xintifboolexpr{#5<0}{\xintifboolexpr{#4==0}{{-}}{-}}{}}\Tikzmark{d}%
      \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{)}}{}%
      \xintifboolexpr{\Multi==0}{%
        \xintifboolexpr{#4<0}{)}{\xintifboolexpr{#5<0}{)}{}}}{)}%
      %
      =
      %
      \xdef\Multi{\fpeval{#2*#4}}%
      \xintifboolexpr{\Multi==0}{}{%
        \xintifboolexpr{#2<0}{(-}{}a\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#4<0}{(-}{}c\xintifboolexpr{#4<0}{)}{}%
      }
      \xdef\Multij{\fpeval{#2*#5}}%
      \xintifboolexpr{\Multij==0}{}{%
        \xintifboolexpr{\Multi==0}{}{+}%
        \xintifboolexpr{#2<0}{(-}{}a\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#5<0}{(-}{}d\xintifboolexpr{#5<0}{)}{}%
      }%
      \xdef\Multik{\fpeval{#3*#4}}%
      \xintifboolexpr{\Multik==0}{}{%
        \xintifboolexpr{\Multi==0}{}{+}%
        \xintifboolexpr{#3<0}{(-}{}b\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#4<0}{(-}{}c\xintifboolexpr{#4<0}{)}{}%
      }%
      \xdef\Multil{\fpeval{#3*#5}}%
      \xintifboolexpr{\Multil==0}{}{+%
        \xintifboolexpr{#3<0}{(-}{}b\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#5<0}{(-}{}d\xintifboolexpr{#5<0}{)}{}%
      }%
      % Fleches
      \ifboolKV[ClesDistributivite]{Fleches}{%
        \xdef\Multi{\fpeval{#2*#3*#4*#5}}%
        \xintifboolexpr{\Multi==0}{%
          \xdef\Multij{\fpeval{#2*#3}}%\relax
          \xintifboolexpr{\Multij==0}{\xintifboolexpr{#2==0}{\DrawArrowSimple{1}
            }{\DrawArrowSimple{0}}}{\xintifboolexpr{#4==0}{\DrawArrowSimpleRenverse{3}}{\DrawArrowSimpleRenverse{2}}}%
        }{%
          \DrawArrow%
        }%
      }{}\setcounter{NbDistri}{0}%
    }%
  }{%
    \ifboolKV[ClesDistributivite]{Tuile}{%
      \Tuile{#2}{#3}{#4}{#5}%
    }{%
      \ifboolKV[ClesDistributivite]{Tableau}{%
        \DistriTableau[#1]{#2}{#3}{#4}{#5}%
      }{%
        \ensuremath{%
          \xintifboolexpr{\useKV[ClesDistributivite]{Echange}>0}{%
            \DistriEchange[#1]{#2}{#3}{#4}{#5}%
          }{%
            \ifboolKV[ClesDistributivite]{Remarquable}{%
              \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==1}{%
                \ifx\bla#4\bla(\Affichage{0}{#2}{#3})^2\else(\Affichage{0}{#2}{#3})(\Affichage{0}{#4}{#5})\fi%
              }{}
              \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==2}{\ifx\bla#4\bla\xintifboolexpr{#3>0}{\xintifboolexpr{#2==1}{}{(\num{#2}}\useKV[ClesDistributivite]{Lettre}\xintifboolexpr{#2==1}{}{)}^2+2\times\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesDistributivite]{Lettre}\times\num{#3}+\num{#3}^2}{\xintifboolexpr{#2==1}{}{(\num{#2}}\useKV[ClesDistributivite]{Lettre}\xintifboolexpr{#2==1}{}{)}^2-2\times\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesDistributivite]{Lettre}\times\num{\fpeval{0-#3}}+\num{\fpeval{0-#3}}^2}\else\xintifboolexpr{#2==1}{}{(\num{#2}}\useKV[ClesDistributivite]{Lettre}\xintifboolexpr{#2==1}{}{)}^2-\num{#3}^2\fi}{}
              \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==3}{%
                \xintifboolexpr{\theNbCalculDistri>1}{\setcounter{NbCalculDistri}{0}}{}%
                \stepcounter{NbCalculDistri}%
                \ifx\bla#4\bla%
                \xdef\Multi{\fpeval{#2*#2}}%
                \xdef\Multij{\fpeval{#2*#3}}%
                \xdef\Multik{\fpeval{#3*#2}}%
                \xdef\Multil{\fpeval{#3*#3}}%
                %% ils sont red\'efinis pour pouvoir envisager la somme de deux
                %% expressions \`a d\'evelopper
                \xdef\Multim{\fpeval{#2*#3+#3*#2}}%
                \ifboolKV[ClesDistributivite]{Oppose}{%
                  \xdef\Multi{\fpeval{-\Multi}}%
                  \xdef\Multim{\fpeval{-\Multim}}%
                  \xdef\Multil{\fpeval{-\Multil}}%
                  \xintifboolexpr{\Multi==0}{}{\xintifboolexpr{\Multi<0}{(}{}\Affichage{\Multi}{0}{0}\xintifboolexpr{\Multi<0}{)}{}}%
                  \xintifboolexpr{\Multim==0}{}{\xintifboolexpr{\Multim>0}{+}{+(}\Affichage{0}{\Multim}{0}\xintifboolexpr{\Multim<0}{)}{}}%
                  \xintifboolexpr{\Multil==0}{}{\xintifboolexpr{\Multil>0}{+}{+(}\Affichage{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}}%
                }{%
                  \Affichage{\Multi}{\Multim}{\Multil}%
                }
                \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+#2*#2}}\xdef\SommeB{\fpeval{\SommeB+#2*#3+#3*#2}}\xdef\SommeC{\fpeval{\SommeC+#3*#3}}}{}%
                \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-#2*#2}}\xdef\SommeB{\fpeval{\SommeB-#2*#3-#3*#2}}\xdef\SommeC{\fpeval{\SommeC-#3*#3}}}{}%
                \else%
                \xdef\Multi{\fpeval{#2*#4}}%
                \xdef\Multij{\fpeval{#2*#5}}%
                \xdef\Multik{\fpeval{#3*#4}}%
                \xdef\Multil{\fpeval{#3*#5}}%
                %% ils sont red\'efinis pour pouvoir envisager la somme de deux
                %% expressions \`a d\'evelopper
                \xdef\Multim{\fpeval{#2*#5+#3*#4}}%
                \ifboolKV[ClesDistributivite]{Oppose}{%
                  \xdef\Multi{\fpeval{-\Multi}}%
                  \xdef\Multim{\fpeval{-\Multim}}%
                  \xdef\Multil{\fpeval{-\Multil}}%
                  \xintifboolexpr{\Multi==0}{}{\xintifboolexpr{\Multi<0}{(}{}\Affichage{\Multi}{0}{0}\xintifboolexpr{\Multi<0}{)}{}}%
                  \xintifboolexpr{\Multim==0}{}{\xintifboolexpr{\Multim>0}{+}{+(}\Affichage{0}{\Multim}{0}\xintifboolexpr{\Multim<0}{)}{}}%
                  \xintifboolexpr{\Multil==0}{}{\xintifboolexpr{\Multil>0}{+}{+(}\Affichage{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}}%
                }{%
                  \Affichage{\Multi}{\Multim}{\Multil}%
                }
                \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+#2*#4}}\xdef\SommeB{\fpeval{\SommeB+#2*#5+#3*#4}}\xdef\SommeC{\fpeval{\SommeC+#3*#5}}}{}%
                \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-#2*#4}}\xdef\SommeB{\fpeval{\SommeB-#2*#5-#3*#4}}\xdef\SommeC{\fpeval{\SommeC-#3*#5}}}{}%
                \fi%
              }{}%
            }{%
              \ifboolKV[ClesDistributivite]{Numerique}{%
                \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==0}{%
                  \num{\fpeval{#2+#3}}\times\num{\fpeval{#4+#5}}\multido{\i=2+1}{4}{=\Distri[Numerique,Etape=\i]{#2}{#3}{#4}{#5}}%
                }{%
                  \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==-1}{%
                    \Distri[Numerique,Etape=3]{#2}{#3}{#4}{#5}\multido{\i=2+-1}{2}{=\Distri[Numerique,Etape=\i]{#2}{#3}{#4}{#5}}=\num{\fpeval{(#2+#3)*(#4+#5)}}%
                  }{%
                    \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==1}{\num{\fpeval{#2+#3}}\times\num{\fpeval{#4+#5}}}{}%
                    \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==2}{\num{\fpeval{#2+#3}}\times(\num{#4}\xintifboolexpr{#5>0}{+}{-}\num{\fpeval{abs(#5)}})}{}%
                    \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==3}{\num{#3}\times\num{#4}\xintifboolexpr{#5>0}{+}{-}\num{#3}\times\num{\fpeval{abs(#5)}}}{}%
                    \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==4}{\num{\fpeval{#3*#4}}\xintifboolexpr{#5>0}{+}{-}\num{\fpeval{abs(#3*#5)}}}{}%
                    \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==5}{\num{\fpeval{#3*#4+#3*#5}}}{}%
                  }%
                }%
              }{%
                \ifboolKV[ClesDistributivite]{All}{%
                  \xdef\NomLettre{\useKV[ClesDistributivite]{NomExpression}}%
                  \xdef\NomFin{\useKV[ClesDistributivite]{Fin}}%
                  \xdef\NomVariable{\useKV[ClesDistributivite]{Lettre}}%
                  \xintFor* ##1 in {\xintSeq {1}{\useKV[ClesDistributivite]{Fin}-1}}\do
                  {\NomLettre&=\Distri[Etape=##1,Lettre=\NomVariable]{#2}{#3}{#4}{#5}\\}%
                  \NomLettre&=\Distri[Etape=\NomFin,Lettre=\NomVariable]{#2}{#3}{#4}{#5}%
                }{%
                  % Etape 1
                  \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==1}{%
                    \xintifboolexpr{#2==0}{%
                    }{\xintifboolexpr{#3==0}{}{(}}\Tikzmark{\Affichage[#1]{0}{#2}{0}}%
                    \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{+(}}{}%
                    \xintifboolexpr{#3>0}{\xintifboolexpr{#2==0}{}{+}}{\xintifboolexpr{#3<0}{-}{}}\Tikzmark{\Affichage[#1]{0}{0}{\fpeval{abs(#3)}}}%
                    \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{)}}{}%
                    \xintifboolexpr{#2==0}{}{\xintifboolexpr{#3==0}{}{)}}%
                    % 
                    \ifboolKV[ClesDistributivite]{AideMul}{\times}{}%on aide dans le cas double
                    \xdef\Multi{\fpeval{#4*#5}}%affichage auto si (a+b)xk
                    % 
                    \xintifboolexpr{\Multi==0}{\times%
                      \xintifboolexpr{#4<0}{(}{\xintifboolexpr{#5<0}{(}{}}}{(}%
                    \Tikzmark{\Affichage[#1]{0}{#4}{0}}%
                    \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{+(}}{}%
                    \xintifboolexpr{#5>0}{\xintifboolexpr{#4==0}{}{+}}{\xintifboolexpr{#5<0}{\xintifboolexpr{#4==0}{{-}}{-}}{}}\Tikzmark{\Affichage[#1]{0}{0}{\fpeval{abs(#5)}}}%
                    \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{)}}{}%
                    \xintifboolexpr{\Multi==0}{%
                      \xintifboolexpr{#4<0}{)}{\xintifboolexpr{#5<0}{)}{}}}{)}%
                    \ifboolKV[ClesDistributivite]{Fleches}{%
                      \xdef\Multi{\fpeval{#2*#3*#4*#5}}%
                      \xintifboolexpr{\Multi==0}{%
                        \xdef\Multij{\fpeval{#2*#3}}%\relax
                        \xintifboolexpr{\Multij==0}{\xintifboolexpr{#2==0}{\DrawArrowSimple{1}}{\DrawArrowSimple{0}}}{\xintifboolexpr{#4==0}{\DrawArrowSimpleRenverse{3}}{\DrawArrowSimpleRenverse{2}}}%
                      }{%
                        \DrawArrow%
                      }%
                    }{}\setcounter{NbDistri}{0}%
                  }{}
                  % Etape 2
                  \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==2}{%
                    \xdef\Multi{\fpeval{#2*#4}}%
                    \xintifboolexpr{\Multi==0}{}{%
                      \xintifboolexpr{#2<0}{(}{}\Affichage[#1]{0}{#2}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\Affichage[#1]{0}{#4}{0}\xintifboolexpr{#4<0}{)}{}%
                    }
                    \xdef\Multij{\fpeval{#2*#5}}%
                    \xintifboolexpr{\Multij==0}{}{%
                      \xintifboolexpr{\Multi==0}{}{+}%
                      \xintifboolexpr{#2<0}{(}{}\Affichage[#1]{0}{#2}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\Affichage[#1]{0}{0}{#5}\xintifboolexpr{#5<0}{)}{}%
                    }%
                    \xdef\Multik{\fpeval{#3*#4}}%
                    \xintifboolexpr{\Multik==0}{}{%
                      \xintifboolexpr{\Multi==0}{}{+}%
                      \xintifboolexpr{#3<0}{(}{}\Affichage[#1]{0}{0}{#3}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\Affichage[#1]{0}{#4}{0}\xintifboolexpr{#4<0}{)}{}%
                    }%
                    \xdef\Multil{\fpeval{#3*#5}}%
                    \xintifboolexpr{\Multil==0}{}{+%
                      \xintifboolexpr{#3<0}{(}{}\Affichage[#1]{0}{0}{#3}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\Affichage[#1]{0}{0}{#5}\xintifboolexpr{#5<0}{)}{}%
                    }%
                  }{}%
                  % Etape 3
                  \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==3}{%
                    \stepcounter{NbCalculDistri}%
                    \xdef\Multi{\fpeval{#2*#4}}%
                    \xdef\Multij{\fpeval{#2*#5}}%
                    \xdef\Multik{\fpeval{#3*#4}}%
                    \xdef\Multil{\fpeval{#3*#5}}%
                    %% ils sont red\'efinis pour pouvoir envisager la somme de deux
                    %% expressions \`a d\'evelopper
                    \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multi<0}{(\Affichage{\Multi}{0}{0})}{\Affichage{\Multi}{0}{0}}}{\Affichage{\Multi}{0}{0}}%
                    \ifboolKV[ClesDistributivite]{Reduction}{\mathunderline{DCReduction}{%
                        \xintifboolexpr{\Multij==0}{}{\xintifboolexpr{\Multi==0}{}{{}+}\xintifboolexpr{\Multij<0}{(}{}\Affichage{0}{\Multij}{0}\xintifboolexpr{\Multij<0}{)}{}}%
                        \xintifboolexpr{\Multik==0}{}{\xintifboolexpr{\Multil==0}{\xintifboolexpr{#2==0}{}{+}}{+}\xintifboolexpr{\Multik<0}{(}{}\Affichage{0}{\Multik}{0}\xintifboolexpr{\Multik<0}{)}{}}%
                      }%
                    }{%
                      \xintifboolexpr{\Multij==0}{}{\xintifboolexpr{\Multi==0}{}{+}\xintifboolexpr{\Multij<0}{(}{}\Affichage{0}{\Multij}{0}\xintifboolexpr{\Multij<0}{)}{}}%
                      \xintifboolexpr{\Multik==0}{}{\xintifboolexpr{\Multil==0}{\xintifboolexpr{#2==0}{}{+}}{\xintifboolexpr{#2==0}{}{+}}\xintifboolexpr{\Multik<0}{(}{}\Affichage{0}{\Multik}{0}\xintifboolexpr{\Multik<0}{)}{}}%
                    }%
                    \xintifboolexpr{\Multil==0}{}{+}\xintifboolexpr{\Multil<0}{(}{}\Affichage{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}%
                  }{}%
                  % Etape 4
                  \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==4}{%
                    \xdef\Multi{\fpeval{#2*#4}}%
                    \xdef\Multij{\fpeval{#2*#5}}%
                    \xdef\Multik{\fpeval{#3*#4}}%
                    \xdef\Multil{\fpeval{#3*#5}}%
                    %% ils sont red\'efinis pour pouvoir envisager la somme de deux
                    %% expressions \`a d\'evelopper
                    \xdef\Multim{\fpeval{#2*#5+#3*#4}}%
                    \xintifboolexpr{\theNbCalculDistri>1}{\setcounter{NbCalculDistri}{0}}{}%
                    \stepcounter{NbCalculDistri}%
                    \ifboolKV[ClesDistributivite]{Oppose}{%
                      \xdef\Multi{\fpeval{-\Multi}}%
                      \xdef\Multim{\fpeval{-\Multim}}%
                      \xdef\Multil{\fpeval{-\Multil}}%
                      \xintifboolexpr{\Multi==0}{}{\xintifboolexpr{\Multi<0}{(}{}\Affichage{\Multi}{0}{0}\xintifboolexpr{\Multi<0}{)}{}}%
                      \xintifboolexpr{\Multim==0}{}{\xintifboolexpr{\Multim>0}{+}{+(}\Affichage{0}{\Multim}{0}\xintifboolexpr{\Multim<0}{)}{}}%
                      \xintifboolexpr{\Multil==0}{}{\xintifboolexpr{\Multil>0}{+}{+(}\Affichage{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}}%
                    }{%
                      \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multi<0}{(\Affichage{\Multi}{0}{0})}{\Affichage{\Multi}{0}{0}}}{\Affichage{\Multi}{0}{0}}%
                      \xintifboolexpr{\Multim==0}{}{%
                        \xintifboolexpr{\Multim>0}{+\Affichage{0}{\Multim}{0}}{-\Affichage{0}{\fpeval{-\Multim}}{0}}%
                      }%
                      \xintifboolexpr{\Multil==0}{}{\xintifboolexpr{\Multil<0}{-\Affichage{0}{0}{\fpeval{-\Multil}}}{+\Affichage{0}{0}{\Multil}}}%
                    }
                    \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+#2*#4}}\xdef\SommeB{\fpeval{\SommeB+#2*#5+#3*#4}}\xdef\SommeC{\fpeval{\SommeC+#3*#5}}}{}%
                    \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-#2*#4}}\xdef\SommeB{\fpeval{\SommeB-#2*#5-#3*#4}}\xdef\SommeC{\fpeval{\SommeC-#3*#5}}}{}%
                  }{}%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\newcommand\DistriTableau[5][]{%
  \useKVdefault[ClesDistributivite]%
  \setKV[ClesDistributivite]{#1}%
  \ensuremath{%
    \begin{array}{|>{\columncolor{gray!15}}c|c|c|}
      \hline
      \rowcolor{gray!15}\times&\Affichage[#1]{0}{#4}{0}&\Affichage[#1]{0}{0}{#5}\\
      \hline
      \xintifboolexpr{#2==0}{}{\Affichage[#1]{0}{#2}{0}&\Affichage[#1]{\fpeval{#2*#4}}{0}{0}&\xintifboolexpr{\fpeval{#2*#5}>0}{+}{}\Affichage[#1]{0}{\fpeval{#2*#5}}{0}\\
      \hline}%
      \xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+}{}\Affichage[#1]{0}{0}{#3}&\xintifboolexpr{\fpeval{#3*#4}>0}{+}{}\Affichage[#1]{0}{\fpeval{#3*#4}}{0}&\xintifboolexpr{\fpeval{#3*#5}>0}{+}{}\Affichage[#1]{0}{0}{\fpeval{#3*#5}}\\
      \hline}
    \end{array}
  }%
}%

\newcommand\Resultat[1][]{%
  \setKV[ClesDistributivite]{#1}%On lit les arguments optionnels
  \ensuremath{%
    \Affichage{\SommeA}{\SommeB}{\SommeC}
  }%
}

\newcommand\AffichageEchange[4][]{%
  \setKV[ClesDistributivite]{#1}%On lit les arguments optionnels
  \def\LETTRE{\useKV[ClesDistributivite]{Lettre}}%
  \ensuremath{%
    % partie du nombre
    \xintifboolexpr{#2==0}{}{\num{#2}}%
    % partie du x
    \xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{\xintifboolexpr{#2==0}{}{+}\xintifboolexpr{#3==1}{}{\num{#3}}}{%
        \xintifboolexpr{#2==0}{\xintifboolexpr{#3==-1}{-}{\num{#3}}}{\xintifboolexpr{#3==-1}{-}{-\num{\fpeval{abs(#3)}}}}
      }\LETTRE}%
    % partie du x^2
    \xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{\xintifboolexpr{#2==0}{\xintifboolexpr{#3==0}{}{+}}{+}\xintifboolexpr{#4==1}{}{\num{#4}}}{%
        \xintifboolexpr{#2==0}{\xintifboolexpr{#3==0}{\num{#4}}{-\num{\fpeval{abs(#4)}}}}{-\num{\fpeval{abs(#4)}}}}\LETTRE^2}%
  }%
}%

\newcommand\DistriEchange[5][]{%
  \ensuremath{%
    \useKVdefault[ClesDistributivite]%
    \setKV[ClesDistributivite]{#1}%
    \ifboolKV[ClesDistributivite]{RAZ}{\xdef\SommeA{0}\xdef\SommeB{0}\xdef\SommeC{0}%
      \setcounter{NbCalculDistri}{0}%
    }{}%
    \colorlet{DCAide}{\useKV[ClesDistributivite]{CouleurAide}}%
    \colorlet{DCReduction}{\useKV[ClesDistributivite]{CouleurReduction}}%
    \colorlet{DCFlechesh}{\useKV[ClesDistributivite]{CouleurFH}}%
    \colorlet{DCFlechesb}{\useKV[ClesDistributivite]{CouleurFB}}%
    \ifboolKV[ClesDistributivite]{Remarquable}{%
      \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==1}{\ifx\bla#4\bla(\AffichageEchange{#2}{#3}{0})^2\else(\AffichageEchange{#2}{#3}{0})(\AffichageEchange{#4}{#5}{0})\fi
      }{}
      \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==2}{%
        \ifx\bla#4\bla\xintifboolexpr{#3>0}{%
          \num{#2}^2+2\times\num{#2}\times\xintifboolexpr{#3==1}{}{\num{#3}}\useKV[ClesDistributivite]{Lettre}+
          \xintifboolexpr{#3==1}{}{(\num{#3}}\useKV[ClesDistributivite]{Lettre}\xintifboolexpr{#3==1}{}{)}^2%
        }{%
          \num{#2}^2-2\times\num{#2}\times\xintifboolexpr{#3==-1}{}{\num{\fpeval{0-#3}}}\useKV[ClesDistributivite]{Lettre}+
          \xintifboolexpr{#3==-1}{}{(\num{\fpeval{0-#3}}}\useKV[ClesDistributivite]{Lettre}\xintifboolexpr{#3==-1}{}{)}^2%
        }%
        \else\num{#2}^2-\xintifboolexpr{#3==1}{}{(\num{#3}}\useKV[ClesDistributivite]{Lettre}\xintifboolexpr{#3==1}{}{)}^2%
        \fi%
      }{}
      \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==3}{%
        \xintifboolexpr{\theNbCalculDistri>1}{\setcounter{NbCalculDistri}{0}}{}%
        \stepcounter{NbCalculDistri}%
        \ifx\bla#4\bla%
        \xdef\Multi{\fpeval{#2*#2}}%
        \xdef\Multij{\fpeval{#2*#3}}%
        \xdef\Multik{\fpeval{#3*#2}}%
        \xdef\Multil{\fpeval{#3*#3}}%
        %% ils sont red\'efinis pour pouvoir envisager la somme de deux
        %% expressions \`a d\'evelopper
        \xdef\Multim{\fpeval{#2*#3+#3*#2}}%
        \ifboolKV[ClesDistributivite]{Oppose}{%
          \xdef\Multi{\fpeval{-\Multi}}%
          \xdef\Multim{\fpeval{-\Multim}}%
          \xdef\Multil{\fpeval{-\Multil}}%
          \xintifboolexpr{\Multi==0}{}{\xintifboolexpr{\Multi<0}{(}{}\AffichageEchange{\Multi}{0}{0}\xintifboolexpr{\Multi<0}{)}{}}%
          \xintifboolexpr{\Multim==0}{}{\xintifboolexpr{\Multim>0}{+}{+(}\AffichageEchange{0}{\Multim}{0}\xintifboolexpr{\Multim<0}{)}{}}%
          \xintifboolexpr{\Multil==0}{}{\xintifboolexpr{\Multil>0}{+}{+(}\AffichageEchange{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}}%
        }{%
          \AffichageEchange{\Multi}{\Multim}{\Multil}%
        }
        \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+#3*#3}}\xdef\SommeB{\fpeval{\SommeB+#2*#3+#3*#2}}\xdef\SommeC{\fpeval{\SommeC+#2*#2}}}{}%
        \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-#3*#3}}\xdef\SommeB{\fpeval{\SommeB-#2*#3-#3*#2}}\xdef\SommeC{\fpeval{\SommeC-#2*#2}}}{}%
        \else%
        \xdef\Multi{\fpeval{#2*#4}}%
        \xdef\Multij{\fpeval{#2*#5}}%
        \xdef\Multik{\fpeval{#3*#4}}%
        \xdef\Multil{\fpeval{#3*#5}}%
        %% ils sont red\'efinis pour pouvoir envisager la somme de deux
        %% expressions \`a d\'evelopper
        \xdef\Multim{\fpeval{#2*#5+#3*#4}}%
        \ifboolKV[ClesDistributivite]{Oppose}{%
          \xdef\Multi{\fpeval{-\Multi}}%
          \xdef\Multim{\fpeval{-\Multim}}%
          \xdef\Multil{\fpeval{-\Multil}}%
          \xintifboolexpr{\Multi==0}{}{\xintifboolexpr{\Multi<0}{(}{}\AffichageEchange{\Multi}{0}{0}\xintifboolexpr{\Multi<0}{)}{}}%
          \xintifboolexpr{\Multim==0}{}{\xintifboolexpr{\Multim>0}{+}{+(}\AffichageEchange{0}{\Multim}{0}\xintifboolexpr{\Multim<0}{)}{}}%
          \xintifboolexpr{\Multil==0}{}{\xintifboolexpr{\Multil>0}{+}{+(}\AffichageEchange{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}}%
        }{%
          \AffichageEchange{\Multi}{\Multim}{\Multil}%
        }
        % \`a faire
        \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+#3*#5}}\xdef\SommeB{\fpeval{\SommeB+#2*#5+#3*#4}}\xdef\SommeC{\fpeval{\SommeC+#2*#4}}}{}%
        \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-#3*#5}}\xdef\SommeB{\fpeval{\SommeB-#2*#5-#3*#4}}\xdef\SommeC{\fpeval{\SommeC-#2*#4}}}{}%
        % 
        \fi%
      }{}%
    }{%
      \ifboolKV[ClesDistributivite]{Numerique}{%
      }{%
        \ifboolKV[ClesDistributivite]{All}{%
           \xdef\NomLettre{\useKV[ClesDistributivite]{NomExpression}}%
           \xdef\NomFin{\useKV[ClesDistributivite]{Fin}}%
           \xdef\ValeurEchange{\useKV[ClesDistributivite]{Echange}}
           \xintFor* ##1 in {\xintSeq {1}{\useKV[ClesDistributivite]{Fin}-1}}\do
           {\NomLettre&=\DistriEchange[Echange=\ValeurEchange,Etape=##1]{#2}{#3}{#4}{#5}\\}%
           \NomLettre&=\DistriEchange[Echange=\ValeurEchange,Etape=\NomFin]{#2}{#3}{#4}{#5}%
        }{%
          % Etape 1
          \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==1}{%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==1||\useKV[ClesDistributivite]{Echange}==3}{%
              \xintifboolexpr{#2==0}{%
              }{\xintifboolexpr{#3==0}{%
                }{(}}\Tikzmark{\Affichage[#1]{0}{0}{#2}}%
              \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{+(}}{}%
              \xintifboolexpr{#3>0}{\xintifboolexpr{#2==0}{}{+}}{\xintifboolexpr{#3<0}{-}{}}\Tikzmark{\Affichage[#1]{0}{\fpeval{abs(#3)}}{0}}%
              \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{)}}{}%
              \xintifboolexpr{#2==0}{%
              }{\xintifboolexpr{#3==0}{%
                }{)}}%
            }{
              \xintifboolexpr{#2==0}{%
              }{\xintifboolexpr{#3==0}{%
                }{(}}\Tikzmark{\Affichage[#1]{0}{#2}{0}}%
              \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{+(}}{}%
              \xintifboolexpr{#3>0}{\xintifboolexpr{#2==0}{}{+}}{\xintifboolexpr{#3<0}{-}{}}\Tikzmark{\Affichage[#1]{0}{0}{\fpeval{abs(#3)}}}%
              \ifboolKV[ClesDistributivite]{AideAdda}{\mathcolor{DCAide}{)}}{}%
              \xintifboolexpr{#2==0}{%
              }{\xintifboolexpr{#3==0}{%
                }{)}}%
            }%
            % 
            \ifboolKV[ClesDistributivite]{AideMul}{\times}{}%on aide dans le cas double
            \xdef\Multi{\fpeval{#4*#5}}%affichage auto si (a+b)xk
            % 
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==2||\useKV[ClesDistributivite]{Echange}==3}{%
              \xintifboolexpr{\Multi==0}{\times%
                \xintifboolexpr{#4<0}{(}{\xintifboolexpr{#5<0}{(}{}}}{(}%
              \Tikzmark{\AffichageEchange[#1]{#4}{0}{0}}%
              \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{+(}}{}%
              \xintifboolexpr{#5>0}{\xintifboolexpr{#4==0}{}{+}}{\xintifboolexpr{#5<0}{-}{}}\Tikzmark{\AffichageEchange[#1]{0}{\fpeval{abs(#5)}}{0}}%
              \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{)}}{}%
              \xintifboolexpr{\Multi==0}{%
                \xintifboolexpr{#4<0}{)}{\xintifboolexpr{#5<0}{)}{}}}{)}%
            }{%
              \xintifboolexpr{\Multi==0}{\times%
                \xintifboolexpr{#4<0}{(}{\xintifboolexpr{#5<0}{(}{}}}{(}%
              \Tikzmark{\Affichage[#1]{0}{#4}{0}}%
              \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{+(}}{}%
              \xintifboolexpr{#5>0}{\xintifboolexpr{#4==0}{}{+}}{\xintifboolexpr{#5<0}{\xintifboolexpr{#4==0}{{-}}{-}}{}}\Tikzmark{\Affichage[#1]{0}{0}{\fpeval{abs(#5)}}}%
              \ifboolKV[ClesDistributivite]{AideAddb}{\mathcolor{DCAide}{)}}{}%
              \xintifboolexpr{\Multi==0}{%
                \xintifboolexpr{#4<0}{)}{\xintifboolexpr{#5<0}{)}{}}}{)}%
            }%
             \ifboolKV[ClesDistributivite]{Fleches}{%
             \xdef\Multi{\fpeval{#2*#3*#4*#5}}%
             \xintifboolexpr{\Multi==0}{%
             \xdef\Multij{\fpeval{#2*#3}}%\relax
             \xintifboolexpr{\Multij==0}{\xintifboolexpr{#2==0}{\DrawArrowSimple{1}}{\DrawArrowSimple{0}}}{\xintifboolexpr{#4==0}{\DrawArrowSimpleRenverse{3}}{\DrawArrowSimpleRenverse{2}}}
             }{%
               \DrawArrow
             }%
             }{}\setcounter{NbDistri}{0}%
          }{}%
          % Etape 2
          \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==2}{%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==1}{%
              \xdef\Multi{\fpeval{#2*#4}}%
              \xintifboolexpr{\Multi==0}{}{%
                \xintifboolexpr{#2<0}{(}{}\AffichageEchange[#1]{#2}{0}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\Affichage[#1]{0}{#4}{0}\xintifboolexpr{#4<0}{)}{}%
              }%
              \xdef\Multij{\fpeval{#2*#5}}%
              \xintifboolexpr{\Multij==0}{}{%
                \xintifboolexpr{\Multi==0}{}{+}%
                \xintifboolexpr{#2<0}{(}{}\AffichageEchange[#1]{#2}{0}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\Affichage[#1]{0}{0}{#5}\xintifboolexpr{#5<0}{)}{}%
              }%
              \xdef\Multik{\fpeval{#3*#4}}%
              \xintifboolexpr{\Multik==0}{}{%
                \xintifboolexpr{\Multi==0}{}{+}%
                \xintifboolexpr{#3<0}{(}{}\AffichageEchange[#1]{0}{#3}{0}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\Affichage[#1]{0}{#4}{0}\xintifboolexpr{#4<0}{)}{}%
              }%
              \xdef\Multil{\fpeval{#3*#5}}%
              \xintifboolexpr{\Multil==0}{}{+%
                \xintifboolexpr{#3<0}{(}{}\AffichageEchange[#1]{0}{#3}{0}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\Affichage[#1]{0}{0}{#5}\xintifboolexpr{#5<0}{)}{}%
              }%
            }{}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==2}{%
              \xdef\Multi{\fpeval{#2*#4}}%
              \xintifboolexpr{\Multi==0}{}{%
                \xintifboolexpr{#2<0}{(}{}\Affichage[#1]{0}{#2}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\AffichageEchange[#1]{#4}{0}{0}\xintifboolexpr{#4<0}{)}{}%
              }%
              \xdef\Multij{\fpeval{#2*#5}}%
              \xintifboolexpr{\Multij==0}{}{%
                \xintifboolexpr{\Multi==0}{}{+}%
                \xintifboolexpr{#2<0}{(}{}\Affichage[#1]{0}{#2}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\AffichageEchange[#1]{0}{#5}{0}\xintifboolexpr{#5<0}{)}{}%
              }%
              \xdef\Multik{\fpeval{#3*#4}}%
              \xintifboolexpr{\Multik==0}{}{%
                \xintifboolexpr{\Multi==0}{}{+}%
                \xintifboolexpr{#3<0}{(}{}\Affichage[#1]{0}{0}{#3}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\AffichageEchange[#1]{#4}{0}{0}\xintifboolexpr{#4<0}{)}{}%
              }%
              \xdef\Multil{\fpeval{#3*#5}}%
              \xintifboolexpr{\Multil==0}{}{+%
                \xintifboolexpr{#3<0}{(}{}\Affichage[#1]{0}{0}{#3}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\AffichageEchange[#1]{0}{#5}{0}\xintifboolexpr{#5<0}{)}{}%
              }%
            }{}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==3}{%
              \xdef\Multi{\fpeval{#2*#4}}%
              \xintifboolexpr{\Multi==0}{}{%
                \xintifboolexpr{#2<0}{(}{}\AffichageEchange[#1]{#2}{0}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\AffichageEchange[#1]{#4}{0}{0}\xintifboolexpr{#4<0}{)}{}%
              }%
              \xdef\Multij{\fpeval{#2*#5}}%
              \xintifboolexpr{\Multij==0}{}{%
                \xintifboolexpr{\Multi==0}{}{+}%
                \xintifboolexpr{#2<0}{(}{}\AffichageEchange[#1]{#2}{0}{0}\xintifboolexpr{#2<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\AffichageEchange[#1]{0}{#5}{0}\xintifboolexpr{#5<0}{)}{}%
              }%
              \xdef\Multik{\fpeval{#3*#4}}%
              \xintifboolexpr{\Multik==0}{}{%
                \xintifboolexpr{\Multi==0}{}{+}%
                \xintifboolexpr{#3<0}{(}{}\AffichageEchange[#1]{0}{#3}{0}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#4<0}{(}{}\AffichageEchange[#1]{#4}{0}{0}\xintifboolexpr{#4<0}{)}{}%
              }%
              \xdef\Multil{\fpeval{#3*#5}}%
              \xintifboolexpr{\Multil==0}{}{+%
                \xintifboolexpr{#3<0}{(}{}\AffichageEchange[#1]{0}{#3}{0}\xintifboolexpr{#3<0}{)}{}\times\xintifboolexpr{#5<0}{(}{}\AffichageEchange[#1]{0}{#5}{0}\xintifboolexpr{#5<0}{)}{}%
              }%
            }{}
          }{}          
          % Etape 3
          \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==3}{%
            \stepcounter{NbCalculDistri}%
            \xdef\Multi{\fpeval{#2*#4}}%
            \xdef\Multij{\fpeval{#2*#5}}%
            \xdef\Multik{\fpeval{#3*#4}}%
            \xdef\Multil{\fpeval{#3*#5}}%
            %% ils sont red\'efinis pour pouvoir envisager la somme de deux
            %% expressions \`a d\'evelopper
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==1}{%
            \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multi<0}{(\AffichageEchange{0}{\Multi}{0})}{\AffichageEchange{0}{\Multi}{0}}}{\AffichageEchange{0}{\Multi}{0}}%
              \xintifboolexpr{\Multij==0}{}{\xintifboolexpr{\Multi==0}{}{+}\xintifboolexpr{\Multij<0}{(}{}\AffichageEchange{\Multij}{0}{0}\xintifboolexpr{\Multij<0}{)}{}}%
              \xintifboolexpr{\Multik==0}{}{\xintifboolexpr{\Multil==0}{\xintifboolexpr{#2=0}{}{+}}{+}\xintifboolexpr{\Multik<0}{(}{}\AffichageEchange{0}{0}{\Multik}\xintifboolexpr{\Multik<0}{)}{}}%
              \xintifboolexpr{\Multil==0}{}{+}\xintifboolexpr{\Multil<0}{(}{}\AffichageEchange{0}{\Multil}{0}\xintifboolexpr{\Multil<0}{)}{}%
              \xdef\Multim{\fpeval{#2*#4+#3*#5}}%              
              \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+\Multik}}\xdef\SommeB{\fpeval{\SommeB+\Multim}}\xdef\SommeC{\fpeval{\SommeC+\Multij}}}{}%
              \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-\Multik}}\xdef\SommeB{\fpeval{\SommeB-\Multim}}\xdef\SommeC{\fpeval{\SommeC-\Multij}}}{}%              
            }{}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==2}{%
            \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multi<0}{(\AffichageEchange{0}{\Multi}{0})}{\AffichageEchange{0}{\Multi}{0}}}{\AffichageEchange{0}{\Multi}{0}}%
              \xintifboolexpr{\Multij==0}{}{\xintifboolexpr{\Multi==0}{}{+}\xintifboolexpr{\Multij<0}{(}{}\AffichageEchange{0}{0}{\Multij}\xintifboolexpr{\Multij<0}{)}{}}%
              \xintifboolexpr{\Multik==0}{}{\xintifboolexpr{\Multil==0}{\xintifboolexpr{#2==0}{}{+}}{+}\xintifboolexpr{\Multik<0}{(}{}\AffichageEchange{\Multik}{0}{0}\xintifboolexpr{\Multik<0}{)}{}}%
              \xintifboolexpr{\Multil==0}{}{+}\xintifboolexpr{\Multil<0}{(}{}\AffichageEchange{0}{\Multil}{0}\xintifboolexpr{\Multil<0}{)}{}%
              \xdef\Multim{\fpeval{#2*#4+#3*#5}}%
              \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+\Multij}}\xdef\SommeB{\fpeval{\SommeB+\Multim}}\xdef\SommeC{\fpeval{\SommeC+\Multik}}}{}%
              \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-\Multij}}\xdef\SommeB{\fpeval{\SommeB-\Multim}}\xdef\SommeC{\fpeval{\SommeC-\Multik}}}{}%
            }{}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==3}{%
            \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multi<0}{(\AffichageEchange{\Multi}{0}{0})}{\AffichageEchange{\Multi}{0}{0}}}{\AffichageEchange{\Multi}{0}{0}}%
              \xintifboolexpr{\Multij==0}{}{\xintifboolexpr{\Multi==0}{}{+}\xintifboolexpr{\Multij<0}{(}{}\AffichageEchange{0}{\Multij}{0}\xintifboolexpr{\Multij<0}{)}{}}%
              \xintifboolexpr{\Multik==0}{}{\xintifboolexpr{\Multil==0}{\xintifboolexpr{#2==0}{}{+}}{+}\xintifboolexpr{\Multik<0}{(}{}\AffichageEchange{0}{\Multik}{0}\xintifboolexpr{\Multik<0}{)}{}}%
              \xintifboolexpr{\Multil==0}{}{+}\xintifboolexpr{\Multil<0}{(}{}\AffichageEchange{0}{0}{\Multil}\xintifboolexpr{\Multil<0}{)}{}%
              \xdef\Multim{\fpeval{#2*#5+#3*#4}}%
              \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+\Multil}}\xdef\SommeB{\fpeval{\SommeB+\Multim}}\xdef\SommeC{\fpeval{\SommeC+\Multi}}}{}%
              \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-\Multil}}\xdef\SommeB{\fpeval{\SommeB-\Multim}}\xdef\SommeC{\fpeval{\SommeC-\Multi}}}{}%
            }{}%
          }{}%fin etape3
          % Etape 4
          \xintifboolexpr{\useKV[ClesDistributivite]{Etape}==4}{%
            \xdef\Multi{\fpeval{#2*#4}}%
            \xdef\Multij{\fpeval{#2*#5}}%
            \xdef\Multik{\fpeval{#3*#4}}%
            \xdef\Multil{\fpeval{#3*#5}}%
            %% ils sont red\'efinis pour pouvoir envisager la somme de deux
            %% expressions \`a d\'evelopper
            % \xintifboolexpr{\theNbCalculDistri>1}{\setcounter{NbCalculDistri}{0}}{}%
            %\stepcounter{NbCalculDistri}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==1}{%
              \xdef\Multim{\fpeval{#2*#4+#3*#5}}%
              \ifboolKV[ClesDistributivite]{Oppose}{%
                \xdef\Multiko{\fpeval{-\Multik}}%
                \xdef\Multimo{\fpeval{-\Multim}}%
                \xdef\Multijo{\fpeval{-\Multij}}%
                 \xintifboolexpr{\Multiko==0}{}{\xintifboolexpr{\Multiko<0}{(}{}\Affichage{\Multiko}{0}{0}\xintifboolexpr{\Multiko<0}{)}{}}%
                 \xintifboolexpr{\Multimo==0}{}{\xintifboolexpr{\Multimo>0}{+}{+(}\Affichage{0}{\Multimo}{0}\xintifboolexpr{\Multimo<0}{)}{}}%
                 \xintifboolexpr{\Multijo==0}{}{\xintifboolexpr{\Multijo>0}{+}{+(}\Affichage{0}{0}{\Multijo}\xintifboolexpr{\Multijo<0}{)}{}}%
              }{%
                \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multik<0}{(\Affichage{\Multik}{0}{0})}{\Affichage{\Multik}{0}{0}}}{\Affichage{\Multik}{0}{0}}%
              \xintifboolexpr{\Multim==0}{}{%
                \xintifboolexpr{\Multim>0}{+\Affichage{0}{\Multim}{0}}{-\Affichage{0}{\fpeval{-\Multim}}{0}}%
              }%
              \xintifboolexpr{\Multij==0}{}{\xintifboolexpr{\Multij<0}{-\Affichage{0}{0}{\fpeval{-\Multij}}}{+\Affichage{0}{0}{\Multij}}}%
              }%
               \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+\Multik}}\xdef\SommeB{\fpeval{\SommeB+\Multim}}\xdef\SommeC{\fpeval{\SommeC+\Multij}}}{}%
               \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-\Multik}}\xdef\SommeB{\fpeval{\SommeB-\Multim}}\xdef\SommeC{\fpeval{\SommeC-\Multij}}}{}%
            }{}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==2}{%
              \xdef\Multim{\fpeval{#2*#4+#3*#5}}%
              \ifboolKV[ClesDistributivite]{Oppose}{%
                \xdef\Multijo{\fpeval{-\Multij}}%
                \xdef\Multimo{\fpeval{-\Multim}}%
                \xdef\Multiko{\fpeval{-\Multik}}%
                 \xintifboolexpr{\Multijo==0}{}{\xintifboolexpr{\Multijo<0}{(}{}\Affichage{\Multijo}{0}{0}\xintifboolexpr{\Multijo<0}{)}{}}%
                 \xintifboolexpr{\Multimo==0}{}{\xintifboolexpr{\Multimo>0}{+}{+(}\Affichage{0}{\Multimo}{0}\xintifboolexpr{\Multimo<0}{)}{}}%
                 \xintifboolexpr{\Multiko==0}{}{\xintifboolexpr{\Multiko>0}{+}{+(}\Affichage{0}{0}{\Multiko}\xintifboolexpr{\Multiko<0}{)}{}}%
              }{%
                \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multij<0}{%%%%%%%%%%%%%%%%%%%%%
                    (\Affichage{\Multij}{0}{0})}{\Affichage{\Multij}{0}{0}}}{\Affichage{\Multij}{0}{0}}%
              \xintifboolexpr{\Multim==0}{}{%
                \xintifboolexpr{\Multim>0}{+\Affichage{0}{\Multim}{0}}{-\Affichage{0}{\fpeval{-\Multim}}{0}}%
              }%
              \xintifboolexpr{\Multik==0}{}{\xintifboolexpr{\Multik<0}{-\Affichage{0}{0}{\fpeval{-\Multik}}}{+\Affichage{0}{0}{\Multik}}}%
              }%
               \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+\Multij}}\xdef\SommeB{\fpeval{\SommeB+\Multim}}\xdef\SommeC{\fpeval{\SommeC+\Multik}}}{}%
               \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-\Multij}}\xdef\SommeB{\fpeval{\SommeB-\Multim}}\xdef\SommeC{\fpeval{\SommeC-\Multik}}}{}%
            }{}%
            \xintifboolexpr{\useKV[ClesDistributivite]{Echange}==3}{%
              \xdef\Multim{\fpeval{#2*#5+#3*#4}}%
              \ifboolKV[ClesDistributivite]{Oppose}{%
                \xdef\Multilo{\fpeval{-\Multil}}%
                \xdef\Multimo{\fpeval{-\Multim}}%
                \xdef\Multio{\fpeval{-\Multi}}%
                 \xintifboolexpr{\Multilo==0}{}{\xintifboolexpr{\Multilo<0}{(}{}\Affichage{\Multilo}{0}{0}\xintifboolexpr{\Multilo<0}{)}{}}%
                 \xintifboolexpr{\Multimo==0}{}{\xintifboolexpr{\Multimo>0}{+}{+(}\Affichage{0}{\Multimo}{0}\xintifboolexpr{\Multimo<0}{)}{}}%
                 \xintifboolexpr{\Multio==0}{}{\xintifboolexpr{\Multio>0}{+}{+(}\Affichage{0}{0}{\Multio}\xintifboolexpr{\Multio<0}{)}{}}%
               }{%
                \xintifboolexpr{\theNbCalculDistri>1}{\xintifboolexpr{\Multil<0}{(\Affichage{\Multil}{0}{0})}{\Affichage{\Multil}{0}{0}}}{\Affichage{\Multil}{0}{0}}%
              \xintifboolexpr{\Multim==0}{}{%
                \xintifboolexpr{\Multim>0}{+\Affichage{0}{\Multim}{0}}{-\Affichage{0}{\fpeval{-\Multim}}{0}}%
              }%
              \xintifboolexpr{\Multi==0}{}{\xintifboolexpr{\Multi<0}{-\Affichage{0}{0}{\fpeval{-\Multi}}}{+\Affichage{0}{0}{\Multi}}}%
              }
               \ifboolKV[ClesDistributivite]{Somme}{\xdef\SommeA{\fpeval{\SommeA+\Multil}}\xdef\SommeB{\fpeval{\SommeB+\Multim}}\xdef\SommeC{\fpeval{\SommeC+\Multi}}}{}%
               \ifboolKV[ClesDistributivite]{Difference}{\xdef\SommeA{\fpeval{\SommeA-\Multil}}\xdef\SommeB{\fpeval{\SommeB-\Multim}}\xdef\SommeC{\fpeval{\SommeC-\Multi}}}{}%
            }{}%
          }{}%
        }%
      }%
    }%
  }%
}%

%%%
% Nombre Premier
%%%
\setKVdefault[ClesNombrePremier]{Tableau=false,TableauVide=false,TableauVertical=false,TableauVerticalVide=false,Exposant=false,Longue=false,All=false,Arbre=false,ArbreVide=false,ArbreComplet=false,ArbreDessine=false,ArbreDessineVide=false,Entoure=false,Entourefin=false,Diviseurs=false,DiviseursT=false,Dot=\dotfill,Impose=false,ImposeAll=false,Potence=false,Decalage=10,Vide=false,CouleurFeuillage=ForestGreen,CouleurTronc=BurlyWood,CouleurFruits=Red,CouleurTexte=white}%
\defKV[ClesNombrePremier]{Nombre=\ifboolKV[ClesNombrePremier]{ArbreDessine}{}{\ifboolKV[ClesNombrePremier]{ArbreDessineVide}{}{\setKV[ClesNombrePremier]{Impose}}}}%
\defKV[ClesNombrePremier]{AllNombre=\setKV[ClesNombrePremier]{ImposeAll}}%
\defKV[ClesNombrePremier]{Impression=\setKV[ClesNombrePremier]{CouleurFeuillage=white,CouleurTronc=white,CouleurFruits=gris,CouleurTexte=black}}

\newcommand\Decomposition[2][]{%
  \useKVdefault[ClesNombrePremier]%
  \setKV[ClesNombrePremier]{#1}%
  \ifboolKV[ClesNombrePremier]{Impose}{\NombrePremierImpose{#2}{\useKV[ClesNombrePremier]{Nombre}}{\fpeval{#2/\useKV[ClesNombrePremier]{Nombre}}}}{}%
  \ifboolKV[ClesNombrePremier]{ImposeAll}{\NombrePremierImpose{#2}{\useKV[ClesNombrePremier]{AllNombre}}{\fpeval{#2/\useKV[ClesNombrePremier]{AllNombre}}}}{}%
  \ifboolKV[ClesNombrePremier]{Tableau}{\NombrePremier{#2}}{}%
  \ifboolKV[ClesNombrePremier]{TableauVide}{\NombrePremier{#2}}{}%
  \ifboolKV[ClesNombrePremier]{Potence}{\NombrePremierPotence{#2}}{}%
  \ifboolKV[ClesNombrePremier]{TableauVertical}{\NombrePremierVertical{#2}}{}%
  \ifboolKV[ClesNombrePremier]{TableauVerticalVide}{\NombrePremierVerticalVide{#2}}{}%
  \ifboolKV[ClesNombrePremier]{Exposant}{\PremierExposant{#2}}{}%
  \ifboolKV[ClesNombrePremier]{Longue}{\PremierLong{#2}}{}%
  \ifboolKV[ClesNombrePremier]{All}{\NombrePremierExposant{#2}}{}%
  \ifboolKV[ClesNombrePremier]{Arbre}{\MPArbre{#2}}{}%
  \ifboolKV[ClesNombrePremier]{ArbreComplet}{\MPArbreComplet{#2}}{}%
  \ifboolKV[ClesNombrePremier]{ArbreVide}{\MPArbreVide{#2}}{}%
  \ifboolKV[ClesNombrePremier]{ArbreDessine}{\MPArbreDessine{#2}{\useKV[ClesNombrePremier]{Nombre}}}{}%
  \ifboolKV[ClesNombrePremier]{ArbreDessineVide}{\setKV[ClesNombrePremier]{Vide=true}\MPArbreDessine{#2}{\useKV[ClesNombrePremier]{Nombre}}}{}%
  \ifboolKV[ClesNombrePremier]{Diviseurs}{\ListeDiviseur{#2}}{}%
  \ifboolKV[ClesNombrePremier]{DiviseursT}{\ListeDiviseurT{#2}}{}%
}%

\def\MPArbre#1{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];
    numeric decalage;
    decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;

    k:=0;
    Ancre0:=(0,0);
    racine:=#1;

    label(btex \num{#1} etex,(0,0));
    forever:
    PremierSimple(racine);
    exitif racine=1;
    endfor;

    if \useKV[ClesNombrePremier]{Entoure}:
    for l=1 upto k:
    if Estcepremier(retenirnb[l]):
    draw cercles(Ancre[l],0.25*decalage);
    fi;
    endfor;
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric decalage;decalage=\useKV[ClesNombrePremier]{Decalage}*1mm; boolean Entoure; Entoure=\useKV[ClesNombrePremier]{Entoure};}]
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];
    
    k:=0;
    Ancre0:=(0,0);
    racine:=#1;
    label(LATEX("\num{"&decimal(racine)&"}"),(0,0));
    forever:
    PremierSimplePdf(racine);
    exitif racine=1;
    endfor;

    if \useKV[ClesNombrePremier]{Entoure}:
    for l=1 upto k:
    if Estcepremier(retenirnb[l]):
    draw cercles(Ancre[l],0.25*decalage);
    fi;
    endfor;
    fi;
\end{mpost}
\fi
}

\def\MPArbreComplet#1{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];
    numeric decalage;
    decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;
    
    dx:=1cm;
    dy:=1cm;
    
    pair N[][];
    nbe:=NbEtape(#1);
    Positions(nbe);
    if \useKV[ClesNombrePremier]{Entoure}:
    draw polygone(N[nbe-1][0]+(-0.25*dx,0.25*decalage),N[nbe-1][nbe-1]+(0.25*dx,0.25*decalage),N[nbe-1][nbe-1]+(0.25*dx,-0.25*decalage),N[nbe-1][0]+(-0.25*dx,-0.25*decalage)) dashed evenly;
  fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric decalage;decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;}]
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];

    dx:=1cm;
    dy:=1cm;

    pair N[][];

    PositionsPdf(NbEtape(#1));
  \end{mpost}
  \fi
}

\def\MPArbreVide#1{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];
    numeric decalage;
    decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;
    
    dx:=1cm;
    dy:=1cm;
    
    pair N[][];
    
    PositionsVide(NbEtape(#1));
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric decalage; decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;}]
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];
    
    dx:=1cm;
    dy:=1cm;

    pair N[][];

    PositionsVidePdf(NbEtape(#1));
  \end{mpost}
  \fi
}

\def\MPArbreDessine#1#2{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}
    input PfCArithmetique;
    numeric depart;
    pair Ancre[];
    numeric decalage;
    decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;
    rayonfruits:=3mm;

    color CouleurTronc,CouleurFeuillage,CouleurFruits,CouleurTexte;
    CouleurTronc=\useKV[ClesNombrePremier]{CouleurTronc};
    CouleurFeuillage=\useKV[ClesNombrePremier]{CouleurFeuillage};
    CouleurFruits=\useKV[ClesNombrePremier]{CouleurFruits};
    CouleurTexte=\useKV[ClesNombrePremier]{CouleurTexte};
    
    k:=0;
    Ancre0:=(0,0);
    racine:=#1;
    k:=1;
    Ancre1:=(-decalage,-decalage);
    draw Branche(Ancre0,Ancre1);
    retenirnb[1]:=#2;
    racine:=#2;
    forever:
    PremierSimpleArbre(racine);
    exitif racine=1;
    endfor;
    k:=k+1;
    Ancre[k]:=(decalage,-decalage);
    draw Branche(Ancre0,Ancre[k]);
    retenirnb[k]:=#1 div #2;
    racine:=retenirnb[k];
    forever:
    PremierSimpleArbre(racine);
    exitif racine=1;
    endfor;

    fill cercles(Ancre[0],rayonfruits) withcolor white;
    label(btex \num{#1} etex,(0,0));
    for l=1 upto k:
    if \useKV[ClesNombrePremier]{Vide}:
    fill cercles(Ancre[l],rayonfruits) withcolor white;
    else:
    if Estcepremier(retenirnb[l]):
    fill cercles(Ancre[l],rayonfruits) withcolor CouleurFruits;
    drawoptions(withcolor CouleurTexte);
    label(TEX("\num{"&decimal(retenirnb[l])&"}"),Ancre[l]);
    drawoptions();
    else:
    fill cercles(Ancre[l],rayonfruits) withcolor white;
    label(TEX("\num{"&decimal(retenirnb[l])&"}"),Ancre[l]);
    fi;
    fi;
    endfor;
    for l=0 upto k:
    draw cercles(Ancre[l],rayonfruits);
    endfor;
    picture Bilan;
    Bilan=currentpicture;
    currentpicture:=nullpicture;
    % Habillage
    % On récupère le min des ordonnées des Ancre pour le feuillage
    minord=1000;
    nbancrearetenir=0;
    for l=0 upto k:
    if ypart(Ancre[l])<minord:
    minord:=ypart(Ancre[l]);
    nbancrearetenir:=l;
    fi;
    endfor;
    pair D[];
    D0=0.5[Ancre0,(0,ypart(Ancre[nbancrearetenir]))];
    dotlabel("",D0);
    % Herbe du sol
    pair A[];
    A0=(xpart(Ancre0)-1cm,ypart(Ancre[nbancrearetenir])-2cm);
    A10=(xpart(Ancre0)+1cm,ypart(Ancre[nbancrearetenir])-2cm);
    for l=1 upto 9:
    A[l]=(l/10)[A0,A10]+uniformdeviate(5)*(unitvector(A10-A0) rotated 90);
    endfor;
    %Pour le tronc
    pair B[];
    B1=D0+(10+uniformdeviate(10))*(unitvector(D0-A0) rotated 90);
    B2=symetrie(B1,Ancre0,1/2[A0,A10]);%=(-2mm,0);
    B3=1/2[Ancre0,(xpart(1/2[A0,A10]),ypart(Ancre[k]))];
    path tronc;
    tronc=A0{dir angle(A1-A0)}..{dir90}B1--B2{dir-90}..{dir angle(A10-A9)}A10--reverse(A0 for l=1 upto 10:--A[l] endfor)--cycle;%
    fill tronc withcolor CouleurTronc;
    trace tronc;
    % Pour le feuillage
    path feuillage;
    feuillage=cercles((0,0),abs(Ancre[nbancrearetenir]-D0));%
    pair C[];
    for l=0 upto 7:
    C[l]=(pointarc(feuillage,l*45+(-5+uniformdeviate(10))) xscaled 1.25 yscaled 1) shifted D0;
    endfor;
    feuillage:=C[0] for l=1 upto 7:..(C[l] if (l mod 2)=0:+(0,2mm) else: +(0,-2mm) fi) endfor ..cycle;
    fill feuillage withcolor CouleurFeuillage;
    trace feuillage;
    draw Bilan;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric decalage;decalage=\useKV[ClesNombrePremier]{Decalage}*1mm;color CouleurTronc,CouleurFeuillage,CouleurFruits,CouleurTexte;CouleurTronc=\useKV[ClesNombrePremier]{CouleurTronc};CouleurFeuillage=\useKV[ClesNombrePremier]{CouleurFeuillage};CouleurFruits=\useKV[ClesNombrePremier]{CouleurFruits}; CouleurTexte=\useKV[ClesNombrePremier]{CouleurTexte}; boolean Vide; Vide=\useKV[ClesNombrePremier]{Vide};}]
    input PfCArithmetiquePDF;
    numeric depart;
    pair Ancre[];
    rayonfruits:=3mm;
    
    k:=0;
    Ancre0:=(0,0);
    racine:=#1;
    k:=1;
    Ancre1:=(-decalage,-decalage);
    draw Branche(Ancre0,Ancre1);
    retenirnb[1]:=#2;
    racine:=#2;
    forever:
    PremierSimpleArbre(racine);
    exitif racine=1;
    endfor;
    k:=k+1;
    Ancre[k]:=(decalage,-decalage);
    draw Branche(Ancre0,Ancre[k]);
    retenirnb[k]:=#1 div #2;
    racine:=retenirnb[k];
    forever:
    PremierSimpleArbre(racine);
    exitif racine=1;
    endfor;

    fill cercles(Ancre[0],rayonfruits) withcolor white;
    label(btex \num{#1} etex,(0,0));
    for l=1 upto k:
    if Vide:
    fill cercles(Ancre[l],rayonfruits) withcolor white;
    else:
    if Estcepremier(retenirnb[l]):
    fill cercles(Ancre[l],rayonfruits) withcolor CouleurFruits;
    drawoptions(withcolor CouleurTexte);
    label(LATEX("\num{"&decimal(retenirnb[l])&"}"),Ancre[l]);
    drawoptions();
    else:
    fill cercles(Ancre[l],rayonfruits) withcolor white;
    label(LATEX("\num{"&decimal(retenirnb[l])&"}"),Ancre[l]);
    fi;
    fi;
    endfor;
    for l=0 upto k:
    draw cercles(Ancre[l],rayonfruits);
    endfor;
    picture Bilan;
    Bilan=currentpicture;
    currentpicture:=nullpicture;
    % Habillage
    minord=1000;
    nbancrearetenir=0;
    for l=0 upto k:
    if ypart(Ancre[l])<minord:
    minord:=ypart(Ancre[l]);
    nbancrearetenir:=l;
    fi;
    endfor;
    pair D[];
    D0=0.5[Ancre0,(0,ypart(Ancre[nbancrearetenir]))];
    pair A[];
    A0=(xpart(Ancre0)-1cm,ypart(Ancre[nbancrearetenir])-2cm);
    A10=(xpart(Ancre0)+1cm,ypart(Ancre[nbancrearetenir])-2cm);
    for l=1 upto 9:
    A[l]=(l/10)[A0,A10]+uniformdeviate(5)*(unitvector(A10-A0) rotated 90);
    endfor;
    pair B[];
    B1=D0+(10+uniformdeviate(10))*(unitvector(D0-A0) rotated 90);
    B2=symetrie(B1,Ancre0,1/2[A0,A10]);%
    B3=1/2[Ancre0,(xpart(1/2[A0,A10]),ypart(Ancre[k]))];
    path tronc;
    tronc=A0{dir angle(A1-A0)}..{dir90}B1--B2{dir-90}..{dir angle(A10-A9)}A10--reverse(A0 for l=1 upto 10:--A[l] endfor)--cycle;%
    fill tronc withcolor CouleurTronc;
    trace tronc;
    path feuillage;
    feuillage=cercles((0,0),abs(Ancre[nbancrearetenir]-D0));%
    pair C[];
    for l=0 upto 7:
    C[l]=(pointarc(feuillage,l*45+(-5+uniformdeviate(10))) xscaled 1.25 yscaled 1) shifted D0;
    endfor;
    feuillage:=C[0] for l=1 upto 7:..(C[l] if (l mod 2)=0:+(0,2mm) else: +(0,-2mm) fi) endfor ..cycle;
    fill feuillage withcolor CouleurFeuillage;
    trace feuillage;
    draw Bilan;
  \end{mpost}
\fi
}

\newcount\premier%

\newcommand\NombrePremier[1]{%\'ecrire la d\'ecomposition compl\`ete
  % #1 le nombre premier \`a tester
  \newcount\anp\newcount\bnp\newcount\cnp%
  \anp=#1\relax
  \bnp=2\relax
  \premier=-1\relax
  % Pour d\'eterminer le nombre d'\'etapes
  \whiledo{\anp > 1}{%
    \modulo{\the\anp}{\the\bnp}
    \ifnum\remainder=0\relax
      \global\premier=\numexpr\premier+1\relax
      \cnp=\numexpr\anp/\bnp\relax
      \anp=\cnp\relax
    \else%
      \bnp=\numexpr\bnp+1\relax%
    \fi%
  }
  \ifnum\premier=0
    Le nombre \num{#1} est un nombre premier.
  \else
    \begin{align*}
      \xintFor* ##1 in {\xintSeq {1}{\premier}}\do {\num{#1}&=\ifboolKV[ClesNombrePremier]{TableauVide}{\phantom{\PremierEtape{#1}{##1}}}{\PremierEtape{#1}{##1}}\xintifboolexpr{##1<\premier}{\\}{}}%
    \end{align*}
  \fi
}

\newcount\premierun
\newcount\premierdeux

\newcommand\NombrePremierImpose[3]{%
  % #1 le nombre premier \`a tester
  % #2 est le premier facteur imposé
  % #3 est le deuxième facteur imposé
  \newcount\anp\newcount\bnp\newcount\cnp%
  % Pour d\'eterminer le nombre d'\'etapes pour #1
  \anp=#1\relax
  \bnp=2\relax
  \premier=-1\relax
  \whiledo{\anp > 1}{%
    \modulo{\the\anp}{\the\bnp}
    \ifnum\remainder=0\relax
      \global\premier=\numexpr\premier+1\relax
      \cnp=\numexpr\anp/\bnp\relax
      \anp=\cnp\relax
    \else%
      \bnp=\numexpr\bnp+1\relax%
    \fi%
  }%
  % Pour d\'eterminer le nombre d'\'etapes pour #2
  \anp=#2\relax
  \bnp=2\relax
  \premierun=-1\relax
  \whiledo{\anp > 1}{%
    \modulo{\the\anp}{\the\bnp}
    \ifnum\remainder=0\relax
      \global\premierun=\numexpr\premierun+1\relax
      \cnp=\numexpr\anp/\bnp\relax
      \anp=\cnp\relax
    \else%
      \bnp=\numexpr\bnp+1\relax%
    \fi%
  }%
  % Pour d\'eterminer le nombre d'\'etapes pour #3
  \anp=#3\relax
  \bnp=2\relax
  \premierdeux=-1\relax
  \whiledo{\anp > 1}{%
    \modulo{\the\anp}{\the\bnp}
    \ifnum\remainder=0\relax
      \global\premierdeux=\numexpr\premierdeux+1\relax
      \cnp=\numexpr\anp/\bnp\relax
      \anp=\cnp\relax
    \else%
      \bnp=\numexpr\bnp+1\relax%
    \fi%
  }%
  \ifboolKV[ClesNombrePremier]{ImposeAll}{\xdef\PfCRappelImposeAll{1}}{\xdef\PfCRappelImposeAll{0}}%
  \ifnum\premier=0
  Le nombre \num{#1} est un nombre premier.
  \else
  \xintifboolexpr{\premierun>\premierdeux}{\premier=\premierun}{\premier=\premierdeux}
  \begin{align*}
    \num{#1}&=\num{#2}\times\num{#3}%\\
    \xintifboolexpr{\premier>0}{\\%
    \xintFor* ##1 in {\xintSeq {1}{\premier}}\do {\num{#1}&=\xintifboolexpr{##1<\premierun}{\PremierEtape{#2}{##1}}{\Decomposition[Longue]{#2}}\mathrel{\times}\xintifboolexpr{##1<\premierdeux}{\PremierEtape{#3}{##1}}{\Decomposition[Longue]{#3}}\xintifboolexpr{##1<\premier}{\\}{}}%
    }{}%
    \xintifboolexpr{\PfCRappelImposeAll==1}{\\\num{#1}&=\PremierExposant{#1}}{}%
  \end{align*}
  \fi
}%

\newcommand\NombrePremierVertical[1]{%\'ecrire la d\'ecomposition compl\`ete
  % #1 le nombre premier \`a tester
  \newcount\anpv\newcount\bnpv\newcount\cnpv%
  \anpv=#1\relax
  \bnpv=2\relax
  \premier=-1\relax
  % Pour d\'eterminer le nombre d'\'etapes
  \whiledo{\anpv > 1}{%
    \modulo{\the\anpv}{\the\bnpv}
    \ifnum\remainder=0\relax
      \global\premier=\numexpr\premier+1\relax
      \cnpv=\numexpr\anpv/\bnpv\relax
      \anpv=\cnpv\relax
    \else%
      \bnpv=\numexpr\bnpv+1\relax%
    \fi%
  }
  \ifnum\premier=0
    Le nombre \num{#1} est un nombre premier.
    \else
    \begin{tabular}{c|c}
      \xintFor* ##1 in {\xintSeq {0}{\premier}}\do
      {\PremierMultipleVide{#1}{##1}&\xdef\Etape{\fpeval{##1+1}}\PremierDiviseurVide{#1}{\Etape}
                                      \xintifboolexpr{##1<\premier}{\\}{\\1\\}}%
    \end{tabular}
  \fi
}

\newcommand\NombrePremierPotence[1]{%
  % #1 le nombre premier \`a tester
  \newcount\anpv\newcount\bnpv\newcount\cnpv%
  \anpv=#1\relax
  \bnpv=2\relax
  \premier=-1\relax
  % Pour d\'eterminer le nombre d'\'etapes
  \whiledo{\anpv > 1}{%
    \modulo{\the\anpv}{\the\bnpv}
    \ifnum\remainder=0\relax
      \global\premier=\numexpr\premier+1\relax
      \cnpv=\numexpr\anpv/\bnpv\relax
      \anpv=\cnpv\relax
    \else%
      \bnpv=\numexpr\bnpv+1\relax%
    \fi%
  }
  \ifnum\premier=0%
    Le nombre \num{#1} est un nombre premier.%
  \else%
  \xdef\PotenceCases{\fpeval{\premier+2}}%
    \begin{NiceTabular}{*{\PotenceCases}{c}}
      %\Body
      \PremierMultipleVide{#1}{0}&\multicolumn{1}{|c}{\PremierDiviseurVide{#1}{1}}\\
      \hhline{~-}
      \xintFor* ##1 in {\xintSeq {1}{\premier}}\do{%
        \xintifboolexpr{##1 == 0}{}{\xintFor* ##2 in {\xintSeq {1}{##1}}\do{%
            &}%
        }%
        \multicolumn{1}{|c}{\PremierMultipleVide{#1}{##1}}&\multicolumn{1}{|c}{\xdef\Etape{\fpeval{##1+1}}\PremierDiviseurVide{#1}{\Etape}}\\
        \hhline{*{\fpeval{##1+1}}{~}-}
      }%
      \xintFor* ##1 in {\xintSeq {1}{\fpeval{\PotenceCases-2}}}\do{%
        &}&\multicolumn{1}{|c}{1}\\
      \CodeAfter
      \tikz \draw [white,fill=white] (1 -|2) circle (0.5mm);
      \xintFor* ##1 in {\xintseq{2}{\PotenceCases}}\do{%
        \tikz \draw [white,fill=white,transform canvas={xshift=0mm}] (\fpeval{##1-1} -|##1) circle (0.5mm);
      }%
    \end{NiceTabular}%
  \fi%
}

\newcommand\PremierDiviseurVide[2]{%
  %#1 : le nombre entier \`a tester
  %#2 : le nombre d'\'etapes \`a effectuer
  \newcount\anpvv\newcount\bnpvv\newcount\cnpvv\newcount\dnpvv%
  \ensuremath{%
    \anpvv=#1\relax
    \bnpvv=2\relax
    \dnpvv=0\relax%
    \whiledo{\anpvv > 1}{%
      \whiledo{\dnpvv < \number#2}{%
        \modulo{\the\anpvv}{\the\bnpvv}
        \ifnum\remainder=0\relax
          \dnpvv=\numexpr\dnpvv+1\relax
          \cnpvv=\numexpr\anpvv/\bnpvv\relax
          \anpvv=\cnpvv\relax
        \else%
          \bnpvv=\numexpr\bnpvv+1\relax%
        \fi%
      }
      \num{\the\bnpvv}%
      \anpvv=1%
    }
  }
}

\newcommand\PremierMultipleVide[2]{%
  %#1 : le nombre entier \`a tester
  %#2 : le nombre d'\'etapes \`a effectuer
  \newcount\anpmv\newcount\bnpmv\newcount\cnpmv\newcount\dnpmv%
  \ensuremath{%
    \anpmv=#1\relax
    \bnpmv=2\relax
    \dnpmv=0\relax%
    \whiledo{\anpmv > 1}{%
      \whiledo{\dnpmv < \number#2}{%
        \modulo{\the\anpmv}{\the\bnpmv}
        \ifnum\remainder=0\relax
          \dnpmv=\numexpr\dnpmv+1\relax
          \cnpmv=\numexpr\anpmv/\bnpmv\relax
          \anpmv=\cnpmv\relax
        \else%
          \bnpmv=\numexpr\bnpmv+1\relax%
        \fi%
      }
      \num{\the\anpmv}%
      \anpmv=1%
    }
  }
}

\newcommand\NombrePremierVerticalVide[1]{%
  % #1 le nombre premier \`a tester
  \newcount\anpv\newcount\bnpv\newcount\cnpv%
  \anpv=#1\relax
  \bnpv=2\relax
  \premier=-1\relax
  % Pour d\'eterminer le nombre d'\'etapes
  \whiledo{\anpv > 1}{%
    \modulo{\the\anpv}{\the\bnpv}
    \ifnum\remainder=0\relax
      \global\premier=\numexpr\premier+1\relax
      \cnpv=\numexpr\anpv/\bnpv\relax
      \anpv=\cnpv\relax
    \else%
      \bnpv=\numexpr\bnpv+1\relax%
    \fi%
  }
  \ifnum\premier=0
    Le nombre \num{#1} est un nombre premier.%
    \else
    \renewcommand{\arraystretch}{1.5}
    \begin{tabular}{c|c}
      \PremierMultipleVide{#1}{0}&\hbox to1cm{\useKV[ClesNombrePremier]{Dot}}\\
      \xintFor* ##1 in {\xintSeq {1}{\premier}}\do
      {\hbox to1cm{\useKV[ClesNombrePremier]{Dot}}&\hbox
                              to1cm{\useKV[ClesNombrePremier]{Dot}}\xintifboolexpr{##1<\premier}{\\}{\\\hbox
      to1cm{\useKV[ClesNombrePremier]{Dot}}\\}}%
    \end{tabular}
    \renewcommand{\arraystretch}{1}
  \fi
}

\newcommand\NombrePremierExposant[1]{%
  \newcount\anp\newcount\bnp\newcount\cnp%
  % #1 le nombre premier \`a tester
  \anp=#1\relax%
  \bnp=2\relax%
  \premier=-1\relax%
  % Pour d\'eterminer le nombre d'\'etapes
  \whiledo{\anp > 1}{%
    \modulo{\the\anp}{\the\bnp}
    \ifnum\remainder=0\relax%
      \global\premier=\numexpr\premier+1\relax%
      \cnp=\numexpr\anp/\bnp\relax%
      \anp=\cnp\relax%
    \else%
      \bnp=\numexpr\bnp+1\relax%
      \fi%
  }%
  \ifnum\premier=0%
    Le nombre \num{#1} est un nombre premier.%
  \else%
  \begin{align*}
      \xintFor* ##1 in {\xintSeq {1}{\premier}}\do {\num{#1}&=\PremierEtape{#1}{##1}\\}%
      \num{#1}&=\PremierExposant{#1}%
    \end{align*}%
  \fi%
}%
  
\newcommand\PremierEtape[2]{%
  %#1 : le nombre entier \`a tester
  %#2 : le nombre d'\'etapes \`a effectuer
  \newcount\anp\newcount\bnp\newcount\cnp\newcount\dnp%
  \ensuremath{%
    \anp=#1\relax
    \bnp=2\relax
    \dnp=0\relax%
    \whiledo{\anp > 1}{%
      \whiledo{\dnp < \number#2}{%
        \modulo{\the\anp}{\the\bnp}
        \ifnum\remainder=0\relax
          \dnp=\numexpr\dnp+1\relax
          \cnp=\numexpr\anp/\bnp\relax
          \anp=\cnp\relax
          \num{\the\bnp}\times%
        \else%
          \bnp=\numexpr\bnp+1\relax%
        \fi%
      }
      \num{\the\anp}%
      \anp=1%
    }
  }
}

\newcommand\PremierExposant[1]{%
  %#1 : le nombre entier \`a tester
  \ensuremath{%
  \newcount\anp\newcount\bnp\newcount\cnp%
  \newcount\pileb\newcount\exposant%
  \exposant=0\relax%
  \anp=#1\relax%
  \bnp=2\relax%
  \pileb=2\relax%
  \whiledo{\the\anp > 1}{%
    \modulo{\the\anp}{\the\bnp}
    \ifnum\remainder=0\relax
      \cnp=\numexpr\anp/\bnp\relax
      \ifnum\pileb=\bnp
      \exposant=\numexpr\exposant+1\relax
      \fi
      \anp=\cnp\relax
    \else%
      \ifnum\exposant>0\relax
        \num{\the\pileb}\ifnum\exposant>1 ^{\num{\the\exposant}}\fi\times%
      \fi
      \bnp=\numexpr\bnp+1\relax%
      \pileb=\bnp\relax%
      \exposant=0\relax%
    \fi%
  }%
  \num{\the\pileb}\ifnum\exposant>1^{\num{\the\exposant}}\fi%
  }%
}%

\newcommand\PremierLong[1]{%
  %#1 : le nombre entier \`a tester
  \ensuremath{%
  \newcount\anpl\newcount\bnpl\newcount\cnpl%
  \newcount\pilebl%
  \anpl=#1\relax%
  \bnpl=2\relax%
  \pilebl=2\relax%
  \whiledo{\the\anpl > 1}{%
    \modulo{\the\anpl}{\the\bnpl}
    \ifnum\remainder=0\relax
      \cnpl=\numexpr\anpl/\bnpl\relax
      \num{\the\bnpl}\ifnum\anpl>\bnpl\times\fi%
      \anpl=\cnpl\relax
    \else%
      \bnpl=\numexpr\bnpl+1\relax%
      \pilebl=\bnpl\relax%
    \fi%
    }
  }
}

\newcommand\ListeDiviseur[1]{%#1 : le nombre entier \`a tester
  \newcount\anp\newcount\bnp%
  \anp=#1%
  \bnp=2\relax%
  1 %
  \whiledo{\bnp<\anp}{%
    \modulo{\the\anp}{\the\bnp}{}%
    \ifnum\remainder=0%
    ; $\num{\the\bnp}$ %
    \fi%
    \bnp=\numexpr\bnp+1%
  }%
  et \num{\the\anp}%
}

\newcount\anpT\newcount\bnpT\newcount\cnpT\newcount\dnpT%

\newcommand\ListeDiviseurT[1]{%#1 : le nombre entier \`a tester
  \anpT=#1%
  \bnpT=2\relax%
  %On compte les diviseurs propres.
  \cnpT=0\relax%
  \whiledo{\bnpT<\anpT}{%
    \modulo{\the\anpT}{\the\bnpT}{}%
    \ifnum\remainder=0%
    \cnpT=\numexpr\cnpT+1%
    \fi%
    \bnpT=\numexpr\bnpT+1%
  }%
  \ifodd\cnpT%
    \begin{tabular}{c|c}%
    1&\num{#1}\\
    \xintFor* ##1 in {\xintSeq {1}{\fpeval{(\cnpT+1)/2}}}\do{%
    \DiviseurNumero{#1}{##1}\num{\fpeval{\dnpT}}\uppercase{&}\DiviseurNumero{#1}{##1}\xintifboolexpr{\dnpT=\fpeval{#1/\dnpT}}{}{\num{\fpeval{#1/\dnpT}}}\\
    }
  \end{tabular}%
  \else%
    \begin{tabular}{c|c}
    1&\num{#1}\\
    \xintFor* ##1 in {\xintSeq {1}{\fpeval{\cnpT/2}}}\do{%
    \DiviseurNumero{#1}{##1}\num{\fpeval{\dnpT}}\uppercase{&}\DiviseurNumero{#1}{##1}\num{\fpeval{#1/\dnpT}}\\
    }
  \end{tabular}%
  \fi%
}%

\newcommand\DiviseurNumero[2]{%
  % #1 nb entier \`a tester
  % #2 no du diviseur (\`a part 1 et #1)
  \anpT=#1%
  \bnpT=2\relax%
  %On compte les diviseurs propres.
  \cnpT=0\relax%
  \whiledo{\bnpT<\anpT}{%
    \modulo{\the\anpT}{\the\bnpT}{}%
    \ifnum\remainder=0%
    \cnpT=\numexpr\cnpT+1%
    \ifnum\cnpT=\numexpr#2-1%
    \dnpT=\bnpT%
    \bnpT=\anpT%
    \fi%
    \fi%
    \bnpT=\numexpr\bnpT+1%
  }%
}

%%%
% Simplification
%%%
\makeatletter%by christian Tellechea
% Calcul du PGCD de #1 et #2
\newcount\cnt@a\newcount\cnt@b\newcount\pgcd
\def\PGCD#1#2{%
  \ifnum#1>#2\cnt@a#1\cnt@b#2\else\cnt@a#2\cnt@b#1\relax\fi
  \PGCD@i
}
\def\PGCD@i{\edef\PGCD@ii##1{##1{\number\cnt@a}{\number\cnt@b}}\PGCD@ii\PGCD@iii}
\def\PGCD@iii#1#2{%
  \cnt@b#1\relax\global\divide\cnt@b#2%
  \global\cnt@b\numexpr#1-#2*\cnt@b%
  \global\cnt@a#2\global\pgcd\cnt@a%
  \ifnum\cnt@b>\z@\expandafter\PGCD@i%
  \fi}%
\makeatother

\def\SSimplifie#1#2{%
  % Simplification d'une \'ecriture #1/#2
  \ensuremath{
    \newcount\numerateur\newcount\denominateur\newcount\valabsnum\newcount\valabsdeno
    \numerateur=\number#1
    \denominateur=\number#2
    \ifnum\number#1<0\relax
      \valabsnum=\numexpr0-\number#1
    \else
      \valabsnum=\number#1
    \fi
    \ifnum\number#2<0\relax
      \valabsdeno=\numexpr0-\number#2
    \else
      \valabsdeno=\number#2
    \fi
    \ifnum\the\numerateur<0\relax
      \ifnum\the\denominateur<0\relax
        \numerateur=\valabsnum
        \denominateur=\valabsdeno
      \fi
    \else
      \ifnum\the\denominateur<0\relax
        \numerateur=-\valabsnum
        \denominateur=\valabsdeno
      \fi
    \fi
    \ifnum\number#2=0\relax
      \text{\bfseries(???)}
    \else
      \ifnum\number#1=0\relax
        0
      \else
        \PGCD{\the\valabsnum}{\the\valabsdeno}%
        \ifnum\pgcd>1\relax
          \ifthenelse{\pgcd=\number#2 \OR \pgcd=\the\valabsdeno}{%
            \divide\numerateur by \denominateur\num{\the\numerateur}
          }{\divide\numerateur by\pgcd%
            \divide\denominateur by\pgcd%
            \frac{\num{\the\numerateur}}{\num{\the\denominateur}}
          }
        \else%%%comme on est avec les n\'egatifs, on doit regarder si la valeur absolue est \'egale \`a 1
          \ifnum\valabsdeno=1\relax
            \divide\numerateur by \denominateur\num{\the\numerateur}
          \else
            \frac{\num{\the\numerateur}}{\num{\the\denominateur}}
          \fi
        \fi%
      \fi%
    \fi%
  }%
}


\newcommand\SSimpli[2]{%
  % D\'ecomposition d'une simplification de #1/#2
  \newcount\numerateur\newcount\denominateur\newcount\valabsnum\newcount\valabsdeno%
  \numerateur=\number#1
  \denominateur=\number#2
  \ifnum\number#1<0
  \valabsnum=\numexpr0-\number#1
  \else
  \valabsnum=\number#1
  \fi
  \ifnum\number#2<0
  \valabsdeno=\numexpr0-\number#2
  \else
  \valabsdeno=\number#2
  \fi
  \ifnum\the\numerateur<0\relax
    \ifnum\the\denominateur<0\relax
      \numerateur=\valabsnum
      \denominateur=\valabsdeno
    \fi
  \else
    \ifnum\the\denominateur<0\relax
      \numerateur=-\valabsnum
      \denominateur=\valabsdeno
    \fi
  \fi
  \ifnum\number#2=0\relax
    \ensuremath{\text{\bfseries(???)}}
  \else
      \ifnum\number#1=0\relax
        0
      \else
        \PGCD{\the\valabsnum}{\the\valabsdeno}%
        \ifnum\pgcd>1\relax
          \ifthenelse{\pgcd=\number#2 \OR \pgcd=\the\valabsdeno}{%
            \divide\numerateur by \denominateur\num{\the\numerateur}
          }{%\divide\numerateur by\pgcd%
            % \divide\denominateur by\pgcd%
            \ensuremath{\frac{\num{\the\numerateur}_{\mbox{\tiny$\div\num{\number\pgcd}$}}}{\num{\the\denominateur}_{\mbox{\tiny$\div\num{\number\pgcd}$}}}}%
          }
        \else
          \ifnum\denominateur=1\relax
            \ensuremath{\frac{\num{\the\numerateur}_{\mbox{\tiny$\div\num{\number\pgcd}$}}}{\num{\the\denominateur}_{\mbox{\tiny$\div\num{\number\pgcd}$}}}}
          \else
            \ensuremath{\frac{\num{\the\numerateur}}{\num{\the\denominateur}}}
          \fi
        \fi
      \fi
    \fi
}

\newcount\anpdc\newcount\bnpdc\newcount\cnpdc\newcount\dnpdc%
\newcount\DivCom
\newcommand\DiviseurCommun[2]{%
  % #1 : le premier nombre entier
  % #2 : le deuxi\`eme nombre entier
 % nombre 1 vaut #1 - Nombre 2 vaut #2
  \anpdc=#1%
  \cnpdc=#2%
  \bnpdc=2\relax%
  \dnpdc=\numexpr#1+1\relax%
  \DivCom=1\relax%
  \whiledo{\bnpdc<\dnpdc}{%
    \modulo{\the\anpdc}{\the\bnpdc}\relax
    \ifnum\remainder=0%
    \modulo{\the\cnpdc}{\the\bnpdc}
    \ifnum\remainder=0%
    \DivCom=\bnpdc%
    \bnpdc=\anpdc%
    \else%
    \DivCom=1%
    \fi
    \else%
    \DivCom=1%
    \fi
    \bnpdc=\numexpr\bnpdc+1\relax%
  }%
}

\newcommand\LongueSimplification[2]{%
  \xdef\NumerateurDiv{#1}%
  \xdef\DenominateurDiv{#2}%
  \DiviseurCommun{#1}{#2}%
  \ensuremath{%
    \whiledo{\DivCom>1}{%
      \frac{\num{\fpeval{\NumerateurDiv/\the\DivCom}}\times\num{\the\DivCom}}{\num{\fpeval{\DenominateurDiv/\the\DivCom}}\times\num{\the\DivCom}}=\frac{\num{\fpeval{\NumerateurDiv/\DivCom}}}{\num{\fpeval{\DenominateurDiv/\DivCom}}}%
      \xdef\NumerateurDiv{\fpeval{\NumerateurDiv/\DivCom}}%
      \xdef\DenominateurDiv{\fpeval{\DenominateurDiv/\DivCom}}%
      \DiviseurCommun{\NumerateurDiv}{\DenominateurDiv}%
      \xintifboolexpr{\DivCom>1}{=}{}%
    }%
  }%
}%

\setKVdefault[ClesSimplification]{Details=false,All=false,Longue=false,Fleches=false,Contraire=0}

\newcounter{NbFrac}%
\setcounter{NbFrac}{0}%

\newcommand\Simplification[3][]{%
  \stepcounter{NbFrac}%
  \useKVdefault[ClesSimplification]%
  \setKV[ClesSimplification]{#1}%
  \ifboolKV[ClesSimplification]{Fleches}{%
    \setsepchar[*]{,*/}%\ignoreemptyitems
    \readlist*\Listea{#2}%
    \readlist*\Listeb{#3}%
    \setbox1=\hbox{\Listea[1,1]{}}%
    \setbox2=\hbox{\Listeb[1,1]}%
    \setbox3=\hbox{\Listea[1,3]}%
    \setbox4=\hbox{\Listeb[1,3]}%
     \ensuremath{%
       \frac{\tikzmarknode[anchor=north]{A-\theNbFrac}{\Listea[1,1]}{}}{\tikzmarknode[anchor=south]{B-\theNbFrac}{\Listeb[1,1]}{}}=\frac{\tikzmarknode[anchor=north]{C-\theNbFrac}{\Listea[1,3]}{}}{\tikzmarknode[anchor=south]{D-\theNbFrac}{\Listeb[1,3]}{}}%
     }%
     \begin{tikzpicture}[remember picture,overlay]%
       \draw[out=45,in=135,-stealth,transform canvas={yshift=0.25em}]
       let
       \p1=(pic cs:A-\theNbFrac),
       \p2=(pic cs:C-\theNbFrac)
       in (pic cs:A-\theNbFrac) to node[midway,above]{\Listea[1,2]}(\x2,\y1);
      \draw[out=-45,in=-135,-stealth,transform canvas={yshift=-0.25em}] (pic cs:B-\theNbFrac) to node[midway,below]{\Listeb[1,2]}(pic cs:D-\theNbFrac);%
    \end{tikzpicture}%
  }{%
    \xintifboolexpr{\useKV[ClesSimplification]{Contraire}>1}{%
      \ensuremath{%
        \frac{\num{#2}}{\num{#3}}=\frac{\num{#2}\times\num{\useKV[ClesSimplification]{Contraire}}}{\num{#3}\times\num{\useKV[ClesSimplification]{Contraire}}}=\frac{\num{\fpeval{\useKV[ClesSimplification]{Contraire}*#2}}}{\num{\fpeval{\useKV[ClesSimplification]{Contraire}*#3}}}%
      }%
    }{%
      \ifboolKV[ClesSimplification]{Longue}{%
        \LongueSimplification{#2}{#3}%
      }{%
        \ifboolKV[ClesSimplification]{Details}{\SSimpli{#2}{#3}}{\ifboolKV[ClesSimplification]{All}{\ensuremath{\SSimpli{#2}{#3}=\SSimplifie{#2}{#3}}}{\SSimplifie{#2}{#3}}}%
      }%
    }%
  }%
}%

%%%
% Thales
%%%
\newcount\ppcm%

\newcommand\PPCM[2]{%
  \PGCD{#1}{#2}%
  \ppcm=\numexpr#1*#2/\pgcd\relax%
}%

\setKVdefault[ClesThales]{Calcul=true,Droites=false,Propor=false,Segment=false,Figure=false,FigureSeule=false,Figurecroisee=false,FigurecroiseeSeule=false,Angle=0,Precision=2,Entier=false,Unite=cm,Reciproque=false,Produit=false,ChoixCalcul=0,Simplification,Redaction=false,Remediation=false,Echelle=1cm,Perso=false,CalculsPerso=false,IntroCalculs,CouleursNum=false,CouleursDen=false}
\defKV[ClesThales]{CouleurNum=\setKV[ClesThales]{CouleursNum}}
\defKV[ClesThales]{CouleurDen=\setKV[ClesThales]{CouleursDen}}

\DeclareSIUnit{\PfCThalesUnit}{\useKV[ClesThales]{Unite}}%

%On d\'efinit la figure \`a utiliser
\def\MPFigThales#1#2#3#4#5#6{
    % #1 Premier sommet
    % #2 Deuxi\`eme sommet
    % #3 Troisi\`eme sommet
    % #4 point sur le segment #1#2
    % #5 point sur le segment #1#3
    % #6 angle de rotation
  \ifluatex
%  \mplibcodeinherit{enable}
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesThales]{Echelle};
    boolean CouleursNum,CouleursDen;
    CouleursNum=\useKV[ClesThales]{CouleursNum};
    CouleursDen=\useKV[ClesThales]{CouleursDen};
    color CouleurNum,CouleurDen;
    if CouleursNum:
    CouleurNum=\useKV[ClesThales]{CouleurNum}
    else:
    CouleurNum=black
    fi;
    if CouleursDen:
    CouleurDen=\useKV[ClesThales]{CouleurDen}
    else:
    CouleurDen=black
    fi;
    pair A,B,C,M,N,O;%
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=u*(1,1);
    B-A=u*(4,0);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On d\'efinit le centre du cercle circonscrit
    O - .5[A,B] = whatever * (B-A) rotated 90;
    O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    cotes2=B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    cotes3=C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    M=point(0.4*length cotes1) of cotes1;
    N=point(0.6*length cotes3) of cotes3;
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    path triangle;
    triangle=cotes1--cotes2--cotes3--cycle;
    draw triangle;
    draw cotes4;
    if CouleursDen:
    draw triangle dashed evenly withpen pencircle scaled 1.5 withcolor CouleurDen;
    fi;
    if CouleursNum:
    draw (cotes1 cutafter cotes4) dashed dashpattern(off 3 on 3) withpen pencircle scaled 1.5 withcolor CouleurNum;
    draw (cotes4 cutbefore cotes1 cutafter cotes3) dashed dashpattern(off 3 on 3) withpen pencircle scaled 1.5 withcolor CouleurNum;
    draw (cotes3 cutbefore cotes4) dashed dashpattern(off 3 on 3) withpen pencircle scaled 1.5 withcolor CouleurNum;
    fi;
    %on labelise
    label(btex #1 etex,1.15[O,A]);
    label(btex #2 etex,1.15[O,B]);
    label(btex #3 etex,1.15[O,C]);
    label(btex #4 etex,1.1[C,M]);
    label(btex #5 etex,1.1[B,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes1 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes3 intersectionpoint cotes4);
    pair I,J,K;
    I=1/2[M,N];
    J=1/2[B,C];
    K=1/2[I,J];
    path cd;
    cd=(fullcircle scaled 6mm) shifted K;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((I{dir(210+angle(I-J))}..{dir(150+angle(I-J))}K) cutafter cd);
    drawarrow reverse((J{dir(210+angle(J-I))}..{dir(150+angle(J-I))}K) cutafter cd);
    draw cd;
    label(btex $//$ etex ,K);
    drawoptions();
  \end{mplibcode}
%  \mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesThales]{Echelle};boolean CouleursNum,CouleursDen;
    CouleursNum=\useKV[ClesThales]{CouleursNum};
    CouleursDen=\useKV[ClesThales]{CouleursDen};
    color CouleurNum,CouleurDen;
    if CouleursNum:
    CouleurNum=\useKV[ClesThales]{CouleurNum}
    else:
    CouleurNum=black
    fi;
    if CouleursDen:
    CouleurDen=\useKV[ClesThales]{CouleurDen}
    else:
    CouleurDen=black
    fi;}]
    pair A,B,C,M,N,O;%
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=u*(1,1);
    B-A=u*(4,0);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On d\'efinit le centre du cercle circonscrit
    O - .5[A,B] = whatever * (B-A) rotated 90;
    O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    cotes2=B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    cotes3=C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    M=point(0.4*length cotes1) of cotes1;
    N=point(0.6*length cotes3) of cotes3;
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    path triangle;
    triangle=cotes1--cotes2--cotes3--cycle;
    draw triangle;
    draw cotes4;
        if CouleursDen:
    draw triangle dashed evenly withpen pencircle scaled 1.5 withcolor CouleurDen;
    fi;
    if CouleursNum:
    draw (cotes1 cutafter cotes4) dashed dashpattern(off 3 on 3) withpen pencircle scaled 1.5 withcolor CouleurNum;
    draw (cotes4 cutbefore cotes1 cutafter cotes3) dashed dashpattern(off 3 on 3) withpen pencircle scaled 1.5 withcolor CouleurNum;
    draw (cotes3 cutbefore cotes4) dashed dashpattern(off 3 on 3) withpen pencircle scaled 1.5 withcolor CouleurNum;
    fi;
    %on labelise
    label(btex #1 etex,1.15[O,A]);
    label(btex #2 etex,1.15[O,B]);
    label(btex #3 etex,1.15[O,C]);
    label(btex #4 etex,1.1[C,M]);
    label(btex #5 etex,1.1[B,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes1 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes3 intersectionpoint cotes4);
    pair I,J,K;
    I=1/2[M,N];
    J=1/2[B,C];
    K=1/2[I,J];
    path cd;
    cd=(fullcircle scaled 6mm) shifted K;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((I{dir(210+angle(I-J))}..{dir(150+angle(I-J))}K) cutafter cd);
    drawarrow reverse((J{dir(210+angle(J-I))}..{dir(150+angle(J-I))}K) cutafter cd);
    draw cd;
    label(btex $//$ etex ,K);
    drawoptions();
  \end{mpost}
  \fi
}

%On d\'efinit la figure \`a utiliser
\def\MPFigReciThales#1#2#3#4#5#6{
    % #1 Premier sommet
    % #2 Deuxi\`eme sommet
    % #3 Troisi\`eme sommet
    % #4 point sur le segment #1#2
    % #5 point sur le segment #1#3
  \ifluatex
  \mplibcodeinherit{enable}
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesThales]{Echelle};
    pair A,B,C,M,N,O;%
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=u*(1,1);
    B-A=u*(4,0);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On d\'efinit le centre du cercle circonscrit
    O - .5[A,B] = whatever * (B-A) rotated 90;
    O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    cotes2=B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    cotes3=C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    M=point(0.4*length cotes1) of cotes1;
    N=point(0.6*length cotes3) of cotes3;
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    path triangle;
    triangle=cotes1--cotes2--cotes3--cycle;
    draw triangle;
    draw cotes4;
    %on labelise
    label(btex #1 etex,1.15[O,A]);
    label(btex #2 etex,1.15[O,B]);
    label(btex #3 etex,1.15[O,C]);
    label(btex #4 etex,1.1[C,M]);
    label(btex #5 etex,1.1[B,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes1 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes3 intersectionpoint cotes4);
  \end{mplibcode}
  \mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesThales]{Echelle};}]
    pair A,B,C,M,N,O;%
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=u*(1,1);
    B-A=u*(4,0);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On d\'efinit le centre du cercle circonscrit
    O - .5[A,B] = whatever * (B-A) rotated 90;
    O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    cotes2=B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    cotes3=C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    M=point(0.4*length cotes1) of cotes1;
    N=point(0.6*length cotes3) of cotes3;
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    path triangle;
    triangle=cotes1--cotes2--cotes3--cycle;
    draw triangle;
    draw cotes4;
    %on labelise
    label(btex #1 etex,1.15[O,A]);
    label(btex #2 etex,1.15[O,B]);
    label(btex #3 etex,1.15[O,C]);
    label(btex #4 etex,1.1[C,M]);
    label(btex #5 etex,1.1[B,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes1 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes3 intersectionpoint cotes4);
  \end{mpost}
  \fi
}

%On d\'efinit la deuxi\`eme figure \`a utiliser
\def\MPFigThalesCroisee#1#2#3#4#5#6{%
    % #1 Premier sommet
    % #2 Deuxi\`eme sommet
    % #3 Troisi\`eme sommet
    % #4 point sur la droite #1#2
    % #5 point sur la droite #1#3
  \ifluatex
  \mplibforcehmode
  \mplibcodeinherit{enable}
  \begin{mplibcode}
    u:=\useKV[ClesThales]{Echelle};
    boolean CouleursNum,CouleursDen;
    CouleursNum=\useKV[ClesThales]{CouleursNum};
    CouleursDen=\useKV[ClesThales]{CouleursDen};
    color CouleurNum,CouleurDen;
    if CouleursNum:
    CouleurNum=\useKV[ClesThales]{CouleurNum}
    else:
    CouleurNum=black
    fi;
    if CouleursDen:
    CouleurDen=\useKV[ClesThales]{CouleurDen}
    else:
    CouleurDen=black
    fi;
    pair A,B,C,M,N,O;%
    O=(2.5u,2.5u);
    path cc;
    cc=(fullcircle scaled 3u) shifted O;
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.1*length cc) of cc;
    B=A rotatedabout(O,130);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    M=1.4[B,A];
    N=1.4[C,A];
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..1.15[A,B]{dir(angle(B-A)+5)};
    cotes2=1.15[C,B]{dir(angle(C-B)+5)}..1.15[B,C]{dir(angle(C-B)+5)};
    cotes3=1.15[A,C]{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    cotes5=A{dir(angle(M-A)+5)}..1.15[A,M]{dir(angle(M-A)+5)};
    cotes6=A{dir(angle(N-A)+5)}..1.15[A,N]{dir(angle(N-A)+5)};
    for k=1 upto 6:
    draw cotes[k];
    endfor;
    if CouleursDen:
    drawoptions(dashed evenly withpen pencircle scaled 1.5 withcolor CouleurDen);
    draw (cotes[1] cutafter cotes[2]);
    draw (cotes[2] cutbefore cotes[1] cutafter cotes[3]);
    draw (cotes[3] cutbefore cotes[2]);
    drawoptions();
    fi;
    if CouleursNum:
    drawoptions(dashed evenly withpen pencircle scaled 1.5 withcolor CouleurNum);
    draw (cotes[5] cutafter cotes[4]);
    draw (cotes[4] cutbefore cotes[5] cutafter cotes[6]);
    draw (cotes[6] cutafter cotes[4]);
    drawoptions();
    fi;
    pair I;
    % On d\'efinit le centre du cercle inscrit \`a AMC
    (I-C) rotated ((angle(A-C)-angle(M-C))/2) shifted C=whatever[A,C];
    (I-M) rotated ((angle(C-M)-angle(A-M))/2) shifted M=whatever[M,C];
    %on labelise
    label(btex #1 etex,I);
    label(btex #2 etex,1.2[M,B]);
    label(btex #3 etex,1.2[N,C]);
    label(btex #4 etex,1.1[B,M]);
    label(btex #5 etex,1.1[C,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes5 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes6 intersectionpoint cotes4);
    pair I,J,K;
    I=1.1[N,M];
    J=1.1[B,C];
    K=1/2[I,J];
    path cd;
    cd=(fullcircle scaled 6mm) shifted K;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((I{dir(210+angle(I-J))}..{dir(150+angle(I-J))}K) cutafter cd);
    drawarrow reverse((J{dir(210+angle(J-I))}..{dir(150+angle(J-I))}K) cutafter cd);
    draw cd;
    label(btex $//$ etex ,K);
    drawoptions();
  \end{mplibcode}
  \mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesThales]{Echelle};boolean CouleursNum,CouleursDen;
    CouleursNum=\useKV[ClesThales]{CouleursNum};
    CouleursDen=\useKV[ClesThales]{CouleursDen};
    color CouleurNum,CouleurDen;
    if CouleursNum:
    CouleurNum=\useKV[ClesThales]{CouleurNum}
    else:
    CouleurNum=black
    fi;
    if CouleursDen:
    CouleurDen=\useKV[ClesThales]{CouleurDen}
    else:
    CouleurDen=black
    fi;}]
    pair A,B,C,M,N,O;%
    O=(2.5u,2.5u);
    path cc;
    cc=(fullcircle scaled 3u) shifted O;
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.1*length cc) of cc;
    B=A rotatedabout(O,130);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    M=1.4[B,A];
    N=1.4[C,A];
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..1.15[A,B]{dir(angle(B-A)+5)};
    cotes2=1.15[C,B]{dir(angle(C-B)+5)}..1.15[B,C]{dir(angle(C-B)+5)};
    cotes3=1.15[A,C]{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    cotes5=A{dir(angle(M-A)+5)}..1.15[A,M]{dir(angle(M-A)+5)};
    cotes6=A{dir(angle(N-A)+5)}..1.15[A,N]{dir(angle(N-A)+5)};
    for k=1 upto 6:
    draw cotes[k];
    endfor;
    if CouleursDen:
    drawoptions(dashed evenly withpen pencircle scaled 1.5 withcolor CouleurDen);
    draw (cotes[1] cutafter cotes[2]);
    draw (cotes[2] cutbefore cotes[1] cutafter cotes[3]);
    draw (cotes[3] cutbefore cotes[2]);
    drawoptions();
    fi;
    if CouleursNum:
    drawoptions(dashed evenly withpen pencircle scaled 1.5 withcolor CouleurNum);
    draw (cotes[5] cutafter cotes[4]);
    draw (cotes[4] cutbefore cotes[5] cutafter cotes[6]);
    draw (cotes[6] cutafter cotes[4]);
    drawoptions();
    fi;
    pair I;
    % On d\'efinit le centre du cercle inscrit \`a AMC
    (I-C) rotated ((angle(A-C)-angle(M-C))/2) shifted C=whatever[A,C];
    (I-M) rotated ((angle(C-M)-angle(A-M))/2) shifted M=whatever[M,C];
    %on labelise
    label(btex #1 etex,I);
    label(btex #2 etex,1.2[M,B]);
    label(btex #3 etex,1.2[N,C]);
    label(btex #4 etex,1.1[B,M]);
    label(btex #5 etex,1.1[C,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes5 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes6 intersectionpoint cotes4);
    pair I,J,K;
    I=1.1[N,M];
    J=1.1[B,C];
    K=1/2[I,J];
    path cd;
    cd=(fullcircle scaled 6mm) shifted K;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((I{dir(210+angle(I-J))}..{dir(150+angle(I-J))}K) cutafter cd);
    drawarrow reverse((J{dir(210+angle(J-I))}..{dir(150+angle(J-I))}K) cutafter cd);
    draw cd;
    label(btex $//$ etex ,K);
    drawoptions();
  \end{mpost}
  \fi
}

%On d\'efinit la deuxi\`eme figure \`a utiliser
\def\MPFigReciThalesCroisee#1#2#3#4#5#6{%
  % #1 Premier sommet
    % #2 Deuxi\`eme sommet
    % #3 Troisi\`eme sommet
    % #4 point sur la droite #1#2
    % #5 point sur la droite #1#3
  \ifluatex
  \mplibforcehmode
  \mplibcodeinherit{enable}
  \begin{mplibcode}
    u:=\useKV[ClesThales]{Echelle};
    pair A,B,C,M,N,O;%
    O=(2.5u,2.5u);
    path cc;
    cc=(fullcircle scaled 3u) shifted O;
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.1*length cc) of cc;
    B=A rotatedabout(O,130);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    M=1.4[B,A];
    N=1.4[C,A];
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..1.15[A,B]{dir(angle(B-A)+5)};
    cotes2=1.15[C,B]{dir(angle(C-B)+5)}..1.15[B,C]{dir(angle(C-B)+5)};
    cotes3=1.15[A,C]{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    cotes5=A{dir(angle(M-A)+5)}..1.15[A,M]{dir(angle(M-A)+5)};
    cotes6=A{dir(angle(N-A)+5)}..1.15[A,N]{dir(angle(N-A)+5)};
    for k=1 upto 6:
    draw cotes[k];
    endfor;
    pair I;
    % On d\'efinit le centre du cercle inscrit \`a AMC
    (I-C) rotated ((angle(A-C)-angle(M-C))/2) shifted C=whatever[A,C];
    (I-M) rotated ((angle(C-M)-angle(A-M))/2) shifted M=whatever[M,C];
    %on labelise
    label(btex #1 etex,I);
    label(btex #2 etex,1.2[M,B]);
    label(btex #3 etex,1.2[N,C]);
    label(btex #4 etex,1.1[B,M]);
    label(btex #5 etex,1.1[C,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes5 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes6 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes1 intersectionpoint cotes2);
    fill (fullcircle scaled 0.75mm) shifted (cotes3 intersectionpoint cotes2);
  \end{mplibcode}
  \mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesThales]{Echelle};}]
    pair A,B,C,M,N,O;%
    O=(2.5u,2.5u);
    path cc;
    cc=(fullcircle scaled 3u) shifted O;
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=point(0.1*length cc) of cc;
    B=A rotatedabout(O,130);
    C=(A--2[A,B rotatedabout(A,45)]) intersectionpoint (B--2[B,A rotatedabout(B,-60)]);
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#6);
    B:=B rotatedabout(O,#6);
    C:=C rotatedabout(O,#6);
    % on dessine \`a main lev\'ee :)
    M=1.4[B,A];
    N=1.4[C,A];
    path cotes[];
    cotes1=A{dir(angle(B-A)+5)}..1.15[A,B]{dir(angle(B-A)+5)};
    cotes2=1.15[C,B]{dir(angle(C-B)+5)}..1.15[B,C]{dir(angle(C-B)+5)};
    cotes3=1.15[A,C]{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    cotes4=1.5[N,M]{dir(angle(N-M)+5)}..1.5[M,N]{dir(angle(N-M)+5)};
    cotes5=A{dir(angle(M-A)+5)}..1.15[A,M]{dir(angle(M-A)+5)};
    cotes6=A{dir(angle(N-A)+5)}..1.15[A,N]{dir(angle(N-A)+5)};
    for k=1 upto 6:
    draw cotes[k];
    endfor;
    pair I;
    % On d\'efinit le centre du cercle inscrit \`a AMC
    (I-C) rotated ((angle(A-C)-angle(M-C))/2) shifted C=whatever[A,C];
    (I-M) rotated ((angle(C-M)-angle(A-M))/2) shifted M=whatever[M,C];
    %on labelise
    label(btex #1 etex,I);
    label(btex #2 etex,1.2[M,B]);
    label(btex #3 etex,1.2[N,C]);
    label(btex #4 etex,1.1[B,M]);
    label(btex #5 etex,1.1[C,N]);
    fill (fullcircle scaled 0.75mm) shifted (cotes5 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes6 intersectionpoint cotes4);
    fill (fullcircle scaled 0.75mm) shifted (cotes1 intersectionpoint cotes2);
    fill (fullcircle scaled 0.75mm) shifted (cotes3 intersectionpoint cotes2);
  \end{mpost}
  \fi
}

\newcommand\RedactionThales{}%
\newcommand\EcritureCalculs{}%
\newcommand\EcritureQuotients{}%

%%%
\newcommand\TTThales[6][]{%
  \useKVdefault[ClesThales]%
  \setKV[ClesThales]{#1}%
  \ifboolKV[ClesThales]{Perso}{\RedactionThales}{%
    \ifboolKV[ClesThales]{Droites}{%
      Les droites \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{$(#3#5)$} et \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{$(#4#6)$} sont s\'ecantes en \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{$#2$}.%
    }{%
      Dans le triangle \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{$#2#3#4$}, \ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{$#5$} est un point \ifboolKV[ClesThales]{Segment}{du segment}{de la
        droite}
      \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{\ifboolKV[ClesThales]{Segment}{$[#2#3]$}{$(#2#3)$}},
      \ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{$#6$} est un
      point \ifboolKV[ClesThales]{Segment}{du segment}{de la droite}
      \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{\ifboolKV[ClesThales]{Segment}{$[#2#4]$}{$(#2#4)$}}.%
    }
    \\Comme les droites \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{$(#5#6)$} et \ifboolKV[ClesThales]{Remediation}{\pointilles[2cm]}{$(#3#4)$} sont parall\`eles, alors \ifboolKV[ClesThales]{Propor}{le tableau%
      \[\begin{array}{c|c|c}
          \ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{#2#5}&\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{#2#6}&\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{#5#6}\\
          \hline
          \ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{#2#3}&\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{#2#4}&\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{#3#4}\\
        \end{array}
      \]
      est un tableau de proportionnalit\'e\ifboolKV[ClesThales]{Segment}{.}{ d'apr\`es le th\'eor\`eme de Thal\`es.}%
    }{%
      \ifboolKV[ClesThales]{Segment}{on a :}{le th\'eor\`eme de Thal\`es permet d'\'ecrire :}%
      \[\frac{\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{\ifboolKV[ClesThales]{CouleursNum}{\mathcolor{\useKV[ClesThales]{CouleurNum}}{#2#5}}{#2#5}}}{\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{\ifboolKV[ClesThales]{CouleursDen}{\mathcolor{\useKV[ClesThales]{CouleurDen}}{#2#3}}{#2#3}}}=\frac{\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{\ifboolKV[ClesThales]{CouleursNum}{\mathcolor{\useKV[ClesThales]{CouleurNum}}{#2#6}}{#2#6}}}{\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{\ifboolKV[ClesThales]{CouleursDen}{\mathcolor{\useKV[ClesThales]{CouleurDen}}{#2#4}}{#2#4}}}=\frac{\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{\ifboolKV[ClesThales]{CouleursNum}{\mathcolor{\useKV[ClesThales]{CouleurNum}}{#5#6}}{#5#6}}}{\ifboolKV[ClesThales]{Remediation}{\pointilles[1cm]}{\ifboolKV[ClesThales]{CouleursDen}{\mathcolor{\useKV[ClesThales]{CouleurDen}}{#3#4}}{#3#4}}}\]%
    }%
  }%
}%

\newcommand\TThalesCalculsD[8][]{%
  \setKV[ClesThales]{#1}%
  \newcount\zzz\newcount\yyy\newcount\xxx%Pour se rappeller des calculs \`a faire et combien en faire%
  \def\Nomx{}%
  \def\Nomy{}%
  \def\Nomz{}%
  \zzz=0\yyy=0\xxx=0%
  \TTThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}\par
\IfDecimal{#3}{%
  \IfDecimal{#6}{}{%
    \IfDecimal{#4}{%
        \IfDecimal{#7}{%
          \xxx=5263%#6&=\frac{#3\times#7}{#4}\\
          \edef\Nomx{#6}\opcopy{#3}{valx}\opcopy{#7}{Valx}\opcopy{#4}{denox}%
          \xdef\ResultatThalesx{\fpeval{round(#3*#7/#4,\useKV[ClesThales]{Precision})}}%
        }{%
          \IfDecimal{#8}{\IfDecimal{#5}{\xxx=5274%\[#6=\frac{#3\times#8}{#5}\]
              \edef\Nomx{#6}\opcopy{#3}{valx}\opcopy{#8}{Valx}\opcopy{#5}{denox}%
              \xdef\ResultatThalesx{\fpeval{round(#3*#8/#5,\useKV[ClesThales]{Precision})}}%
          }{}}{}
        }
      }{\IfDecimal{#8}{\IfDecimal{#5}{\xxx=5274%\[#6=\frac{#3\times#8}{#5}\]
            \edef\Nomx{#6}\opcopy{#3}{valx}\opcopy{#8}{Valx}\opcopy{#5}{denox}%
            \xdef\ResultatThalesx{\fpeval{round(#3*#8/#5,\useKV[ClesThales]{Precision})}}%
          }{}}{}
      }
    }
  }{%
    \IfDecimal{#6}{%
      \IfDecimal{#4}{%
        \IfDecimal{#7}{%
          \xxx=2536%\[#3=\frac{#6\times#4}{#7}\]%
          \edef\Nomx{#3}\opcopy{#6}{valx}\opcopy{#4}{Valx}\opcopy{#7}{denox}%
          \xdef\ResultatThalesx{\fpeval{round(#6*#4/#7,\useKV[ClesThales]{Precision})}}%
        }{%
          \IfDecimal{#5}{\IfDecimal{#8}{\xxx=2547
              \edef\Nomx{#3}\opcopy{#6}{valx}\opcopy{#5}{Valx}\opcopy{#8}{denox}%\[#3=\frac{#6\times#5}{#8}\]
              \xdef\ResultatThalesx{\fpeval{round(#6*#5/#8,\useKV[ClesThales]{Precision})}}%
            }{}}{}
        }
      }{\IfDecimal{#5}{\IfDecimal{#8}{\xxx=2547
            \edef\Nomx{#3}\opcopy{#6}{valx}\opcopy{#5}{Valx}\opcopy{#8}{denox}%\[#3=\frac{#6\times#5}{#8}\]
            \xdef\ResultatThalesx{\fpeval{round(#6*#5/#8,\useKV[ClesThales]{Precision})}}%
          }{}}{}
      }
    }{}
  }%
  % 
  \IfDecimal{#4}{%
    \IfDecimal{#7}{}{%
      \IfDecimal{#5}{%
        \IfDecimal{#8}{%
          \yyy=6374%\[#7=\frac{#4\times#8}{#5}\]%
          \edef\Nomy{#7}\opcopy{#4}{valy}\opcopy{#8}{Valy}\opcopy{#5}{denoy}%
          \xdef\ResultatThalesy{\fpeval{round(#4*#8/#5,\useKV[ClesThales]{Precision})}}%
        }{%
          \IfDecimal{#6}{\IfDecimal{#3}{\yyy=6352%\[#7=\frac{#4\times#6}{#3}\]
              \edef\Nomy{#7}\opcopy{#4}{valy}\opcopy{#6}{Valy}\opcopy{#3}{denoy}%
              \xdef\ResultatThalesy{\fpeval{round(#4*#6/#3,\useKV[ClesThales]{Precision})}}%
            }{}}{}
        }
      }{\IfDecimal{#6}{\IfDecimal{#3}{\yyy=6352%\[#7=\frac{#4\times#6}{#3}\]
            \edef\Nomy{#7}\opcopy{#4}{valy}\opcopy{#6}{Valy}\opcopy{#3}{denoy}%
            \xdef\ResultatThalesy{\fpeval{round(#4*#6/#3,\useKV[ClesThales]{Precision})}}%
            }{}}{}
      }
    }
  }{%
    \IfDecimal{#7}{%
      \IfDecimal{#5}{%
        \IfDecimal{#8}{%
          \yyy=3647%\[#4=\frac{#7\times#5}{#8}\]%
          \edef\Nomy{#4}\opcopy{#7}{valy}\opcopy{#5}{Valy}\opcopy{#8}{denoy}%
          \xdef\ResultatThalesy{\fpeval{round(#7*#5/#8,\useKV[ClesThales]{Precision})}}%
        }{%
          \IfDecimal{#3}{\IfDecimal{#6}{\yyy=3625%\[#4=\frac{#7\times#3}{#6}\]
              \edef\Nomy{#4}\opcopy{#7}{valy}\opcopy{#3}{Valy}\opcopy{#6}{denoy}%
              \xdef\ResultatThalesy{\fpeval{round(#7*#3/#6,\useKV[ClesThales]{Precision})}}%
            }{}}{}
        }
      }{\IfDecimal{#3}{\IfDecimal{#6}{\yyy=3625%\[#4=\frac{#7\times#3}{#6}\]
            \edef\Nomy{#4}\opcopy{#7}{valy}\opcopy{#3}{Valy}\opcopy{#6}{denoy}%
            \xdef\ResultatThalesy{\fpeval{round(#7*#3/#6,\useKV[ClesThales]{Precision})}}%
            }{}}{}
      }}{}}%
  % 
  \IfDecimal{#5}{%
    \IfDecimal{#8}{}{%
      \IfDecimal{#4}{
        \IfDecimal{#7}{
          \zzz=7463%\[#8=\frac{#5\times#7}{#4}\]%
          \edef\Nomz{#8}\opcopy{#5}{valz}\opcopy{#7}{Valz}\opcopy{#4}{denoz}%
          \xdef\ResultatThalesz{\fpeval{round(#5*#7/#4,\useKV[ClesThales]{Precision})}}%
        }{%
          \IfDecimal{#3}{\IfDecimal{#6}{\zzz=7452%\[#8=\frac{#5\times#6}{#3}\]
              \edef\Nomz{#8}\opcopy{#5}{valz}\opcopy{#6}{Valz}\opcopy{#3}{denoz}%
              \xdef\ResultatThalesz{\fpeval{round(#5*#6/#3,\useKV[ClesThales]{Precision})}}%
            }{}}{}
        }
      }{\IfDecimal{#3}{\IfDecimal{#6}{\zzz=7452%\[#8=\frac{#5\times#6}{#3}\]
            \edef\Nomz{#8}\opcopy{#5}{valz}\opcopy{#6}{Valz}\opcopy{#3}{denoz}%
            \xdef\ResultatThalesz{\fpeval{round(#5*#6/#3,\useKV[ClesThales]{Precision})}}%
            }{}}{}
      }
    }
  }{%
    \IfDecimal{#8}{%
      \IfDecimal{#4}{%
        \IfDecimal{#7}{%
          \zzz=4736% \[#5=\frac{#8\times#4}{#7}\]%
          \edef\Nomz{#5}\opcopy{#8}{valz}\opcopy{#4}{Valz}\opcopy{#7}{denoz}%
          \xdef\ResultatThalesz{\fpeval{round(#8*#4/#7,\useKV[ClesThales]{Precision})}}%
        }{%
          \IfDecimal{#3}{\IfDecimal{#6}{\zzz=4725%\[#5=\frac{#8\times#3}{#6}\]
              \edef\Nomz{#5}\opcopy{#8}{valz}\opcopy{#3}{Valz}\opcopy{#6}{denoz}%
              \xdef\ResultatThalesz{\fpeval{round(#8*#3/#6,\useKV[ClesThales]{Precision})}}%
            }{}}{}
        }
      }{\IfDecimal{#3}{\IfDecimal{#6}{\zzz=4725%\[#5=\frac{#8\times#3}{#6}\]
            \edef\Nomz{#5}\opcopy{#8}{valz}\opcopy{#3}{Valz}\opcopy{#6}{denoz}%
            \xdef\ResultatThalesz{\fpeval{round(#8*#3/#6,\useKV[ClesThales]{Precision})}}%
            }{}}{}
      }}{}
  }%  
  %%
  \StrMid{\the\zzz}{1}{1}[\cmza]%
  \StrMid{\the\yyy}{1}{1}[\cmya]%
  \StrMid{\the\xxx}{1}{1}[\cmxa]%
  \ifboolKV[ClesThales]{Calcul}{%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%
  \ifboolKV[ClesThales]{IntroCalculs}{On remplace par les longueurs connues :}{}%
  \ifboolKV[ClesThales]{CalculsPerso}{%
    \EcritureQuotients%
  }{%
    \ifboolKV[ClesThales]{Propor}{%
      \[\begin{array}{c|c|c}
          \IfDecimal{#3}{\num{#3}}{#3}&\IfDecimal{#4}{\num{#4}}{#4}&\IfDecimal{#5}{\num{#5}}{#5}\\
          \hline
          \IfDecimal{#6}{\num{#6}}{#6}&\IfDecimal{#7}{\num{#7}}{#7}&\IfDecimal{#8}{\num{#8}}{#8}
        \end{array}
      \]
    }{%
      \[\frac{\IfDecimal{#3}{\num{#3}}{#3}}{\IfDecimal{#6}{\num{#6}}{#6}}=\frac{\IfDecimal{#4}{\num{#4}}{#4}}{\IfDecimal{#7}{\num{#7}}{#7}}=\frac{\IfDecimal{#5}{\num{#5}}{#5}}{\IfDecimal{#8}{\num{#8}}{#8}}\]
    }%
  }%
  % On choisit \'eventuellement le calcul \`a faire s'il y en a plusieurs.
  \xdef\CompteurCalcul{\useKV[ClesThales]{ChoixCalcul}}%
  \xintifboolexpr{\CompteurCalcul>0}{\xintifboolexpr{\CompteurCalcul==1}{\xdef\cmya{0}\xdef\cmza{0}}{\xintifboolexpr{\CompteurCalcul==2}{\xdef\cmxa{0}\xdef\cmza{0}}{\xdef\cmxa{0}\xdef\cmya{0}}}}{}%
  %% on fait les calculs
  \ifboolKV[ClesThales]{CalculsPerso}{%
    \EcritureCalculs%
  }{%
    \begin{align*}
      % Premier compteur \xxx
      \ifnum\cmxa>0
      \Nomx\uppercase{&}=\frac{\opexport{valx}{\valx}\num{\valx}\times\opexport{Valx}{\Valx}\num{\Valx}}{\opexport{denox}{\denox}\num{\denox}}\relax%\global\numx=\numexpr\opprint{valx}*\opprint{Valx}\relax
    \fi
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \ifnum\cmxa=0
      \else
        \uppercase{&}
      \fi%
      \Nomy\uppercase{&}=\frac{\opexport{valy}{\valy}\num{\valy}\times\opexport{Valy}{\Valy}\num{\Valy}}{\opexport{denoy}{\denoy}\num{\denoy}}\relax%\global\numy=\numexpr\opprint{valy}*\opprint{Valy}\relax
    \fi
    % Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \ifnum\cmxa=0
        \ifnum\cmya=0                           
          %
        \else
          \uppercase{&}
        \fi
        \Nomz\uppercase{&}=\frac{\opexport{valz}{\valz}\num{\valz}\times\opexport{Valz}{\Valz}\num{\Valz}}{\opexport{denoz}{\denoz}\num{\denoz}}\relax%\global\numz=\numexpr\opprint{valz}*\opprint{Valz}\relax
      \else
        \uppercase{&}\Nomz\uppercase{&}=\frac{\opexport{valz}{\valz}\num{\valz}\times\opexport{Valz}{\Valz}\num{\Valz}}{\opexport{denoz}{\denoz}\num{\denoz}}\relax%\global\numz=\numexpr\opprint{valz}*\opprint{Valz}\relax
      \fi
    \fi
    \\
%    % 2eme ligne du tableau : calcul des num\'erateurs
%        %Premier compteur \xxx
    \ifnum\cmxa>0
      \Nomx\uppercase{&}=\frac{\opmul*{valx}{Valx}{numx}\opexport{numx}{\numx}\num{\numx}}{\opexport{denox}{\denox}\num{\denox}}
    \fi
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \ifnum\cmxa=0
        %
      \else
        \uppercase{&}
      \fi
      \Nomy\uppercase{&}=\frac{\opmul*{valy}{Valy}{numy}\opexport{numy}{\numy}\num{\numy}}{\opexport{denoy}{\denoy}\num{\denoy}}%
    \fi
%    %Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \ifnum\cmxa=0
        \ifnum\cmya=0                           
          %
        \else
          \uppercase{&}
        \fi
        \Nomz\uppercase{&}=\frac{\opmul*{valz}{Valz}{numz}\opexport{numz}{\numz}\num{\numz}}{\opexport{denoz}{\denoz}\num{\denoz}}
      \else
        \uppercase{&}\Nomz\uppercase{&}=\frac{\opmul*{valz}{Valz}{numz}\opexport{numz}{\numz}\num{\numz}}{\opexport{denoz}{\denoz}\num{\denoz}}
      \fi
    \fi
    \\
%    % 3eme ligne : Calculs
    \ifnum\cmxa>0
      \Nomx\uppercase{&}\opdiv*{numx}{denox}{resultatx}{restex}\opcmp{restex}{0}\ifopeq=\SI{\ResultatThalesx}{\PfCThalesUnit}\else\approx\SI{\fpeval{round(\ResultatThalesx,\useKV[ClesThales]{Precision})}}{\PfCThalesUnit}\fi%
    \fi
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \ifnum\cmxa=0
        %
      \else
        \uppercase{&}
      \fi
      \Nomy\uppercase{&}\opdiv*{numy}{denoy}{resultaty}{restey}\opcmp{restey}{0}\ifopeq=\SI{\ResultatThalesy}{\PfCThalesUnit}\else\approx\SI{\fpeval{round(\ResultatThalesy,\useKV[ClesThales]{Precision})}}{\PfCThalesUnit}\fi%
    \fi
%    %Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \ifnum\cmxa=0
        \ifnum\cmya=0                           
          %
        \else
          \uppercase{&}
        \fi
        \Nomz\uppercase{&}\opdiv*{numz}{denoz}{resultatz}{restez}\opcmp{restez}{0}\ifopeq=\SI{\ResultatThalesz}{\PfCThalesUnit}\else\approx\SI{\fpeval{round(\ResultatThalesz,\useKV[ClesThales]{Precision})}}{\PfCThalesUnit}\fi%
      \else
        \uppercase{&}\Nomz\uppercase{&}\opdiv*{numz}{denoz}{resultatz}{restez}\opcmp{restez}{0}\ifopeq=\SI{\ResultatThalesz}{\PfCThalesUnit}\else\approx\SI{\fpeval{round(\ResultatThalesz,\useKV[ClesThales]{Precision})}}{\PfCThalesUnit}\fi%
      \fi
    \fi
    \end{align*}
    }
}{}
}

\newcommand\TThalesCalculsE[8][]{%
  \setKV[ClesThales]{#1}%
  \newcount\zzz\newcount\yyy\newcount\xxx%Pour se rappeller des calculs \`a faire et combien en faire%
  \newcount\valx\newcount\Valx%
  \newcount\valy\newcount\Valy%
  \newcount\valz\newcount\Valz%
  \newcount\numx\newcount\numy\newcount\numz%
  \newcount\denox\newcount\denoy\newcount\denoz%
  \def\Nomx{}%
  \def\Nomy{}%
  \def\Nomz{}%
  \zzz=0\yyy=0\xxx=0%
  \TTThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}\par%
\IfDecimal{#3}{%
  \IfDecimal{#6}{}{%
    \IfDecimal{#4}{%
        \IfDecimal{#7}{%
          \xxx=5263%#6&=\frac{#3\times#7}{#4}\\
          \edef\Nomx{#6}\valx=#3\Valx=#7\denox=#4%
        }{%
          \IfDecimal{#8}{\IfDecimal{#5}{\xxx=5274%\[#6=\frac{#3\times#8}{#5}\]
            \edef\Nomx{#6}\valx=#3\Valx=#8\denox=#5%
          }{}}{}
        }
      }{\IfDecimal{#8}{\IfDecimal{#5}{\xxx=5274%\[#6=\frac{#3\times#8}{#5}\]
            \edef\Nomx{#6}\valx=#3\Valx=#8\denox=#5%
          }{}}{}
      }
    }
  }{%
    \IfDecimal{#6}{%
      \IfDecimal{#4}{%
        \IfDecimal{#7}{%
          \xxx=2536%\[#3=\frac{#6\times#4}{#7}\]%
          \edef\Nomx{#3}\valx=#6\Valx=#4\denox=#7%
        }{%
          \IfDecimal{#5}{\IfDecimal{#8}{\xxx=2547
            \edef\Nomx{#3}\valx=#6\Valx=#5\denox=#8%\[#3=\frac{#6\times#5}{#8}\]
            }{}}{}
        }
      }{\IfDecimal{#5}{\IfDecimal{#8}{\xxx=2547
            \edef\Nomx{#3}\valx=#6\Valx=#5\denox=#8%\[#3=\frac{#6\times#5}{#8}\]
            }{}}{}
      }
    }{}
  }%
  % 
  \IfDecimal{#4}{%
    \IfDecimal{#7}{}{%
      \IfDecimal{#5}{%
        \IfDecimal{#8}{%
          \yyy=6374%\[#7=\frac{#4\times#8}{#5}\]%
          \edef\Nomy{#7}\valy=#4\Valy=#8\denoy=#5%
        }{%
          \IfDecimal{#6}{\IfDecimal{#3}{\yyy=6352%\[#7=\frac{#4\times#6}{#3}\]
            \edef\Nomy{#7}\valy=#4\Valy=#6\denoy=#3%
            }{}}{}
        }
      }{\IfDecimal{#6}{\IfDecimal{#3}{\yyy=6352%\[#7=\frac{#4\times#6}{#3}\]
            \edef\Nomy{#7}\valy=#4\Valy=#6\denoy=#3%
            }{}}{}
      }
    }
  }{%
    \IfDecimal{#7}{%
      \IfDecimal{#5}{%
        \IfDecimal{#8}{%
          \yyy=3647%\[#4=\frac{#7\times#5}{#8}\]%
          \edef\Nomy{#4}\valy=#7\Valy=#5\denoy=#8%
        }{%
          \IfDecimal{#3}{\IfDecimal{#6}{\yyy=3625%\[#4=\frac{#7\times#3}{#6}\]
            \edef\Nomy{#4}\valy=#7\Valy=#3\denoy=#6%
            }{}}{}
        }
      }{\IfDecimal{#3}{\IfDecimal{#6}{\yyy=3625%\[#4=\frac{#7\times#3}{#6}\]
            \edef\Nomy{#4}\valy=#7\Valy=#3\denoy=#6%
            }{}}{}
      }}{}}%
  % 
  \IfDecimal{#5}{%
    \IfDecimal{#8}{}{%
      \IfDecimal{#4}{
        \IfDecimal{#7}{
          \zzz=7463%\[#8=\frac{#5\times#7}{#4}\]%
          \edef\Nomz{#8}\valz=#5\Valz=#7\denoz=#4%
        }{%
          \IfDecimal{#3}{\IfDecimal{#6}{\zzz=7452%\[#8=\frac{#5\times#6}{#3}\]
            \edef\Nomz{#8}\valz=#5\Valz=#6\denoz=#3%
            }{}}{}
        }
      }{\IfDecimal{#3}{\IfDecimal{#6}{\zzz=7452%\[#8=\frac{#5\times#6}{#3}\]
            \edef\Nomz{#8}\valz=#5\Valz=#6\denoz=#3%
            }{}}{}
      }
    }
  }{%
    \IfDecimal{#8}{%
      \IfDecimal{#4}{%
        \IfDecimal{#7}{%
          \zzz=4736% \[#5=\frac{#8\times#4}{#7}\]%
          \edef\Nomz{#5}\valz=#8\Valz=#4\denoz=#7%
        }{%
          \IfDecimal{#3}{\IfDecimal{#6}{\zzz=4725%\[#5=\frac{#8\times#3}{#6}\]
            \edef\Nomz{#5}\valz=#8\Valz=#3\denoz=#6%
            }{}}{}
        }
      }{\IfDecimal{#3}{\IfDecimal{#6}{\zzz=4725%\[#5=\frac{#8\times#3}{#6}\]
            \edef\Nomz{#5}\valz=#8\Valz=#3\denoz=#6%
            }{}}{}
      }}{}
  }%  
  %%
\StrMid{\the\zzz}{1}{1}[\cmza]%
\StrMid{\the\yyy}{1}{1}[\cmya]%
\StrMid{\the\xxx}{1}{1}[\cmxa]%
\ifboolKV[ClesThales]{Calcul}{%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%
  On remplace par les longueurs connues :
  \ifboolKV[ClesThales]{Propor}{%
    \[\begin{array}{c|c|c}
        \IfDecimal{#3}{\num{#3}}{#3}&\IfDecimal{#4}{\num{#4}}{#4}&\IfDecimal{#5}{\num{#5}}{#5}\\
        \hline
        \IfDecimal{#6}{\num{#6}}{#6}&\IfDecimal{#7}{\num{#7}}{#7}&\IfDecimal{#8}{\num{#8}}{#8}\\
      \end{array}
    \]
  }{%
    \[\frac{\IfDecimal{#3}{\num{#3}}{#3}}{\IfDecimal{#6}{\num{#6}}{#6}}=\frac{\IfDecimal{#4}{\num{#4}}{#4}}{\IfDecimal{#7}{\num{#7}}{#7}}=\frac{\IfDecimal{#5}{\num{#5}}{#5}}{\IfDecimal{#8}{\num{#8}}{#8}}\]
  }%
  % On choisit \'eventuellement le calcul \`a faire s'il y en a plusieurs.
  \xdef\CompteurCalcul{\useKV[ClesThales]{ChoixCalcul}}%
  \xintifboolexpr{\CompteurCalcul>0}{\xintifboolexpr{\CompteurCalcul==1}{\xdef\cmya{0}\xdef\cmza{0}}{\xintifboolexpr{\CompteurCalcul==2}{\xdef\cmxa{0}\xdef\cmza{0}}{\xdef\cmxa{0}\xdef\cmya{0}}}}%
  %%on fait les calculs
\begin{align*}
    %Premier compteur \xxx
    \ifnum\cmxa>0
      \Nomx\uppercase{&}=\frac{\the\valx\times\the\Valx}{\the\denox}\global\numx=\numexpr\the\valx*\the\Valx\relax
    \fi
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \ifnum\cmxa=0
      \else
        \uppercase{&}
      \fi%
      \Nomy\uppercase{&}=\frac{\the\valy\times\the\Valy}{\the\denoy}\global\numy=\numexpr\the\valy*\the\Valy\relax
     % \else
     %   \uppercase{&}\Nomy\uppercase{&}=\frac{\the\valy\times\the\Valy}{\the\denoy}\global\numy=\numexpr\the\valy*\the\Valy\relax
     % \fi
    \fi
    % Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \ifnum\cmxa=0
        \ifnum\cmya=0                           
          %\Nomz\uppercase{&}=\frac{\the\valz\times\the\Valz}{\the\denoz}\global\numz=\numexpr\the\valz*\the\Valz\relax
        \else
          \uppercase{&}%\Nomz\uppercase{&}=\frac{\the\valz\times\the\Valz}{\the\denoz}\global\numz=\numexpr\the\valz*\the\Valz\relax
        \fi
        \Nomz\uppercase{&}=\frac{\the\valz\times\the\Valz}{\the\denoz}\global\numz=\numexpr\the\valz*\the\Valz\relax
      \else
        \uppercase{&}\Nomz\uppercase{&}=\frac{\the\valz\times\the\Valz}{\the\denoz}\global\numz=\numexpr\the\valz*\the\Valz\relax
      \fi
    \fi
    \\
    % 2eme ligne du tableau : calcul des num\'erateurs
        %Premier compteur \xxx
    \ifnum\cmxa>0
      \Nomx\uppercase{&}=\frac{\num{\the\numx}}{\num{\the\denox}}
    \fi
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \ifnum\cmxa=0
        %\Nomy\uppercase{&}=\frac{\num{\the\numy}}{\num{\the\denoy}}
      \else
        \uppercase{&}%\Nomy\uppercase{&}=\frac{\num{\the\numy}}{\num{\the\denoy}}
      \fi
      \Nomy\uppercase{&}=\frac{\num{\the\numy}}{\num{\the\denoy}}%
    \fi
    %Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \ifnum\cmxa=0
        \ifnum\cmya=0                           
          %\Nomz\uppercase{&}=\frac{\num{\the\numz}}{\num{\the\denoz}}
        \else
          \uppercase{&}%\Nomz\uppercase{&}=\frac{\num{\the\numz}}{\num{\the\denoz}}
        \fi
        \Nomz\uppercase{&}=\frac{\num{\the\numz}}{\num{\the\denoz}}
      \else
        \uppercase{&}\Nomz\uppercase{&}=\frac{\num{\the\numz}}{\num{\the\denoz}}
      \fi
    \fi
    \\
    % 3eme ligne : faire les simplifications ou pas ?
    %Premier compteur \xxx
    \ifnum\cmxa>0
      \PGCD{\the\numx}{\the\denox}
      \ifnum\pgcd>1
        \Nomx\uppercase{&}=\SSimpli{\the\numx}{\the\denox}
      \else
        \uppercase{&}
      \fi
    \fi                    
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \PGCD{\the\numy}{\the\denoy}
      \ifnum\cmxa=0
         \ifnum\pgcd>1
           \Nomy\uppercase{&}=\SSimpli{\the\numy}{\the\denoy}
         \else
           \uppercase{&}
         \fi
      \else
        \ifnum\pgcd>1
          \uppercase{&}\Nomy\uppercase{&}=\SSimpli{\the\numy}{\the\denoy}
        \else
          \uppercase{&&}
        \fi
      \fi
    \fi
    %Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \PGCD{\the\numz}{\the\denoz}
      \ifnum\cmxa=0
        \ifnum\cmya=0
          \ifnum\pgcd>1
            \Nomz\uppercase{&}=\SSimpli{\the\numz}{\the\denoz}
          \else
            \uppercase{&}
          \fi
        \else
          \ifnum\pgcd>1
            \uppercase{&}\Nomz\uppercase{&}=\SSimpli{\the\numz}{\the\denoz}
          \else
            \uppercase{&&}
          \fi
        \fi
      \else
        \ifnum\pgcd>1
          \uppercase{&}\Nomz\uppercase{&}=\SSimpli{\the\numz}{\the\denoz}
        \else
          \uppercase{&&}
        \fi
      \fi
    \fi
    \\
    % 4eme ligne : Terminer les simplifications ?
    %Premier compteur \xxx
    \ifnum\cmxa>0
      \PGCD{\the\numx}{\the\denox}
      \ifnum\pgcd>1
        \ifnum\pgcd<\the\denox
          \Nomx\uppercase{&}=\SSimplifie{\the\numx}{\the\denox}
        \else
          \uppercase{&}
        \fi
      \else
        \uppercase{&}
      \fi
    \fi                    
    %    % Deuxi\`eme compteur \yyy
    \ifnum\cmya>0
      \PGCD{\the\numy}{\the\denoy}
      \ifnum\cmxa=0
        \ifnum\pgcd>1
          \ifnum\pgcd<\the\denoy
            \Nomy\uppercase{&}=\SSimplifie{\the\numy}{\the\denoy}
          \else
            \uppercase{&}
          \fi
         \else
           \uppercase{&}
         \fi
      \else
        \ifnum\pgcd>1
          \ifnum\pgcd<\the\denoy
            \uppercase{&}\Nomy\uppercase{&}=\SSimplifie{\the\numy}{\the\denoy}
          \else
            \uppercase{&&}
          \fi
        \else
          \uppercase{&&}
        \fi
      \fi
    \fi
    %Troisi\`eme compteur \zzz
    \ifnum\cmza>0
      \PGCD{\the\numz}{\the\denoz}
      \ifnum\cmxa=0
        \ifnum\cmya=0
          \ifnum\pgcd>1
            \ifnum\pgcd<\the\denoz
              \Nomz\uppercase{&}=\SSimplifie{\the\numz}{\the\denoz}
            \else
              \uppercase{&}
            \fi
          \else
            \uppercase{&}
          \fi
        \else
          \ifnum\pgcd>1
            \ifnum\pgcd<\the\denoz
              \uppercase{&}\Nomz\uppercase{&}=\SSimplifie{\the\numz}{\the\denoz}
            \else
              \uppercase{&&}
            \fi
          \else
            \uppercase{&&}
          \fi
        \fi
      \else
        \ifnum\pgcd>1
          \ifnum\pgcd<\the\denoz
            \uppercase{&}\Nomz\uppercase{&}=\SSimplifie{\the\numz}{\the\denoz}
          \else
            \uppercase{&&}
          \fi
        \else
          \uppercase{&&}
        \fi
      \fi
    \fi%\\
\end{align*}
}{}%
}

\newcommand\TThales[8][]{%
  \setKV[ClesThales]{#1}%
  \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
  \ifboolKV[ClesThales]{FigureSeule}{%
    \MPFigThales{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}%
  }{\ifboolKV[ClesThales]{FigurecroiseeSeule}{%
      \MPFigThalesCroisee{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}%
    }{%
      \ifboolKV[ClesThales]{Figure}{%
        \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
        \begin{multicols}{2}%
          {\em La figure est donn\'ee \`a titre indicatif.}%
          \[\MPFigThales{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}\]%
          \par\columnbreak\par%
          \ifboolKV[ClesThales]{Entier}{\TThalesCalculsE[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}}{\TThalesCalculsD[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}}%
        \end{multicols}%
      }{\ifboolKV[ClesThales]{Figurecroisee}{%
          \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
          \begin{multicols}{2}%
            {\em La figure est donn\'ee \`a titre indicatif.}%
            \[\MPFigThalesCroisee{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}\]%
            \par\columnbreak\par%
            \ifboolKV[ClesThales]{Entier}{\TThalesCalculsE[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}}{\TThalesCalculsD[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}}%
          \end{multicols}%
        }{\ifboolKV[ClesThales]{Entier}{\TThalesCalculsE[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}}{\TThalesCalculsD[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}}}%
      }%
    }%
  }%
}%
%%%%

\newcommand\ReciThales[6][]{%
  \ifboolKV[ClesThales]{Droites}{%
    Les droites $(#3#5)$ et $(#4#6)$ sont s\'ecantes en $#2$.
  }{%
    Dans le triangle $#2#3#4$, $#5$ est un point
    \ifboolKV[ClesThales]{Segment}{du segment $[#2#3]$}{de la
      droite $(#2#3)$}, $#6$ est un point
    \ifboolKV[ClesThales]{Segment}{du segment $[#2#4]$}{de la droite
      $(#2#4)$}.
  } %
  \ifboolKV[ClesThales]{Propor}{Le tableau $\begin{array}{c|c}
        #2#5&#2#6\\
        \hline
        #2#3&#2#4\\
      \end{array}
    $ est-il un tableau de proportionnalit\'e ?
  }{%
  }
}

\newcommand\ReciThalesCalculs[8][]{%
  \StrMid{#2}{1}{1}[\NomA]%
  \StrMid{#2}{2}{2}[\NomB]%
  \StrMid{#2}{3}{3}[\NomC]%
  \StrMid{#2}{4}{4}[\NomM]%
  \StrMid{#2}{5}{5}[\NomN]%
  \ifboolKV[ClesThales]{Produit}{%
    \begin{align*}
      \dfrac{\NomA\NomM}{\NomA\NomB}=\dfrac{\num{#3}}{\num{#4}}&&\dfrac{\NomA\NomN}{\NomA\NomC}=\dfrac{\num{#5}}{\num{#6}}
    \end{align*}
    Effectuons les produits en croix :\xdef\NumA{\fpeval{#3*#6}}\xdef\NumB{\fpeval{#4*#5}}
    \begin{align*}
      \num{#3}\times\num{#6}&=\num{\fpeval{#3*#6}}&&&\num{#4}\times\num{#5}&=\num{\fpeval{#4*#5}}
    \end{align*}
    \xintifboolexpr{\NumA == \NumB}{Comme les produits en croix sont
      \'egaux, alors
      $\dfrac{\NomA\NomM}{\NomA\NomB}=\dfrac{\NomA\NomN}{\NomA\NomC}$.\\[0.5em]%
    }{%
      Comme les produits en croix sont diff\'erents, alors
      $\dfrac{\NomA\NomM}{\NomA\NomB}\not=\dfrac{\NomA\NomN}{\NomA\NomC}$.\\%
    }%
  }{%
    \[\left.
        \begin{array}{l}
          \dfrac{\NomA\NomM}{\NomA\NomB}=\dfrac{\num{#3}}{\num{#4}}\ifx\bla#7\bla\ifboolKV[ClesThales]{Simplification}{\PGCD{#3}{#4}\xintifboolexpr{\pgcd==1}{%il faut regarder si on doit continuer avec le PPCM...
          \PGCD{#5}{#6}\xintifboolexpr{\pgcd>1}{\xdef\DenomSimpaa{\fpeval{#6/\pgcd}}\PPCM{#4}{\DenomSimpaa}\xintifboolexpr{\ppcm==#4}{}{=\dfrac{#3\times\num{\fpeval{\ppcm/#4}}}{#4\times\num{\fpeval{\ppcm/#4}}}=\dfrac{\num{\fpeval{#3*\ppcm/#4}}}{\num{\fpeval{\ppcm}}}}}{}%
          }{=\displaystyle\Simplification[All]{#3}{#4}\PGCD{#3}{#4}\xdef\NumSimp{\fpeval{#3/\pgcd}}\xdef\DenomSimp{\fpeval{#4/\pgcd}}\PGCD{#5}{#6}\xdef\NumSimpa{\fpeval{#5/\pgcd}}\xdef\DenomSimpa{\fpeval{#6/\pgcd}}\PPCM{\DenomSimp}{\DenomSimpa}\xintifboolexpr{\fpeval{\the\ppcm/\DenomSimp}==1}{}{=\dfrac{\num{\NumSimp}\times\num{\fpeval{\the\ppcm/\DenomSimp}}}{\num{\DenomSimp}\times\PPCM{\DenomSimp}{\DenomSimpa}\num{\fpeval{\the\ppcm/\DenomSimp}}}=\dfrac{\PPCM{\DenomSimp}{\DenomSimpa}\num{\fpeval{\NumSimp*\the\ppcm/\DenomSimp}}}{\PPCM{\DenomSimp}{\DenomSimpa}\num{\the\ppcm}}}}}{\PPCM{#4}{#6}\xintifboolexpr{\fpeval{\the\ppcm/#4}==1}{}{=\dfrac{\num{#3}\times\num{\fpeval{\the\ppcm/#4}}}{\num{#4}\times\PPCM{#4}{#6}\num{\fpeval{\the\ppcm/#4}}}=\dfrac{\PPCM{#4}{#6}\num{\fpeval{#3*\the\ppcm/#4}}}{\PPCM{#4}{#6}\num{\the\ppcm}}}}\xdef\NumA{\fpeval{#3*#6}}\else%
         \xintifboolexpr{#7==1}{}{=\dfrac{\num{#3}\times\num{#7}}{\num{#4}\times\num{#7}}=\dfrac{\num{\fpeval{#3*#7}}}{\num{\fpeval{#4*#7}}}}\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\xintifboolexpr{\the\ppcm==\fpeval{#4*#7}}{}{=\dfrac{\num{\fpeval{#3*#7}}\times\num{\fpeval{\the\ppcm/(#4*#7)}}}{\num{\fpeval{#4*#7}}\times\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\num{\fpeval{\the\ppcm/(#4*#7)}}}=\dfrac{\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\num{\fpeval{#3*\the\ppcm/#4}}}{\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\num{\fpeval{\the\ppcm}}}}\xdef\NumA{\fpeval{#3*#7*#6*#8}}
          \fi
          \\
          \\
          \dfrac{\NomA\NomN}{\NomA\NomC}=\dfrac{\num{#5}}{\num{#6}}%
          \ifx\bla#8\bla%
          \ifboolKV[ClesThales]{Simplification}{\PGCD{#5}{#6}\xintifboolexpr{\pgcd==1}{%il faut regarder si on doit continuer avec le PPCM...
          \PGCD{#3}{#4}\xintifboolexpr{\pgcd>1}{\xdef\DenomSimpaa{\fpeval{#4/\pgcd}}\PPCM{#6}{\DenomSimpaa}\xintifboolexpr{\ppcm==#6}{}{=\dfrac{#5\times\num{\fpeval{\ppcm/#6}}}{#6\times\num{\fpeval{\ppcm/#6}}}=\dfrac{\num{\fpeval{#5*\ppcm/#6}}}{\num{\fpeval{\ppcm}}}}}{}%
          }{=\displaystyle\Simplification[All]{#5}{#6}\PGCD{#5}{#6}\xdef\NumSimp{\fpeval{#5/\pgcd}}\xdef\DenomSimp{\fpeval{#6/\pgcd}}\PGCD{#3}{#4}\xdef\NumSimpa{\fpeval{#3/\pgcd}}\xdef\DenomSimpa{\fpeval{#4/\pgcd}}\PPCM{\DenomSimp}{\DenomSimpa}\xintifboolexpr{\fpeval{\the\ppcm/\DenomSimp}==1}{}{=\dfrac{\num{\NumSimp}\times\num{\fpeval{\the\ppcm/\DenomSimp}}}{\num{\DenomSimp}\times\PPCM{\DenomSimp}{\DenomSimpa}\num{\fpeval{\the\ppcm/\DenomSimp}}}=\dfrac{\PPCM{\DenomSimp}{\DenomSimpa}\num{\fpeval{\NumSimp*\the\ppcm/\DenomSimp}}}{\PPCM{\DenomSimp}{\DenomSimpa}\num{\the\ppcm}}}}}{\PPCM{#4}{#6}\xintifboolexpr{\fpeval{\the\ppcm/#6}==1}{}{=\dfrac{\num{#5}\times\num{\fpeval{\the\ppcm/#6}}}{\num{#6}\times\PPCM{#4}{#6}\num{\fpeval{\the\ppcm/#6}}}=\dfrac{\PPCM{#4}{#6}\num{\fpeval{#5*\the\ppcm/#6}}}{\PPCM{#4}{#6}\num{\the\ppcm}}}}\xdef\NumB{\fpeval{#5*#4}}%
          \else%
          \xintifboolexpr{#8==1}{}{=\dfrac{\num{#5}\times\num{#8}}{\num{#6}\times\num{#8}}=\dfrac{\num{\fpeval{#5*#8}}}{\num{\fpeval{#6*#8}}}}\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\xintifboolexpr{\the\ppcm==\fpeval{#6*#8}}{}{=\dfrac{\num{\fpeval{#5*#8}}\times\num{\fpeval{\the\ppcm/(#6*#8)}}}{\num{\fpeval{#6*#8}}\times\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\num{\fpeval{\the\ppcm/(#6*#8)}}}=\dfrac{\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\num{\fpeval{#5*\the\ppcm/#6}}}{\xdef\NumC{\fpeval{#4*#7}}\xdef\NumD{\fpeval{#6*#8}}\PPCM{\NumC}{\NumD}\num{\fpeval{\the\ppcm}}}
          }\xdef\NumB{\fpeval{#5*#8*#4*#7}}
          \fi\\
        \end{array}
      \right\}\ifnum\NumA=\NumB \dfrac{\NomA\NomM}{\NomA\NomB}=\dfrac{\NomA\NomN}{\NomA\NomC}\else\dfrac{\NomA\NomM}{\NomA\NomB}\not=\dfrac{\NomA\NomN}{\NomA\NomC}\fi
    \]
  }
  \ifboolKV[ClesThales]{Propor}{%
    \ifnum\NumA=\NumB Donc le tableau $\begin{array}{c|c}
        \NomA\NomM&\NomA\NomN\\
        \hline
        \NomA\NomB&\NomA\NomC\\
      \end{array}
    $ est bien un tableau de proportionnalit\'e.\\De plus, les points
    $\NomA$, $\NomM$, $\NomB$ sont align\'es dans le m\^eme ordre que les
    points $\NomA$, $\NomN$, $\NomC$. Donc les droites $(\NomM\NomN)$
    et $(\NomB\NomC)$ sont parall\`eles d'apr\`es la r\'eciproque du
    th\'eor\`eme de Thal\`es.\else%
    Donc les droites $(\NomM\NomN)$ et $(\NomB\NomC)$ ne sont pas parall\`eles.\fi
  }{%
    \xintifboolexpr{\NumA==\NumB}{%
      De plus, les points $\NomA$, $\NomM$, $\NomB$ sont align\'es dans
      le m\^eme ordre que les points $\NomA$, $\NomN$, $\NomC$. Donc les
      droites $(\NomM\NomN)$ et $(\NomB\NomC)$ sont parall\`eles d'apr\`es
      la r\'eciproque du th\'eor\`eme de Thal\`es.}{%
      Donc les droites $(\NomM\NomN)$ et $(\NomB\NomC)$ ne sont pas
      parall\`eles.}
  }
}

\newcommand\ReciproqueThales[8][]{%
  % #1 Cl\'es
  % #2 NomTriangle + Points ABCEF pour droite (BC)//(EF)
  % #3 longueur AE
  % #4 longueur AB
  % #5 longueur AF
  % #6 longueur AC
  \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
  \ifboolKV[ClesThales]{FigureSeule}{%
%    \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
    \MPFigReciThales{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}%
  }{\ifboolKV[ClesThales]{FigurecroiseeSeule}{%
%      \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
      \MPFigReciThalesCroisee{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}%
    }{%
      \ifboolKV[ClesThales]{Figure}{%
%        \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
        \begin{multicols}{2}
          {\em La figure est donn\'ee \`a titre indicatif.}
          \[\MPFigReciThales{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}\]
          \par\columnbreak\par        
          \ReciThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}\par
          \ReciThalesCalculs[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}
        \end{multicols}
      }{\ifboolKV[ClesThales]{Figurecroisee}{%
%          \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]
          \fbox{\begin{minipage}{0.4\linewidth}%
            {\em La figure est donn\'ee \`a titre indicatif.}%
            \[\MPFigReciThalesCroisee{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}\]%
          \end{minipage}}
          \hfill
          \begin{minipage}{0.55\linewidth}%
            \ReciThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}\par
            \ReciThalesCalculs[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
          \end{minipage}%
        }{\ReciThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}\par
          \ReciThalesCalculs[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
        }%
      }%
    }%
  }%
}%

\newcommand\Thales[8][]{%
  \useKVdefault[ClesThales]%
  \setKV[ClesThales]{#1}%
  %Définir les points pour une utilisation perso
  \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
  \xdef\NomPointA{\NomA}%
  \xdef\NomPointB{\NomB}%
  \xdef\NomPointC{\NomC}%
  \xdef\NomTriangle{\NomA\NomB\NomC}%
  \xdef\NomPointM{\NomM}%
  \xdef\NomPointN{\NomN}%
  %
  \ifboolKV[ClesThales]{Reciproque}{%
    \ReciproqueThales[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
  }{%
    \ifboolKV[ClesThales]{FigureSeule}{%
      \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
      \MPFigThales{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}%
    }{%
      \ifboolKV[ClesThales]{FigurecroiseeSeule}{%
        \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
        \MPFigThalesCroisee{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}%
      }{%
        \ifboolKV[ClesThales]{Redaction}{%
          \ifboolKV[ClesThales]{Figure}{%
            \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
            \begin{multicols}{2}
              {\em La figure est donn\'ee \`a titre indicatif.}%
              \[\MPFigThales{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}\]%
              \par\columnbreak\par%
              \TTThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}%
            \end{multicols}%
          }{%
            \ifboolKV[ClesThales]{Figurecroisee}{%
              \StrMid{#2}{1}{1}[\NomA]\StrMid{#2}{2}{2}[\NomB]\StrMid{#2}{3}{3}[\NomC]\StrMid{#2}{4}{4}[\NomM]\StrMid{#2}{5}{5}[\NomN]%
              \begin{multicols}{2}
                {\em La figure est donn\'ee \`a titre indicatif.}%
                \[\MPFigThalesCroisee{\NomA}{\NomB}{\NomC}{\NomM}{\NomN}{\useKV[ClesThales]{Angle}}\]%
                \par\columnbreak\par%
                \TTThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}%
              \end{multicols}
            }{%
              \TTThales[#1]{\StrMid{#2}{1}{1}}{\StrMid{#2}{2}{2}}{\StrMid{#2}{3}{3}}{\StrMid{#2}{4}{4}}{\StrMid{#2}{5}{5}}%
            }
          }    
        }{%
          \TThales[#1]{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
        }%
      }%
    }%
  }%
}%

%%%
% Trigonom\'etrie
%%%
\def\MPFigTrigo#1#2#3#4#5#6#7#8{%
  \ifluatex
  \mplibcodeinherit{enable}
   \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesTrigo]{Echelle};
    pair A,B,C,O,I,D,E,F;%
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=u*(1,1);
    B-A=u*(3,0);
    C=(A--2[A,B rotatedabout(A,50)]) intersectionpoint (B--2[B,A rotatedabout(B,-90)]);
    % On d\'efinit le centre du cercle circonscrit
    O - .5[A,B] = whatever * (B-A) rotated 90;
    O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#8);
    B:=B rotatedabout(O,#8);
    C:=C rotatedabout(O,#8);
    % On d\'efinit le centre du cercle inscrit
    (I-C) rotated ((angle(A-C)-angle(B-C))/2) shifted C=whatever[A,C];
    (I-B) rotated ((angle(C-B)-angle(A-B))/2) shifted B=whatever[B,C];
    % on dessine \`a main lev\'ee :)
    path triangle;
    triangle=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)}--B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)}--C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)}--cycle;
    % on d\'efinit l'angle droit
    D-B=7*unitvector(C-B);
    F-B=7*unitvector(A-B);
    E-D=F-B;
    draw D{dir(angle(E-D)+5)}..E{dir(angle(E-D)+5)}--E{dir(angle(F-E)+5)}..F{dir(angle(F-E)+5)};
    % L'angle :)
    path cc;
    cc=fullcircle scaled 1u;
    % on marque les angles
    picture MAngle;
    MAngle=image(
    draw (cc shifted A);
    );
    draw MAngle;
    clip currentpicture to triangle;
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    % on labelise
    picture z;
    label(btex #1 etex,1.15[O,A]);
    label(btex #2 etex,1.15[O,B]);
    label(btex #3 etex,1.15[O,C]);
    label(btex \ang{#7} etex,A+0.95u*unitvector(I-A));
    decalage:=3mm;
    if #6<0:
    else:
    if angle(1/2[A,C]-B)>0:
      if #6=0:
        label(btex ? etex,1.1[B,1/2[A,C]]);
      else:
        label(btex \num{#6} etex,1.2[B,1/2[A,C]]);
      fi;
    else:
      if #6=0:
        label(btex ? etex,1.1[B,1/2[A,C]]);
      else:
        label(btex \num{#6} etex,1.2[B,1/2[A,C]]);
      fi;
    fi;
  fi;   
  if #4<0:
  else:
    if angle(1/2[B,C]-A)>0:
      if #4=0:
        label(btex ? etex,1/2[B,C]-decalage*(unitvector(A-B)));
      else:
        label(btex \num{#4} etex,1/2[B,C]-decalage*(unitvector(A-B)));
      fi;
    else:
      if #4=0:
        label(btex ? etex,1/2[B,C]-decalage*(unitvector(A-B)));
      else:
        label(btex \num{#4} etex,1/2[B,C]-decalage*(unitvector(A-B)));
      fi;
    fi;
  fi;
  if #5<0:
  else:
    if angle(1/2[A,B]-C)>0:
      if #5=0:
        label(btex ? etex,1/2[A,B]-decalage*(unitvector(C-B)));
      else:
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
      fi;
    else:
      if #5=0:
        label(btex ? etex,1/2[A,B]-decalage*(unitvector(C-B)));
      else:
        label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
      fi;
    fi;
    fi;
  \end{mplibcode}
  \mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesTrigo]{Echelle};}]
    pair A,B,C,O,I,D,E,F;%
    % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
    A=u*(1,1);
    B-A=u*(3,0);
    C=(A--2[A,B rotatedabout(A,50)]) intersectionpoint (B--2[B,A rotatedabout(B,-90)]);
    % On d\'efinit le centre du cercle circonscrit
    O - .5[A,B] = whatever * (B-A) rotated 90;
    O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
    A:=A rotatedabout(O,#8);
    B:=B rotatedabout(O,#8);
    C:=C rotatedabout(O,#8);
    % On d\'efinit le centre du cercle inscrit
    (I-C) rotated ((angle(A-C)-angle(B-C))/2) shifted C=whatever[A,C];
    (I-B) rotated ((angle(C-B)-angle(A-B))/2) shifted B=whatever[B,C];
    % on dessine \`a main lev\'ee :)
    path triangle;
    triangle=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)}--B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)}--C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)}--cycle;
    % on d\'efinit l'angle droit
    D-B=7*unitvector(C-B);
    F-B=7*unitvector(A-B);
    E-D=F-B;
    draw D{dir(angle(E-D)+5)}..E{dir(angle(E-D)+5)}--E{dir(angle(F-E)+5)}..F{dir(angle(F-E)+5)};
    % L'angle :)
    path cc;
    cc=fullcircle scaled 1u;
    % on marque les angles
    picture MAngle;
    MAngle=image(
    draw (cc shifted A);
    % draw (cc shifted B);
    % draw (cc shifted C);
    );
    draw MAngle;
    clip currentpicture to triangle;
    draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
    draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
    draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    % on labelise
    picture z;
    label(btex #1 etex,1.15[O,A]);
    label(btex #2 etex,1.15[O,B]);
    label(btex #3 etex,1.15[O,C]);
    label(btex \ang{#7} etex,A+0.95u*unitvector(I-A));
    decalage:=3mm;
    if #6<0:
    else:
    if angle(1/2[A,C]-B)>0:
      if #6=0:
        label(btex ? etex rotated angle(C-A),1.1[B,1/2[A,C]]);
      else:
        label(btex \num{#6} etex rotated angle(C-A),1.2[B,1/2[A,C]]);
      fi;
    else:
      if #6=0:
        label(btex ? etex rotated angle(A-C),1.1[B,1/2[A,C]]);
      else:
        label(btex \num{#6} etex rotated angle(A-C),1.2[B,1/2[A,C]]);
      fi;
    fi;
  fi;   
  if #4<0:
  else:
    if angle(1/2[B,C]-A)>0:
      if #4=0:
        label(btex ? etex rotated(angle(B-C)),1/2[B,C]-decalage*(unitvector(A-B)));
      else:
        label(btex \num{#4} etex rotated(angle(B-C)),1/2[B,C]-decalage*(unitvector(A-B)));
      fi;
    else:
      if #4=0:
        label(btex ? etex rotated(angle(C-B)),1/2[B,C]-decalage*(unitvector(A-B)));
      else:
        label(btex \num{#4} etex rotated(angle(C-B)),1/2[B,C]-decalage*(unitvector(A-B)));
      fi;
    fi;
  fi;
  if #5<0:
  else:
    if angle(1/2[A,B]-C)>0:
      if #5=0:
        label(btex ? etex rotated angle(A-B),1/2[A,B]-decalage*(unitvector(C-B)));
      else:
        label(btex \num{#5} etex rotated angle(A-B),1/2[A,B]-decalage*(unitvector(C-B)));
      fi;
    else:
      if #5=0:
        label(btex ? etex rotated angle(B-A),1/2[A,B]-decalage*(unitvector(C-B)));
      else:
        label(btex \num{#5} etex rotated angle(B-A),1/2[A,B]-decalage*(unitvector(C-B)));
      fi;
    fi;
  fi;
\end{mpost}
\fi
}

\def\MPFigTrigoAngle#1#2#3#4#5#6#7{%
  % #1 A
  % #2 B
  % #3 C
  % #4 opp
  % #5 adj
  % #6 hyp
  % #7 angle de rotation
  \ifluatex
  \mplibcodeinherit{enable}
   \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesTrigo]{Echelle};
  pair A,B,C,O,I,D,E,F;%
  % On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
  A=u*(1,1);
  B-A=u*(3,0);
  C=(A--2[A,B rotatedabout(A,50)]) intersectionpoint (B--2[B,A rotatedabout(B,-90)]);
    % On d\'efinit le centre du cercle circonscrit
  O - .5[A,B] = whatever * (B-A) rotated 90;
  O - .5[B,C] = whatever * (C-B) rotated 90;
  % On tourne pour \'eventuellement moins de lassitude :)
  A:=A rotatedabout(O,#7);
  B:=B rotatedabout(O,#7);
  C:=C rotatedabout(O,#7);
  % On d\'efinit le centre du cercle inscrit
  (I-C) rotated ((angle(A-C)-angle(B-C))/2) shifted C=whatever[A,C];
  (I-B) rotated ((angle(C-B)-angle(A-B))/2) shifted B=whatever[B,C];
    %on dessine \`a main lev\'ee :)
  path triangle;
  triangle=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)}--B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)}--C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)}--cycle;
  %on d\'efinit l'angle droit
  D-B=7*unitvector(C-B);
  F-B=7*unitvector(A-B);
  E-D=F-B;
  draw D{dir(angle(E-D)+5)}..E{dir(angle(E-D)+5)}--E{dir(angle(F-E)+5)}..F{dir(angle(F-E)+5)};
  %L'angle :)
  path cc;
  cc=fullcircle scaled 1u;
  % on marque les angles
  picture MAngle;
  MAngle=image(
  draw (cc shifted A);
  );
  draw MAngle;
  clip currentpicture to triangle;
  draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
  draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
  draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
  % on labelise
  label(btex #1 etex,1.15[O,A]);
  label(btex #2 etex,1.15[O,B]);
  label(btex #3 etex,1.15[O,C]);
  label(btex ? etex,A+0.95u*unitvector(I-A));
  decalage:=3mm;
  if #6>0:
  if angle(1/2[A,C]-B)>0:
    label(btex \num{#6} etex,1.2[B,1/2[A,C]]);
  else:
  label(btex \num{#6} etex,1.2[B,1/2[A,C]]);
  fi;
  fi;
  if #4>0:
  if angle(1/2[B,C]-A)>0:
   label(btex \num{#4} etex,1/2[B,C]-decalage*(unitvector(A-B)));
  else:
    label(btex \num{#4} etex,1/2[B,C]-decalage*(unitvector(A-B)));
    fi;
    fi;
    if #5>0:
  if angle(1/2[A,B]-C)>0:
    label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
  else:
  label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
  fi;
  fi;
\end{mplibcode}
\mplibcodeinherit{disable}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesTrigo]{Echelle};}]
      u:=1cm;
  pair A,B,C,O,I,D,E,F;%
    %On place les points A,B,C sur le cercle de mani\`ere \`a faciliter la rotation de la figure
  A=u*(1,1);
  B-A=u*(3,0);
  C=(A--2[A,B rotatedabout(A,50)]) intersectionpoint (B--2[B,A rotatedabout(B,-90)]);
    % On d\'efinit le centre du cercle circonscrit
  O - .5[A,B] = whatever * (B-A) rotated 90;
  O - .5[B,C] = whatever * (C-B) rotated 90;
    % On tourne pour \'eventuellement moins de lassitude :)
  A:=A rotatedabout(O,#7);
  B:=B rotatedabout(O,#7);
  C:=C rotatedabout(O,#7);
    % On d\'efinit le centre du cercle inscrit
  (I-C) rotated ((angle(A-C)-angle(B-C))/2) shifted C=whatever[A,C];
  (I-B) rotated ((angle(C-B)-angle(A-B))/2) shifted B=whatever[B,C];
    %on dessine \`a main lev\'ee :)
  path triangle;
  triangle=A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)}--B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)}--C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)}--cycle;
  %on d\'efinit l'angle droit
  D-B=7*unitvector(C-B);
  F-B=7*unitvector(A-B);
  E-D=F-B;
  draw D{dir(angle(E-D)+5)}..E{dir(angle(E-D)+5)}--E{dir(angle(F-E)+5)}..F{dir(angle(F-E)+5)};
  %L'angle :)
  path cc;
  cc=fullcircle scaled 1u;
    % on marque les angles
  picture MAngle;
  MAngle=image(
      draw (cc shifted A);
    );
  draw MAngle;
  clip currentpicture to triangle;
  draw A{dir(angle(B-A)+5)}..B{dir(angle(B-A)+5)};
  draw B{dir(angle(C-B)+5)}..C{dir(angle(C-B)+5)};
  draw C{dir(angle(A-C)+5)}..A{dir(angle(A-C)+5)};
    %on labelise
  label(btex #1 etex,1.15[O,A]);
  label(btex #2 etex,1.15[O,B]);
  label(btex #3 etex,1.15[O,C]);
  label(btex ? etex,A+0.95u*unitvector(I-A));
  decalage:=3mm;
  if #6>0:
  if angle(1/2[A,C]-B)>0:
    label(btex \num{#6} etex,1.2[B,1/2[A,C]]);
  else:
  label(btex \num{#6} etex,1.2[B,1/2[A,C]]);
  fi;
  fi;
  if #4>0:
  if angle(1/2[B,C]-A)>0:
   label(btex \num{#4} etex,1/2[B,C]-decalage*(unitvector(A-B)));
  else:
    label(btex \num{#4} etex,1/2[B,C]-decalage*(unitvector(A-B)));
    fi;
    fi;
    if #5>0:
  if angle(1/2[A,B]-C)>0:
    label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
  else:
  label(btex \num{#5} etex,1/2[A,B]-decalage*(unitvector(C-B)));
  fi;
  fi;
\end{mpost}
\fi
}

\setKVdefault[ClesTrigo]{Angle=0,Propor=false,Figure=false,FigureSeule=false,ValeurExacte=false,Precision=2,Unite=cm,Sinus=false,Cosinus=false,Tangente=false,Perso=false,Echelle=1cm}%

\newcommand\RedactionTrigo{}%

\newcommand\TrigoCalculs[5][]{%
  \setKV[ClesTrigo]{#1}%
  % #1 Cl\'es
  % #2 Nom du triangle ABC, rectangle en B, angle connu ou pas : BAC
  % #3 Longueur #4 Longueur #5 angle
  % On d\'efinit les points
  \DeclareSIUnit{\PfCTrigoUnit}{\useKV[ClesTrigo]{Unite}}%
  \StrMid{#2}{1}{1}[\NomA]%
  \StrMid{#2}{2}{2}[\NomB]%
  \StrMid{#2}{3}{3}[\NomC]%
  \xdef\NomTriangle{\NomA\NomB\NomC}%
  \xdef\NomAngleDroit{\NomB}%
  \xdef\NomSommetA{\NomA}%
  \xdef\NomSommetB{\NomB}%
  \xdef\NomSommetC{\NomC}%
  \ifboolKV[ClesTrigo]{Perso}{%
    \RedactionTrigo%
  }{%
    Dans le triangle $\NomA\NomB\NomC$, rectangle en $\NomB$, on a :%
  }%
  \ifboolKV[ClesTrigo]{Cosinus}{%
    \ifx\bla#3\bla%on calcule le c\^ot\'e adjacent
    \xdef\ResultatTrigo{\fpeval{round(#4*cosd(#5),\useKV[ClesTrigo]{Precision})}}%
   \ifboolKV[ClesTrigo]{Propor}{%
     \begin{align*}
       \NomA\NomC\times\cos(\widehat{\NomB\NomA\NomC})&=\NomA\NomB\\
       \num{#4}\times\cos(\ang{#5})&=\NomA\NomB%\\
       \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\
       \SI{\fpeval{round(#4*cosd(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}&\IfInteger{\fpeval{round(#4*cosd(#5),9)}}{=}{\approx}\NomA\NomB}
      \end{align*}%
    }{%
      \begin{align*}
        \cos(\widehat{\NomB\NomA\NomC})&=\frac{\NomA\NomB}{\NomA\NomC}\\
        \cos(\ang{#5})&=\frac{\NomA\NomB}{\num{#4}}\\
        \num{#4}\times\cos(\ang{#5})&=\NomA\NomB%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \SI{\fpeval{round(#4*cosd(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}&\IfInteger{\fpeval{round(#4*cosd(#5),9)}}{=}{\approx}\NomA\NomB}%
      \end{align*}
    }%
    \else%
    \ifx\bla#4\bla%on calcule l'hypoth\'enuse
    \xdef\ResultatTrigo{\fpeval{round(#3/cosd(#5),\useKV[ClesTrigo]{Precision})}}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomC\times\cos(\widehat{\NomB\NomA\NomC})&=\NomA\NomB\\
        \NomA\NomC\times\cos(\ang{#5})&=\num{#3}\\
        \NomA\NomC&=\frac{\num{#3}}{\cos(\ang{#5})}%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \NomA\NomC&\IfInteger{\fpeval{round(#3/cosd(#5),9)}}{=}{\approx}\SI{\fpeval{round(#3/cosd(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}}%
      \end{align*}
    }{%
      \begin{align*}
        \cos(\widehat{\NomB\NomA\NomC})&=\frac{\NomA\NomB}{\NomA\NomC}\\
        \cos(\ang{#5})&=\frac{\num{#3}}{\NomA\NomC}\\
        \NomA\NomC&=\frac{\num{#3}}{\cos(\ang{#5})}%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \NomA\NomC&\IfInteger{\fpeval{round(#3/cosd(#5),9)}}{=}{\approx}\SI{\fpeval{round(#3/cosd(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}}%
      \end{align*}%
    }%
    \else%on calcule l'angle
    \xdef\ResultatTrigo{\fpeval{round(acosd(#3/#4),\useKV[ClesTrigo]{Precision})}}%
    \setKV[ClesTrigo]{Precision=0}%
    \setKV[ClesTrigo]{#1}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomC\times\cos(\widehat{\NomB\NomA\NomC})&=\NomA\NomB\\
        \num{#4}\times\cos(\widehat{\NomB\NomA\NomC})&=\num{#3}\\
        \cos(\widehat{\NomB\NomA\NomC})&=\frac{\num{#3}}{\num{#4}}\\
        \widehat{\NomB\NomA\NomC}&\IfInteger{\fpeval{round(acosd(#3/#4),9)}}{=}{\approx}\ang{\fpeval{round(acosd(#3/#4),\useKV[ClesTrigo]{Precision})}}%
      \end{align*}%
    }{%
      \begin{align*}
        \cos(\widehat{\NomB\NomA\NomC})&=\frac{\NomA\NomB}{\NomA\NomC}\\
        \cos(\widehat{\NomB\NomA\NomC})&=\frac{\num{#3}}{\num{#4}}\\
        \widehat{\NomB\NomA\NomC}&\IfInteger{\fpeval{round(acosd(#3/#4),9)}}{=}{\approx}\ang{\fpeval{round(acosd(#3/#4),\useKV[ClesTrigo]{Precision})}}%
      \end{align*}%
    }%
    \fi%
    \fi%
  }{}%
  \ifboolKV[ClesTrigo]{Sinus}{%
    \ifx\bla#3\bla%on calcule le c\^ot\'e oppos\'e
    \xdef\ResultatTrigo{\fpeval{round(#4*sind(#5),\useKV[ClesTrigo]{Precision})}}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomC\times\sin(\widehat{\NomB\NomA\NomC})&=\NomB\NomC\\
        \num{#4}\times\sin(\ang{#5})&=\NomB\NomC%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \SI{\fpeval{round(#4*sind(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}&\IfInteger{\fpeval{round(#4*sind(#5),9)}}{=}{\approx}\NomB\NomC}%
      \end{align*}%
    }{%
      \begin{align*}
        \sin(\widehat{\NomB\NomA\NomC})&=\frac{\NomB\NomC}{\NomA\NomC}\\
        \sin(\ang{#5})&=\frac{\NomB\NomC}{\num{#4}}\\
        \num{#4}\times\sin(\ang{#5})&=\NomB\NomC%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \SI{\fpeval{round(#4*sind(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}&\IfInteger{\fpeval{round(#4*sind(#5),9)}}{=}{\approx}\NomB\NomC}%
      \end{align*}%
    }%
    \else
    \ifx\bla#4\bla%on calcule l'hypoth\'enuse
    \xdef\ResultatTrigo{\fpeval{round(#3/sind(#5),\useKV[ClesTrigo]{Precision})}}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomC\times\sin(\widehat{\NomB\NomA\NomC})&=\NomB\NomC\\
        \NomA\NomC\times\sin(\ang{#5})&=\num{#3}\\
        \NomA\NomC&=\frac{\num{#3}}{\sin(\ang{#5})}%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \NomA\NomC&\IfInteger{\fpeval{round(#3/sind(#5),9)}}{=}{\approx}\SI{\fpeval{round(#3/sind(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}}%
      \end{align*}%
    }{%
      \begin{align*}
        \sin(\widehat{\NomB\NomA\NomC})&=\frac{\NomB\NomC}{\NomA\NomC}\\
        \sin(\ang{#5})&=\frac{\num{#3}}{\NomA\NomC}\\
        \NomA\NomC&=\frac{\num{#3}}{\sin(\ang{#5})}%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \NomA\NomC&\IfInteger{\fpeval{round(#3/sind(#5),9)}}{=}{\approx}\SI{\fpeval{round(#3/sind(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}}%
      \end{align*}%
    }%
    \else%on calcule l'angle
    \xdef\ResultatTrigo{\fpeval{round(asind(#3/#4),\useKV[ClesTrigo]{Precision})}}%
    \setKV[ClesTrigo]{Precision=0}%
    \setKV[ClesTrigo]{#1}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomC\times\sin(\widehat{\NomB\NomA\NomC})&=\NomB\NomC\\
        \num{#4}\times\sin(\widehat{\NomB\NomA\NomC})&=\num{#3}\\
        \sin(\widehat{\NomB\NomA\NomC})&=\frac{\num{#3}}{\num{#4}}\\
        \widehat{\NomB\NomA\NomC}&\IfInteger{\fpeval{round(asind(#3/#4),9)}}{=}{\approx}\ang{\fpeval{round(asind(#3/#4),\useKV[ClesTrigo]{Precision})}}%
      \end{align*}%
    }{%
      \begin{align*}
        \sin(\widehat{\NomB\NomA\NomC})&=\frac{\NomB\NomC}{\NomA\NomC}\\
        \sin(\widehat{\NomB\NomA\NomC})&=\frac{\num{#3}}{\num{#4}}\\
        \widehat{\NomB\NomA\NomC}&\IfInteger{\fpeval{round(asind(#3/#4),9)}}{=}{\approx}\ang{\fpeval{round(asind(#3/#4),\useKV[ClesTrigo]{Precision})}}%
      \end{align*}%
    }%
    \fi%
    \fi%
  }{}%
  \ifboolKV[ClesTrigo]{Tangente}{%
    \ifx\bla#3\bla%on calcule le c\^ot\'e oppos\'e
    \xdef\ResultatTrigo{\fpeval{round(#4*tand(#5),\useKV[ClesTrigo]{Precision})}}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomB\times\tan(\widehat{\NomB\NomA\NomC})&=\NomB\NomC\\%
        \num{#4}\times\tan(\ang{#5})&=\NomB\NomC%\\%
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \SI{\fpeval{round(#4*tand(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}&\IfInteger{\fpeval{round(#4*tand(#5),9)}}{=}{\approx}\NomB\NomC}%
      \end{align*}%
    }{%
      \begin{align*}
        \tan(\widehat{\NomB\NomA\NomC})&=\frac{\NomB\NomC}{\NomA\NomB}\\
        \tan(\ang{#5})&=\frac{\NomB\NomC}{\num{#4}}\\
        \num{#4}\times\tan(\ang{#5})&=\NomB\NomC%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \SI{\fpeval{round(#4*tand(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}&\IfInteger{\fpeval{round(#4*tand(#5),9)}}{=}{\approx}\NomB\NomC}%
      \end{align*}%
    }%
    \else
    \ifx\bla#4\bla%on calcule l'adjacent
    \xdef\ResultatTrigo{\fpeval{round(#3/tand(#5),\useKV[ClesTrigo]{Precision})}}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomB\times\tan(\widehat{\NomB\NomA\NomC})&=\NomB\NomC\\
        \NomA\NomB\times\tan(\ang{#5})&=\num{#3}\\
        \NomA\NomB&=\frac{\num{#3}}{\tan(\ang{#5})}%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \NomA\NomB&\IfInteger{\fpeval{round(#3/tand(#5),9)}}{=}{\approx}\SI{\fpeval{round(#3/tand(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}}%
      \end{align*}%
    }{%
      \begin{align*}
        \tan(\widehat{\NomB\NomA\NomC})&=\frac{\NomB\NomC}{\NomA\NomB}\\
        \tan(\ang{#5})&=\frac{\num{#3}}{\NomA\NomB}\\
        \NomA\NomB&=\frac{\num{#3}}{\tan(\ang{#5})}%\\
        \ifboolKV[ClesTrigo]{ValeurExacte}{}{\\%
        \NomA\NomB&\IfInteger{\fpeval{round(#3/tand(#5),9)}}{=}{\approx}\SI{\fpeval{round(#3/tand(#5),\useKV[ClesTrigo]{Precision})}}{\PfCTrigoUnit}}%
      \end{align*}%
    }%
    \else%on calcule l'angle
    \setKV[ClesTrigo]{Precision=0}%
    \setKV[ClesTrigo]{#1}%
    \xdef\ResultatTrigo{\fpeval{round(atand(#3/#4),\useKV[ClesTrigo]{Precision})}}%
    \ifboolKV[ClesTrigo]{Propor}{%
      \begin{align*}
        \NomA\NomB\times\tan(\widehat{\NomB\NomA\NomC})&=\NomB\NomC\\
        \num{#4}\times\tan(\widehat{\NomB\NomA\NomC})&=\num{#3}\\
        \tan(\widehat{\NomB\NomA\NomC})&=\frac{\num{#3}}{\num{#4}}\\
        \widehat{\NomB\NomA\NomC}&\IfInteger{\fpeval{round(atand(#3/#4),9)}}{=}{\approx}\ang{\fpeval{round(atand(#3/#4),\useKV[ClesTrigo]{Precision})}}%
      \end{align*}%
    }{%
      \begin{align*}
        \tan(\widehat{\NomB\NomA\NomC})&=\frac{\NomB\NomC}{\NomA\NomB}\\
        \tan(\widehat{\NomB\NomA\NomC})&=\frac{\num{#3}}{\num{#4}}\\
        \widehat{\NomB\NomA\NomC}&\IfInteger{\fpeval{round(atand(#3/#4),9)}}{=}{\approx}\ang{\fpeval{round(atand(#3/#4),\useKV[ClesTrigo]{Precision})}}%
      \end{align*}%
    }%
    \fi%
    \fi%
  }{}%
}%

\newcommand\Trigo[5][]{%
  \useKVdefault[ClesTrigo]%
  \setKV[ClesTrigo]{#1}%
  % #1 Cl\'es
  % #2 Nom du triangle ABC, rectangle en B, angle connu ou pas : BAC
  % #3 Longueur #4 Longueur #5 angle
  % On d\'efinit les points
  \StrMid{#2}{1}{1}[\NomA]%
  \StrMid{#2}{2}{2}[\NomB]%
  \StrMid{#2}{3}{3}[\NomC]%
  % On r\'edige
  \ifboolKV[ClesTrigo]{FigureSeule}{%
    \ifx\bla#5\bla%
    \ifboolKV[ClesTrigo]{Cosinus}{%
      \MPFigTrigoAngle{\NomA}{\NomB}{\NomC}{-1}{#3}{#4}{\useKV[ClesTrigo]{Angle}}
    }{}%
    \ifboolKV[ClesTrigo]{Sinus}{%
      \MPFigTrigoAngle{\NomA}{\NomB}{\NomC}{#3}{-1}{#4}{\useKV[ClesTrigo]{Angle}}
    }{}%
    \ifboolKV[ClesTrigo]{Tangente}{%
      \MPFigTrigoAngle{\NomA}{\NomB}{\NomC}{#3}{#4}{-1}{\useKV[ClesTrigo]{Angle}}
    }{}%
    \else%}{%figure pour calculer une longueur
    \ifboolKV[ClesTrigo]{Cosinus}{%
      \ifx\bla#3\bla%adjacent inconnu
      \MPFigTrigo{\NomA}{\NomB}{\NomC}{-1}{0}{#4}{#5}{\useKV[ClesTrigo]{Angle}}
      \else
      \MPFigTrigo{\NomA}{\NomB}{\NomC}{-1}{#3}{0}{#5}{\useKV[ClesTrigo]{Angle}}
      \fi
    }{}%
    \ifboolKV[ClesTrigo]{Sinus}{%
      \ifx\bla#3\bla%adjacent inconnu
      \MPFigTrigo{\NomA}{\NomB}{\NomC}{0}{-1}{#4}{#5}{\useKV[ClesTrigo]{Angle}}
      \else
      \MPFigTrigo{\NomA}{\NomB}{\NomC}{#3}{-1}{0}{#5}{\useKV[ClesTrigo]{Angle}}
      \fi
    }{}%
    \ifboolKV[ClesTrigo]{Tangente}{%
      \ifx\bla#3\bla%adjacent inconnu
      \MPFigTrigo{\NomA}{\NomB}{\NomC}{0}{#4}{-1}{#5}{\useKV[ClesTrigo]{Angle}}
      \else%
      \MPFigTrigo{\NomA}{\NomB}{\NomC}{#3}{0}{-1}{#5}{\useKV[ClesTrigo]{Angle}}
      \fi%
    }{}%
    \fi%
  }{%
    \ifboolKV[ClesTrigo]{Figure}{%
      \begin{multicols}{2}%
        {\em La figure est donn\'ee \`a titre indicatif.}%
        \ifx\bla#5\bla%
        \ifboolKV[ClesTrigo]{Cosinus}{%
          \begin{center}
            \MPFigTrigoAngle{\NomA}{\NomB}{\NomC}{-1}{#3}{#4}{\useKV[ClesTrigo]{Angle}}
          \end{center}
        }{}%
        \ifboolKV[ClesTrigo]{Sinus}{%
          \begin{center}
            \MPFigTrigoAngle{\NomA}{\NomB}{\NomC}{#3}{-1}{#4}{\useKV[ClesTrigo]{Angle}}
          \end{center}
        }{}%
        \ifboolKV[ClesTrigo]{Tangente}{%
          \begin{center}
            \MPFigTrigoAngle{\NomA}{\NomB}{\NomC}{#3}{#4}{-1}{\useKV[ClesTrigo]{Angle}}
          \end{center}
        }{}%
        \else%}{%figure pour calculer une longueur
        \ifboolKV[ClesTrigo]{Cosinus}{%
          \ifx\bla#3\bla%adjacent inconnu
          \begin{center}
            \MPFigTrigo{\NomA}{\NomB}{\NomC}{-1}{0}{#4}{#5}{\useKV[ClesTrigo]{Angle}}
          \end{center}
          \else
          \begin{center}
            \MPFigTrigo{\NomA}{\NomB}{\NomC}{-1}{#3}{0}{#5}{\useKV[ClesTrigo]{Angle}}
          \end{center}
          \fi
        }{}%
        \ifboolKV[ClesTrigo]{Sinus}{%
          \ifx\bla#3\bla%adjacent inconnu
          \begin{center}
            \MPFigTrigo{\NomA}{\NomB}{\NomC}{0}{-1}{#4}{#5}{\useKV[ClesTrigo]{Angle}}
          \end{center}
          \else
          \begin{center}
            \MPFigTrigo{\NomA}{\NomB}{\NomC}{#3}{-1}{0}{#5}{\useKV[ClesTrigo]{Angle}}
          \end{center}
          \fi
        }{}%
        \ifboolKV[ClesTrigo]{Tangente}{%
          \ifx\bla#3\bla%adjacent inconnu
          \begin{center}
            \MPFigTrigo{\NomA}{\NomB}{\NomC}{0}{#4}{-1}{#5}{\useKV[ClesTrigo]{Angle}}
          \end{center}
          \else%
          \begin{center}
            \MPFigTrigo{\NomA}{\NomB}{\NomC}{#3}{0}{-1}{#5}{\useKV[ClesTrigo]{Angle}}
          \end{center}
          \fi%
        }{}%
        \fi%
        \par\columnbreak\par
        \TrigoCalculs[#1]{#2}{#3}{#4}{#5}%
      \end{multicols}
    }{%
      \TrigoCalculs[#1]{#2}{#3}{#4}{#5}%
    }%
  }%
}%

%%%
% Statistiques
%%%
\newcommand\NbDonnees{}%
\newcommand\SommeDonnees{}%
\newcommand\EffectifTotal{}%
\newcommand\Moyenne{}%
\newcommand\Etendue{}%
\newcommand\Mediane{}%
\newcommand\DonneeMax{}%
\newcommand\DonneeMin{}%
\newcommand\EffectifMax{}%

\setKVdefault[ClesStat]{ColVide=0,CaseVide=false,EffVide=false,%
FreqVide=false,AngVide=false,ECCVide=false,TotalVide=false,Sondage=false,Liste=false,%
Tableau=false,Stretch=1,Frequence=false,EffectifTotal=false,%
Etendue=false,Moyenne=false,SET=false,ValeurExacte=false,Mediane=false,QuartileUn=false,QuartileTrois=false,Total=false,Concret=false,%
Unite={},Largeur=1cm,Precision=2,PrecisionF=0,Donnee=Valeurs,Effectif=Effectif,Grille=false,Origine=0,Angle=false,SemiAngle=false,Qualitatif=false,TableauVide=false,ECC=false,Coupure=10,CouleurTab=gray!15,Graphique=false,Batons=true,%
% Pour les diags batons
EpaisseurBatons=1,ListeCouleursB={a},Lecture=false,LectureFine=false,AideLecture=false,Reponses=false,DonneesSup=false,AbscisseRotation=false,Tiret=false,AngleRotationAbscisse=0,Pasx=1,Pasy=1,Unitex=0.5,Unitey=0.5,Depart=0,CouleurDefaut=black,%
% Pour les diags circulaires
Rayon=3cm,AffichageAngle=false,AffichageDonnee=false,ListeCouleurs={white},Hachures=false,LectureInverse=false,EcartHachures=0.25,EpaisseurHachures=1,Legende,LegendeVide=false,ACompleter=false,%
%Pour les représentations
Representation=false,%
%Pour les barres horizontales
Barre=false,Longueur=10cm,Hauteur=5mm,Bicolore=false,EcartBarre=0%Grille est dispo
}%
%compl\'ements
\defKV[ClesStat]{AngleRotationAbscisse=\setKV[ClesStat]{AbscisseRotation}}%
\defKV[ClesStat]{AffichageDonnees=\setKV[ClesStat]{AffichageAngle=false}\setKV[ClesStat]{AffichageDonnee}}%
\defKV[ClesStat]{CasesVides=\setKV[ClesStat]{CaseVide}}%
\defKV[ClesStat]{LegendesVides=\setKV[ClesStat]{LegendeVide}}%
% La construction du tableau
\def\addtotok#1#2{#1\expandafter{\the#1#2}}%
\newtoks\tabtoksa\newtoks\tabtoksb\newtoks\tabtoksc%
\def\updatetoks#1/#2\nil{\addtotok\tabtoksa{\ifboolKV[ClesStat]{Qualitatif}{&#1}{&\num{#1}}}\addtotok\tabtoksb{&\num{#2}}}%
%
\newcounter{PfCCompteLignes}%
%
\def\BuildtabStat{% %%Tableau sans total
  \setcounter{PfCCompteLignes}{0}%
  \tabtoksa{\useKV[ClesStat]{Donnee}}\tabtoksb{\useKV[ClesStat]{Effectif}}%
  \foreachitem\compteur\in\ListeComplete{\expandafter\updatetoks\compteur\nil}%
  \ifboolKV[ClesStat]{Total}{%
    \renewcommand{\arraystretch}{\useKV[ClesStat]{Stretch}}%
    \begin{NiceTabular}{c*{\fpeval{\ListeCompletelen+1}}{>{\centering\arraybackslash}p{\useKV[ClesStat]{Largeur}}}}%
      \CodeBefore%
      \rowcolor{\useKV[ClesStat]{CouleurTab}}{1}%
      \columncolor{\useKV[ClesStat]{CouleurTab}}{1}%
      \Body%
      \the\tabtoksa&Total\\%
      \ifboolKV[ClesStat]{EffVide}{\useKV[ClesStat]{Effectif}\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&}}{\the\tabtoksb&\num{\EffectifTotal}}\\%
      \ifboolKV[ClesStat]{Frequence}{\stepcounter{PfCCompteLignes}Fr\'equence (\%)\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{FreqVide}{}{\num{\CalculFrequence{##1}}}}}&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{FreqVide}{}{100}}\\}{}%
      \ifboolKV[ClesStat]{Angle}{\stepcounter{PfCCompteLignes}Angle (\si{\degree})\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{AngVide}{}{\CalculAngle{##1}}}}&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{AngVide}{}{360}}\\}{}%
      \ifboolKV[ClesStat]{SemiAngle}{\stepcounter{PfCCompteLignes}Angle (\si{\degree})\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{AngVide}{}{\CalculSemiAngle{##1}}}}&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{AngVide}{}{180}}\\}{}%
      \ifboolKV[ClesStat]{ECC}{\stepcounter{PfCCompteLignes}E.C.C.\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{ECCVide}{}{\CalculECC{##1}}}}&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{ECCVide}{}{\num{\EffectifTotal}}}\\}{}%
      \CodeAfter%
      % On crée la liste des colonnes à vider
      \xintifboolexpr{\useKV[ClesStat]{ColVide}>0}{%
        \xdef\FooStat{\useKV[ClesStat]{ColVide}}%
        \setsepchar{,}%
        \readlist*\ListeColonnesAVider{\FooStat}%
        \foreachitem\compteur\in\ListeColonnesAVider{%
          \tikz\fill[white] (row-2-|col-\fpeval{\compteur+1}) rectangle (last-|col-\fpeval{\compteur+2});%
        }%
      }{}%
      % On crée la liste des cases à vider
      \ifboolKV[ClesStat]{CaseVide}{%
        \xdef\FooStatCases{\useKV[ClesStat]{CasesVides}}%
        \setsepchar[*]{,*/}%
        \readlist*\ListeCasesAVider{\FooStatCases}%
        \foreachitem\compteur\in\ListeCasesAVider{%
          \tikz\fill[white] (row-\fpeval{\ListeCasesAVider[\compteurcnt,1]+1}-|col-\fpeval{\ListeCasesAVider[\compteurcnt,2]+1}) rectangle (row-\fpeval{\ListeCasesAVider[\compteurcnt,1]+2}-|col-\fpeval{\ListeCasesAVider[\compteurcnt,2]+2});%
        }%
      }{}%
      % On retrace le tableau
      %Les colonnes
      \xintFor* ##1 in {\xintSeq{1}{\fpeval{\ListeCompletelen+3}}}\do{%
        \tikz\draw (row-1-|col-##1) -- (last-|col-##1);%
      }%
      % Les lignes
      \xintFor* ##1 in {\xintSeq{1}{\fpeval{\thePfCCompteLignes+3}}}\do{%
        \tikz\draw (row-##1-|col-1) -- (row-##1-|last);%
      }%
    \end{NiceTabular}%
  }{%
    \renewcommand{\arraystretch}{\useKV[ClesStat]{Stretch}}%
    \begin{NiceTabular}{c*{\fpeval{\ListeCompletelen}}{>{\centering\arraybackslash}p{\useKV[ClesStat]{Largeur}}}}%
      \CodeBefore%
      \rowcolor{\useKV[ClesStat]{CouleurTab}}{1}%
      \columncolor{\useKV[ClesStat]{CouleurTab}}{1}%
      \Body%
      \the\tabtoksa\\%
      \ifboolKV[ClesStat]{EffVide}{\useKV[ClesStat]{Effectif}\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&}}{\the\tabtoksb}\\%
      \ifboolKV[ClesStat]{Frequence}{\stepcounter{PfCCompteLignes}Fr\'equence (\%)\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{FreqVide}{}{\num{\CalculFrequence{##1}}}}}\\}{}%
      \ifboolKV[ClesStat]{Angle}{\stepcounter{PfCCompteLignes}Angle (\si{\degree})\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{AngVide}{}{\CalculAngle{##1}}}}\\}{}%
      \ifboolKV[ClesStat]{SemiAngle}{\stepcounter{PfCCompteLignes}Angle (\si{\degree})\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{AngVide}{}{\CalculSemiAngle{##1}}}}\\}{}%
      \ifboolKV[ClesStat]{ECC}{\stepcounter{PfCCompteLignes}E.C.C.\xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{&\ifboolKV[ClesStat]{TableauVide}{}{\ifboolKV[ClesStat]{ECCVide}{}{\CalculECC{##1}}}}\\}{}%
      \CodeAfter%
      % On crée la liste des colonnes à vider
      \xintifboolexpr{\useKV[ClesStat]{ColVide}>0}{%
        \xdef\FooStat{\useKV[ClesStat]{ColVide}}%
        \setsepchar{,}%
        \readlist*\ListeColonnesAVider{\FooStat}%
        \foreachitem\compteur\in\ListeColonnesAVider{%
          \tikz\fill[white] (row-2-|col-\fpeval{\compteur+1}) rectangle (last-|col-\fpeval{\compteur+2});%
        }%
      }{}%
      % On crée la liste des cases à vider
      \ifboolKV[ClesStat]{CaseVide}{%
        \xdef\FooStatCases{\useKV[ClesStat]{CasesVides}}%
        \setsepchar[*]{,*/}%
        \readlist*\ListeCasesAVider{\FooStatCases}%
        \foreachitem\compteur\in\ListeCasesAVider{%
          \tikz\fill[white] (row-\fpeval{\ListeCasesAVider[\compteurcnt,1]+1}-|col-\fpeval{\ListeCasesAVider[\compteurcnt,2]+1}) rectangle (row-\fpeval{\ListeCasesAVider[\compteurcnt,1]+2}-|col-\fpeval{\ListeCasesAVider[\compteurcnt,2]+2});%
        }%
      }{}%
      % On retrace le tableau
      %Les colonnes
      \xintFor* ##1 in {\xintSeq{1}{\fpeval{\ListeCompletelen+2}}}\do{%
        \tikz\draw (row-1-|col-##1) -- (last-|col-##1);%
      }%
      % Les lignes
      \xintFor* ##1 in {\xintSeq{1}{\fpeval{\thePfCCompteLignes+3}}}\do{%
        \tikz\draw (row-##1-|col-1) -- (row-##1-|last);%
      }%
    \end{NiceTabular}%
  }%
}%

% Pour construire le diagramme en barres horizontales
\def\UpdatetoksHor#1/#2/#3\nil{\addtotok\toklistenomhor{"#1",}\addtotok\toklistedonhor{#3,}\addtotok\toklisteaffhor{"#2",}}%

\newcommand\buildgraphbarhor{%
  \newtoks\toklistenomhor%
  \newtoks\toklistedonhor%
  \newtoks\toklisteaffhor%
  \newtoks\toklistecouleur%
  \xdef\PfCfooStat{}%
  \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
    \xdef\PfCfooStat{\PfCfooStat \ListeComplete[##1,2],}%
  }%
  \xdef\DivMax{\fpeval{max(\PfCfooStat)}}%
  \xdef\ExposantDivMax{\fpeval{round(ln(\DivMax)/ln(10))}}%
  \xdef\DivMax{\fpeval{10**\ExposantDivMax}}%
  \xdef\PfCfooStat{}%
  \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
    \xdef\PfCfooStat{\PfCfooStat \ListeComplete[##1,1]/\ListeComplete[##1,2]/\fpeval{\ListeComplete[##1,2]/\DivMax},}%
  }%
  \readlist*\ListeCompleteDiagHor{\PfCfooStat}%
  \foreachitem\compteur\in\ListeCompleteDiagHor{\expandafter\UpdatetoksHor\compteur\nil}%
  \xdef\ListeAvantCouleurs{\useKV[ClesStat]{ListeCouleurs}}%
  \readlist*\ListeCouleur{\ListeAvantCouleurs}%
  \foreachitem\couleur\in\ListeCouleur{\expandafter\UpdateCoul\couleur\nil}%
  \NewMPDiagBarreHor{\the\toklistenomhor}{\the\toklistedonhor}{\the\toklisteaffhor}{\the\toklistecouleur}%
}%

% Pour construire le diagramme en bâtons
\def\Updatetoks#1/#2\nil{\addtotok\toklistepoint{(#1,#2),}}%
\newcommand\buildgraph[1][]{%
  \newtoks\toklistepoint%
  \foreachitem\compteur\in\ListeComplete{\expandafter\Updatetoks\compteur\nil}%
  \newtoks\toklistecouleur%
  \xdef\ListeAvantCouleurs{\useKV[ClesStat]{ListeCouleursB}}%
  \readlist*\ListeCouleur{\ListeAvantCouleurs}%
  \foreachitem\couleur\in\ListeCouleur{\expandafter\UpdateCoul\couleur\nil}%
  \MPStatNew{\the\toklistepoint}{\the\toklistecouleur}%
}%

% Pour construire le diagramme en bâtons qualitatif
\def\Updatetoksq#1/#2\nil{\addtotok\toklistepointq{"#1",#2,}}%
\newcommand\buildgraphq[1][]{%
  \newtoks\toklistepointq%
  \foreachitem\compteur\in\ListeComplete{\expandafter\Updatetoksq\compteur\nil}%
  \newtoks\toklistecouleur%
  \xdef\ListeAvantCouleurs{\useKV[ClesStat]{ListeCouleursB}}%
  \readlist*\ListeCouleur{\ListeAvantCouleurs}%
  \foreachitem\couleur\in\ListeCouleur{\expandafter\UpdateCoul\couleur\nil}%
  \MPStatNew{\the\toklistepointq}{\the\toklistecouleur}%
}%

\def\UpdateCoul#1\nil{\addtotok\toklistecouleur{#1,}}%
\def\UpdateLegende#1\nil{\addtotok\toklistelegende{#1,}}%

% Pour construire le diagramme circulaire qualitatif
\def\buildgraphcq#1{%
  \newtoks\toklistepointq\toklistepointq{}%
  \newtoks\toklistecouleur\toklistecouleur{}%
  \newtoks\toklistelegende\toklistelegende{}%
  \ifboolKV[ClesStat]{LegendeVide}{%
    \xdef\foo{\useKV[ClesStat]{LegendesVides}}%
    \readlist*\ListeLegendesAEffacer{\foo}%
  }{\xdef\foo{0}\readlist*\ListeLegendesAEffacer{\foo}%
  }%
  \foreachitem\compteur\in\ListeLegendesAEffacer{\expandafter\UpdateLegende\compteur\nil}%
  %
  \foreachitem\compteur\in\ListeComplete{\expandafter\Updatetoksq\compteur\nil}%
  \xdef\ListeAvantCouleurs{\useKV[ClesStat]{ListeCouleurs}}%
  \readlist*\ListeCouleur{\ListeAvantCouleurs}%
  \foreachitem\couleur\in\ListeCouleur{\expandafter\UpdateCoul\couleur\nil}%
  \NewMPStatCirculaireQ{\the\toklistepointq}{#1}{\the\toklistecouleur}{\the\toklistelegende}%
}%

%% calcul des fr\'equences
\newcommand\CalculFrequence[1]{%
  \fpeval{round(\ListeComplete[#1,2]*100/\EffectifTotal,\useKV[ClesStat]{PrecisionF})}
}

%% calcul des angles
\newcommand\CalculAngle[1]{%
  \fpeval{round(\ListeComplete[#1,2]*360/\EffectifTotal,0)}
}
\newcommand\CalculSemiAngle[1]{%
  \fpeval{round(\ListeComplete[#1,2]*180/\EffectifTotal,0)}
}

%% calcul des ECC
\newcount\CompteurECC%
\newcount\CompteurECCTotal%

\newcommand\CalculECC[1]{%
  \xdef\TotalECC{0}%
  \CompteurECC=1%
  \CompteurECCTotal=\numexpr#1+1%
  \whiledo{\CompteurECC < \CompteurECCTotal}{%
    \xdef\TotalECC{\fpeval{\TotalECC+\ListeComplete[\the\CompteurECC,2]}}%
    \CompteurECC=\numexpr\CompteurECC+1%
  }%
  \num{\TotalECC}%
}

% Construction d'un diagramme en barres horizontal
\newcommand\NewMPDiagBarreHor[4]{%
  % #1 Liste des noms
  % #2 Liste des valeurs associées
  % #3 Liste des valeurs à afficher (si pb calcul MP)
  % #4 Liste des couleurs
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    Longueur:=\useKV[ClesStat]{Longueur};
    Hauteur:=\useKV[ClesStat]{Hauteur};
    Ecart:=\useKV[ClesStat]{EcartBarre};
    ExposantDivMax:=\ExposantDivMax;
    ecarthachures=\useKV[ClesStat]{EcartHachures};
    epaisseurhachures=\useKV[ClesStat]{EpaisseurHachures};
    boolean Hachures;
    Hachures=\useKV[ClesStat]{Hachures};
    boolean Bicolore;
    Bicolore=\useKV[ClesStat]{Bicolore};
    boolean Grille;
    Grille=\useKV[ClesStat]{Grille};
    boolean AffichageDonnee;
    AffichageDonnee=\useKV[ClesStat]{AffichageDonnee};
    boolean LegendeVide;
    LegendeVide=\useKV[ClesStat]{LegendeVide};
    vardef CalculNombreDonneesEtDonneeMax(text t)=
    nbdon:=0;%nombre de données
    DonneeMax:=0;%donnée DonneeMaximale
    for p_=t:
    nbdon:=nbdon+1;
    if p_>DonneeMax:
    DonneeMax:=p_;
    fi;
    endfor;
    enddef;
    vardef ListeDonnees(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    Donnees[n]:=p_;
    endfor;
    enddef;
    vardef RecuperationCouleurs(text t)=
    color Col[];
    n:=0;
    for p_=t:
    n:=n+1;
    Col[n]=p_;
    endfor;
    enddef;
    vardef TraceDiag=
    if Grille:
    pair Zz[];%Pour déterminer "le dernier point"
    Zz0=(0,-(nbdon-1)*(Hauteur+Ecart)-Ecart);
    Zz2=(0,(Hauteur+Ecart));
    Zz1=((1/DonneeMax)*Longueur,-(nbdon-1)*(Hauteur+Ecart)-Ecart);
    Zz3=if ExposantDivMax=0 : (DonneeMax+1)[Zz0,Zz1] else: ((floor(DonneeMax*10+2))/10)[Zz0,Zz1];fi;
    if ExposantDivMax=0:
    for k=1 upto DonneeMax+1:
    trace (Zz0--Zz2) shifted (k*(Zz1-Zz0)) dashed evenly withcolor 0.5white;
    endfor;
    else:
    for k=1 upto (floor(DonneeMax*10+2)):
    trace (Zz0--Zz2) shifted ((k/10)*(Zz1-Zz0)) dashed evenly withcolor 0.5white;
    endfor;
    fi;
    if ExposantDivMax=0:
    for k=1 upto (DonneeMax+1):
    label.bot(TEX("\num{"&decimal(k)&"}"),Zz0+k*(Zz1-Zz0));
    endfor;
    else:
    if ExposantDivMax<5:
    for k=1 upto (floor(DonneeMax*10+2)):
    label.bot(TEX("\num{\fpeval{"&decimal(k)&"*(10**"&decimal(ExposantDivMax-1)&")}}"),Zz0+(k/10)*(Zz1-Zz0));
    endfor;
    else:
    dotlabel.bot(TEX("\num{\fpeval{10**"&decimal(ExposantDivMax)&"}}"),Zz1);
    fi;
    fi;
    fi;
    for k=0 upto nbdon-1:
    path RectangleDonnee;
    RectangleDonnee=(unitsquare xscaled ((Donnees[k+1]/DonneeMax)*Longueur) yscaled Hauteur) shifted(0,-k*(Hauteur+Ecart));
    if Hachures:
    fill RectangleDonnee withcolor white;
    trace Hachurage(RectangleDonnee,60 if
    (k mod 2)=0: +90 fi,ecarthachures,if (k mod 2)=0 : 0 else: 1 fi)
    withpen pencircle scaled epaisseurhachures;
    else:
    remplis RectangleDonnee withcolor if unknown Col[k+1]: if Bicolore:Col[(k mod 2)+1] else: white fi; else:if Bicolore:Col[(k mod 2)+1] else: Col[k+1] fi; fi;
    fi;
    trace RectangleDonnee;
    endfor;
    if Grille:
    drawarrow (0,-(nbdon-1)*(Hauteur+Ecart)-Ecart)--(0,(Hauteur+Ecart)) withpen pencircle scaled 1.5;
    drawarrow (0,-(nbdon-1)*(Hauteur+Ecart)-Ecart)--(Zz3+u*(0.25,0)) withpen pencircle scaled 1.5;
    fi;
    enddef;
    vardef AffichageNom(text t)=
    k:=0;
    for p_=t:
    label.lft(TEX(p_),0.5[(0,0),(0,Hauteur)] shifted (0,-k*(Hauteur+Ecart)));
    k:=k+1;
    endfor;
    enddef;
    vardef AffichageDonnees(text t)=
    k:=0;
    for p_=t:
    label.rt(TEX("\num{"&p_&"}"),0.5[(0,0),(0,Hauteur)] shifted (((Donnees[k+1]/DonneeMax)*Longueur),-k*(Hauteur+Ecart)));
    k:=k+1;
    endfor;
    enddef;
    CalculNombreDonneesEtDonneeMax(#2);
    ListeDonnees(#2);
    RecuperationCouleurs(#4);
    TraceDiag;
    if LegendeVide=false:
    AffichageNom(#1);
    fi;
    if AffichageDonnee:
    AffichageDonnees(#3);
    fi;
  \end{mplibcode}
  \else%
  \begin{mpost}[mpsettings={%
      Longueur:=\useKV[ClesStat]{Longueur};
      Hauteur:=\useKV[ClesStat]{Hauteur};
      Ecart:=\useKV[ClesStat]{EcartBarre};
      ExposantDivMax:=\ExposantDivMax;
      ecarthachures=\useKV[ClesStat]{EcartHachures};
      epaisseurhachures=\useKV[ClesStat]{EpaisseurHachures};
      boolean Hachures;
      Hachures=\useKV[ClesStat]{Hachures};
      boolean Bicolore;
      Bicolore=\useKV[ClesStat]{Bicolore};
      boolean Grille;
      Grille=\useKV[ClesStat]{Grille};
      boolean AffichageDonnee;
      AffichageDonnee=\useKV[ClesStat]{AffichageDonnee};
      boolean LegendeVide;
      LegendeVide=\useKV[ClesStat]{LegendeVide};
    }]
    vardef CalculNombreDonneesEtDonneeMax(text t)=
    nbdon:=0;%nombre de données
    DonneeMax:=0;%donnée DonneeMaximale
    for p_=t:
    nbdon:=nbdon+1;
    if p_>DonneeMax:
    DonneeMax:=p_;
    fi;
    endfor;
    enddef;
    vardef ListeDonnees(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    Donnees[n]:=p_;
    endfor;
    enddef;
    vardef RecuperationCouleurs(text t)=
    color Col[];
    n:=0;
    for p_=t:
    n:=n+1;
    Col[n]=p_;
    endfor;
    enddef;
    vardef TraceDiag=
    if Grille:
    pair Zz[];%Pour déterminer "le dernier point"
    Zz0=(0,-(nbdon-1)*(Hauteur+Ecart)-Ecart);
    Zz2=(0,(Hauteur+Ecart));
    Zz1=((1/DonneeMax)*Longueur,-(nbdon-1)*(Hauteur+Ecart)-Ecart);
    Zz3=if ExposantDivMax=0 : (DonneeMax+1)[Zz0,Zz1] else: ((floor(DonneeMax*10+2))/10)[Zz0,Zz1];fi;
    if ExposantDivMax=0:
    for k=1 upto DonneeMax+1:
    trace (Zz0--Zz2) shifted (k*(Zz1-Zz0)) dashed evenly withcolor 0.5white;
    endfor;
    else:
    for k=1 upto (floor(DonneeMax*10+2)):
    trace (Zz0--Zz2) shifted ((k/10)*(Zz1-Zz0)) dashed evenly withcolor 0.5white;
    endfor;
    fi;
    if ExposantDivMax=0:
    for k=1 upto (DonneeMax+1):
    label.bot(LATEX("\num{"&decimal(k)&"}"),Zz0+k*(Zz1-Zz0));
    endfor;
    else:
    if ExposantDivMax<5:
    for k=1 upto (floor(DonneeMax*10+2)):
    label.bot(LATEX("\num{\noexpand\fpeval{"&decimal(k)&"*(10**"&decimal(ExposantDivMax-1)&")}}"),Zz0+(k/10)*(Zz1-Zz0));
    endfor;
    else:
    dotlabel.bot(LATEX("\num{\noexpand\fpeval{10**"&decimal(ExposantDivMax)&"}}"),Zz1);
    fi;
    fi;
    fi;
    for k=0 upto nbdon-1:
    path RectangleDonnee;
    RectangleDonnee=(unitsquare xscaled ((Donnees[k+1]/DonneeMax)*Longueur) yscaled Hauteur) shifted(0,-k*(Hauteur+Ecart));
    if Hachures:
    fill RectangleDonnee withcolor white;
    trace Hachurage(RectangleDonnee,60 if
    (k mod 2)=0: +90 fi,ecarthachures,if (k mod 2)=0 : 0 else: 1 fi)
    withpen pencircle scaled epaisseurhachures;
    else:
    remplis RectangleDonnee withcolor if unknown Col[k+1]: if Bicolore:Col[(k mod 2)+1] else: white fi; else:if Bicolore:Col[(k mod 2)+1] else: Col[k+1] fi; fi;
    fi;
    trace RectangleDonnee;
    endfor;
    if Grille:
    drawarrow (0,-(nbdon-1)*(Hauteur+Ecart)-Ecart)--(0,(Hauteur+Ecart)) withpen pencircle scaled 1.5;
    drawarrow (0,-(nbdon-1)*(Hauteur+Ecart)-Ecart)--(Zz3+u*(0.25,0)) withpen pencircle scaled 1.5;
    fi;
    enddef;
    vardef AffichageNom(text t)=
    k:=0;
    for p_=t:
    label.lft(LATEX(p_),0.5[(0,0),(0,Hauteur)] shifted (0,-k*(Hauteur+Ecart)));
    k:=k+1;
    endfor;
    enddef;
    vardef AffichageDonnees(text t)=
    k:=0;
    for p_=t:
    label.rt(LATEX("\num{"&p_&"}"),0.5[(0,0),(0,Hauteur)] shifted (((Donnees[k+1]/DonneeMax)*Longueur),-k*(Hauteur+Ecart)));
    k:=k+1;
    endfor;
    enddef;
    CalculNombreDonneesEtDonneeMax(#2);
    ListeDonnees(#2);
    RecuperationCouleurs(#4);
    TraceDiag;
    if LegendeVide=false:
    AffichageNom(#1);
    fi;
    if AffichageDonnee:
    AffichageDonnees(#3);
    fi;
  \end{mpost}
  \fi%
}%

% Construction du graphique en bâtons
\newcommand\MPStatNew[2]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    maxx:=0;
    maxy:=0;
    unitex:=\useKV[ClesStat]{Unitex}*cm;
    unitey:=\useKV[ClesStat]{Unitey}*cm;
    xpartorigine:=\useKV[ClesStat]{Origine};
    AngleRotation=\useKV[ClesStat]{AngleRotationAbscisse};
    boolean Rotation;
    Rotation=\useKV[ClesStat]{AbscisseRotation};
    boolean Lecture;
    Lecture:=\useKV[ClesStat]{Lecture};
    boolean LectureFine;
    LectureFine:=\useKV[ClesStat]{LectureFine};
    boolean AideLecture;
    AideLecture:=\useKV[ClesStat]{AideLecture};
    boolean DonneesSup;
    DonneesSup:=\useKV[ClesStat]{DonneesSup};
    boolean Reponses;
    Reponses:=\useKV[ClesStat]{Reponses};
    epaisseurbatons=\useKV[ClesStat]{EpaisseurBatons};
    boolean Qualitatif;
    Qualitatif=\useKV[ClesStat]{Qualitatif};
    boolean Tiret;
    Tiret=\useKV[ClesStat]{Tiret};
    color CoulDefaut;
    CoulDefaut=\useKV[ClesStat]{CouleurDefaut};
    Depart=\useKV[ClesStat]{Depart};
    % on r\'ecup\`ere les couleurs
    color Col[];
    n:=0;
    for p_=#2:
    n:=n+1;
    if color p_:
    Col[n]=p_;
    else:
    Col[n]=CoulDefaut;
    fi;
    endfor;
    % 
    pair A[],B[],P[];
    vardef toto(text t)=%points quantitatif
    n:=0;
    for p_=t:
    if pair p_:
    n:=n+1;
    P[n]=((xpart(p_)-(xpartorigine))*unitex,ypart(p_)*unitey);
    if xpart(p_)>maxx:
    maxx:=xpart(p_)-(xpartorigine);
    fi;
    if ypart(p_)>maxy:
    maxy:=ypart(p_);
    fi;
    A[n]=unitex*(xpart(p_)-(xpartorigine),0);
    B[n]=unitey*(0,ypart(p_));
    fi;
    endfor;
    enddef;
    vardef tutu(text t)=%points qualitatif
    n:=0;
    for p_=t:
    if numeric p_:
    P[n]=((n)*unitex,unitey*(p_-Depart));
    B[n]=(0,unitey*(p_-Depart));
    if p_>maxy:
    maxy:=p_;
    fi;
    else:
    n:=n+1;
    A[n]=unitex*(n,0);
    fi;
    endfor;
    maxy:=maxy-Depart;
    maxx:=n;
    enddef;
    vardef tata(text t)=%affichage quantitatif
    l=0;
    for p_=t:
    if pair p_:
    l:=l+1;
    if Rotation:
    label.bot(TEX("\num{"&decimal(xpart(p_))&"}") rotated AngleRotation,A[l]);
    else :
    label.bot(TEX("\num{"&decimal(xpart(p_))&"}"),A[l]);
    fi;
    if Reponses:
    if DonneesSup:
    label.top(TEX("\num{"&decimal(ypart(p_))&"}"),P[l]);
    else:
    if Tiret:
    trace (B[l]+(-1pt,0))--(B[l]+(1pt,0));
    label.lft(TEX("\num{"&decimal(p_)&"}"),B[l]);
    else:
    dotlabel.lft(TEX("\num{"&decimal(ypart(p_))&"}"),B[l]);
    fi;
    fi;
    fi;
    fi;
    endfor;
    enddef;
    vardef titi(text t)=%affichage qualitatif
    l:=0;
    for p_=t:
    if numeric p_:
    if Reponses:
    if DonneesSup:
    label.top(TEX("\num{"&decimal(p_)&"}"),P[l]);
    else:
    if Tiret:
    trace (B[l]+(-1pt,0))--(B[l]+(1pt,0));
    label.lft(TEX("\num{"&decimal(p_)&"}"),B[l]);
    else:
    dotlabel.lft(TEX("\num{"&decimal(p_)&"}"),B[l]);
    fi;
    fi;
    fi;
    else:
    l:=l+1;
    if Rotation:
    if AngleRotation<>0:
    picture TEXTELABEL;
    TEXTELABEL=image(
    labeloffset:=labeloffset*2;
    label.lft(TEX(p_),A[l]);
    labeloffset:=labeloffset/2;
    );
    trace rotation(TEXTELABEL,A[l],AngleRotation);
    else :
    label.bot(TEX(p_),A[l]);
    fi;
    fi;
    fi;
    endfor;
    enddef;
    if Qualitatif: tutu(#1); else: toto(#1); fi;
    boolean Grille;
    Grille:=\useKV[ClesStat]{Grille};
    Pasx:=\useKV[ClesStat]{Pasx};
    Pasy:=\useKV[ClesStat]{Pasy};
    if Grille:
    drawoptions(withcolor 0.75white);
    for k=0 step Pasx until ((maxx+1)):
    trace (k*unitex,0)--(k*unitex,unitey*(maxy+2*Pasy));
    endfor;
    for k=0 step Pasy until ((maxy+2*Pasy)):
    trace (0,k*unitey)--(unitex*(maxx+1),k*unitey);
    endfor;
    drawoptions();
    fi;
    if epaisseurbatons<>0:
    for k=1 upto n:
    fill polygone(A[k]-(epaisseurbatons*1pt,0),A[k]+(epaisseurbatons*1pt,0),P[k]+(epaisseurbatons*1pt,0),P[k]-(epaisseurbatons*1pt,0)) withcolor if unknown Col[k]: CoulDefaut else:Col[k] fi;
    if AideLecture:
    draw B[k]--P[k] dashed evenly;
    fi;
    endfor;
    fi;
    if LectureFine:
    for k=0 step Pasy until ((maxy+1*Pasy)):
    if Tiret:
    trace (1pt,k*unitey)--(-1pt,k*unitey);
    label.lft(TEX("\num{"&decimal(k+Depart)&"}"),(0,k*unitey));
    else:
    dotlabel.lft(TEX("\num{"&decimal(k+Depart)&"}"),(0,k*unitey));
    fi;
    endfor;
    fi;
    if Lecture:
    for k=0 step Pasy until Pasy:
    if Tiret:
    trace (1pt,k*unitey)--(-1pt,k*unitey);
    label.lft(TEX("\num{"&decimal(k)&"}"),(0,k*unitey));
    else:
    dotlabel.lft(TEX("\num{"&decimal(k)&"}"),(0,k*unitey));
    fi;
    endfor;
    fi;
    drawarrow (0,0)--unitex*(maxx+1,0);
    drawarrow (0,0)--unitey*(0,maxy+2*Pasy);
    label.lrt(btex \useKV[ClesStat]{Donnee} etex,unitex*(maxx+1,0));
    label.urt(btex \useKV[ClesStat]{Effectif} etex,unitey*(0,maxy+2*Pasy));
    if Qualitatif: titi(#1); else:tata(#1); fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={%
      unitex:=\useKV[ClesStat]{Unitex}*cm;
      unitey:=\useKV[ClesStat]{Unitey}*cm;
      xpartorigine:=\useKV[ClesStat]{Origine};
      AngleRotation=\useKV[ClesStat]{AngleRotationAbscisse};
      boolean Rotation;
      Rotation=\useKV[ClesStat]{AbscisseRotation};
      boolean Lecture;
      Lecture:=\useKV[ClesStat]{Lecture};
      boolean LectureFine;
      LectureFine:=\useKV[ClesStat]{LectureFine};
      boolean AideLecture;
      AideLecture:=\useKV[ClesStat]{AideLecture};
      boolean DonneesSup;
      DonneesSup:=\useKV[ClesStat]{DonneesSup};
      boolean Reponses;
      Reponses:=\useKV[ClesStat]{Reponses};
      epaisseurbatons=\useKV[ClesStat]{EpaisseurBatons};
      boolean Qualitatif;
      Qualitatif=\useKV[ClesStat]{Qualitatif};
      boolean Tiret;
      Tiret=\useKV[ClesStat]{Tiret};
      color CoulDefaut;
      CoulDefaut=\useKV[ClesStat]{CouleurDefaut};}
    Depart=\useKV[ClesStat]{Depart};
    ]
    maxx:=0;
    maxy:=0;
    % on r\'ecup\`ere les couleurs
    color Col[];
    n:=0;
    for p_=#2:
    n:=n+1;
    if color p_:
    Col[n]=p_;
    else:
    Col[n]=CoulDefaut;
    fi;
    endfor;
    % 
    pair A[],B[],P[];
    vardef toto(text t)=%points quantitatif
    n:=0;
    for p_=t:
    if pair p_:
    n:=n+1;
    P[n]=((xpart(p_)-(xpartorigine))*unitex,ypart(p_)*unitey);
    if xpart(p_)>maxx:
    maxx:=xpart(p_)-(xpartorigine);
    fi;
    if ypart(p_)>maxy:
    maxy:=ypart(p_);
    fi;
    A[n]=unitex*(xpart(p_)-(xpartorigine),0);
    B[n]=unitey*(0,ypart(p_));
    fi;
    endfor;
    enddef;
    vardef tata(text t)=%affichage quantitatif
    l=0;
    for p_=t:
    if pair p_:
    l:=l+1;
    if Rotation:
    label.bot(LATEX("\num{"&decimal(xpart(p_))&"}") rotated AngleRotation,A[l]);
    else :
    label.bot(LATEX("\num{"&decimal(xpart(p_))&"}"),A[l]);
    fi;
    if Reponses:
    if DonneesSup:
    label.top(LATEX("\num{"&decimal(ypart(p_))&"}"),P[l]);
    else:
    if Tiret:
    trace (B[l]+(-1pt,0))--(B[l]+(1pt,0));
    label.lft(LATEX("\num{"&decimal(p_)&"}"),B[l]);
    else:
    dotlabel.lft(LATEX("\num{"&decimal(ypart(p_))&"}"),B[l]);
    fi;
    fi;
    fi;
    fi;
    endfor;
    enddef;
    vardef tutu(text t)=%points qualitatif
    n:=0;
    for p_=t:
    if numeric p_:
    P[n]=((n)*unitex,unitey*p_);
    B[n]=(0,unitey*p_);
    if p_>maxy:
    maxy:=p_;
    fi;
    else:
    n:=n+1;
    A[n]=unitex*(n,0);
    fi;
    endfor;
    maxx:=n;
    enddef;
    vardef titi(text t)=%affichage qualitatif
    l:=0;
    for p_=t:
    if numeric p_:
    if Reponses:
    if DonneesSup:
    label.top(LATEX("\num{"&decimal(p_)&"}"),P[l]);
    else:
    if Tiret:
    trace (B[l]+(-1pt,0))--(B[l]+(1pt,0));
    label.lft(LATEX("\num{"&decimal(p_)&"}"),B[l]);
    else:
    dotlabel.lft(LATEX("\num{"&decimal(p_)&"}"),B[l]);
    fi;
    fi;
    fi;
    else:
    l:=l+1;
    if Rotation:
    if AngleRotation<>0:
    picture TEXTELABEL;
    TEXTELABEL=image(
    labeloffset:=labeloffset*2;
    label.lft(LATEX(p_),A[l]);
    labeloffset:=labeloffset/2;
    );
    trace rotation(TEXTELABEL,A[l],AngleRotation);
    else :
    label.bot(LATEX(p_),A[l]);
    fi;
    fi;
    fi;
    endfor;
    enddef;
    if Qualitatif: tutu(#1); else: toto(#1); fi;
    boolean Grille;
    Grille:=\useKV[ClesStat]{Grille};
    Pasx:=\useKV[ClesStat]{Pasx};
    Pasy:=\useKV[ClesStat]{Pasy};    
    if Grille:
    drawoptions(withcolor 0.75white);
    for k=0 step Pasx until ((maxx+1)):
    trace (k*unitex,0)--(k*unitex,unitey*(maxy+2*Pasy));
    endfor;
    for k=0 step Pasy until ((maxy+2*Pasy)):
    trace (0,k*unitey)--(unitex*(maxx+1),k*unitey);
    endfor;
    drawoptions();
    fi;
    if epaisseurbatons<>0:
    for k=1 upto n:
    fill polygone(A[k]-(epaisseurbatons*1pt,0),A[k]+(epaisseurbatons*1pt,0),P[k]+(epaisseurbatons*1pt,0),P[k]-(epaisseurbatons*1pt,0)) withcolor if unknown Col[k]: CoulDefaut else:Col[k] fi;
    if AideLecture:
    draw B[k]--P[k] dashed evenly;
    fi;
    endfor;
    fi;
    if LectureFine:
    for k=0 step Pasy until ((maxy+1*Pasy)):
    if Tiret:
    trace (1pt,k*unitey)--(-1pt,k*unitey);
    label.lft(LATEX("\num{"&decimal(k)&"}"),(0,k*unitey));
    else:
    dotlabel.lft(LATEX("\num{"&decimal(k)&"}"),(0,k*unitey));
    fi;
    endfor;
    fi;
    if Lecture:
    for k=0 step Pasy until Pasy:
    if Tiret:
    trace (1pt,k*unitey)--(-1pt,k*unitey);
    label.lft(LATEX("\num{"&decimal(k)&"}"),(0,k*unitey));
    else:
    dotlabel.lft(LATEX("\num{"&decimal(k)&"}"),(0,k*unitey));
    fi;
    endfor;
    fi;
    drawarrow (0,0)--unitex*(maxx+1,0);
    drawarrow (0,0)--unitey*(0,maxy+2*Pasy);
    label.lrt(btex \useKV[ClesStat]{Donnee} etex,unitex*(maxx+1,0));
    label.urt(btex \useKV[ClesStat]{Effectif} etex,unitey*(0,maxy+2*Pasy));
    if Qualitatif: titi(#1); else:tata(#1); fi;
  \end{mpost}
  \fi
}

% la construction du graphique qualitatif
\def\NewMPStatCirculaireQ#1#2#3#4{%
  %#1 : la liste des données
  %#2 : 360 ou 180
  %#3 : liste des couleurs
  %#4 : liste des légendes à effacer.
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    Rayon:=\useKV[ClesStat]{Rayon};
    ecarthachures=\useKV[ClesStat]{EcartHachures};
    epaisseurhachures=\useKV[ClesStat]{EpaisseurHachures};
    boolean AffichageAngle;
    AffichageAngle=\useKV[ClesStat]{AffichageAngle};
    boolean AffichageDonnee;
    AffichageDonnee=\useKV[ClesStat]{AffichageDonnee};
    boolean Hachures;
    Hachures=\useKV[ClesStat]{Hachures};
    boolean Inverse;
    Inverse=\useKV[ClesStat]{LectureInverse};
    boolean Legende;
    Legende=\useKV[ClesStat]{Legende};
    boolean LegendeVide;
    LegendeVide=\useKV[ClesStat]{LegendeVide};
    boolean Retour;
    Retour=false;
    boolean ACompleter;
    ACompleter=\useKV[ClesStat]{ACompleter};
    pair A[],O,B[],C[],D[];
    O=(0,0);
    n:=0;
    numeric total[],ang[];
    total[0]=0;
    ang[0]:=0;
    path cc;
    cc=(fullcircle scaled (2*Rayon));
    % on r\'ecup\`ere les couleurs
    color Col[];
    n:=0;
    for p_=#3:
    n:=n+1;
    Col[n]=p_;
    endfor;
    if Inverse=false:
    A[0]=point(0) of cc;
    else:
    A[0]=point(180) of cc;
    fi;
    vardef toto(text t)=
    n:=0;
    for p_=t:
    if numeric p_:
    n:=n+1;
    total[n]:=total[n-1]+p_;
    fi;
    endfor;
    N=n;
    for k=1 upto N:
    ang[k]=(#2/total[N])*total[k];
    endfor;
    n:=0;
    for p_=t:
    if numeric p_:
    n:=n+1;
    if Inverse=false:
    A[n]=A[n-1] rotatedabout(O,p_*(#2/total[N]));
    else:
    A[n]=A[n-1] rotatedabout(O,-p_*(#2/total[N]));
    fi;
    %hachure ou pas ?
    if Hachures=false:
    fill (O--if Inverse=false:arccercle(A[n-1],A[n],O) else:
    arccercle(A[n],A[n-1],O) fi--cycle) withcolor if unknown Col[n]: white else:Col[n] fi;
    else:
    draw
    Hachurage((O--if Inverse=false:arccercle(A[n-1],A[n],O)
    else:arccercle(A[n],A[n-1],O) fi--cycle),p_*(#2/total[N]) if
    (n mod 2)=0: +90 else: -90 fi,ecarthachures,if (n mod 2)=0 : 0 else: 1 fi)
    withpen pencircle scaled epaisseurhachures if AffichageAngle: withcolor 0.5white fi;
    fi;
    if ACompleter=false:
    draw A[n-1]--O--A[n] if Hachures: withpen pencircle scaled2 fi;
    fi;
    % Affichage des angles associ\'es
    if AffichageAngle:
    if round(p_*(#2/total[N]))>15:
    if (n mod 2)=0:
    marque_a:=20*0.75*Rayon/cm;
    else:
    marque_a:=20*0.5*Rayon/cm;
    fi;
    if Hachures:
    if Inverse=false:
    undraw
    Codeangle(A[n-1],O,A[n],0,(((TEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    else:
    undraw
    Codeangle(A[n],O,A[n-1],0,(((TEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    fi;
    fill cercles(w shifted(marque_ang*unitvector(w-O)),3mm) withcolor
    blanc;
    fi;
    if Inverse=false:
    draw
    Codeangle(A[n-1],O,A[n],0,(((TEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    else:
    draw
    Codeangle(A[n],O,A[n-1],0,(((TEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    fi;
    fi;
    elseif AffichageDonnee:
    if round(p_*(#2/total[N]))>15:
    if (n mod 2)=0:
    marque_a:=20*0.75*Rayon/cm;
    else:
    marque_a:=20*0.5*Rayon/cm;
    fi;
    if Hachures:
    if Inverse=false:
    undraw
    Codeangle(A[n-1],O,A[n],0,TEX(""&decimal(p_)&""));
    else:
    undraw
    Codeangle(A[n],O,A[n-1],0,(((TEX(""&decimal(p_)&"")))));
    fi;
    fill cercles(w shifted(marque_ang*unitvector(w-O)),3mm) withcolor
    blanc;
    fi;
    if Inverse=false:
    draw
    Codeangle(A[n-1],O,A[n],0,(((TEX(""&decimal(p_)&"")))));
    else:
    draw
    Codeangle(A[n],O,A[n-1],0,(((TEX(""&decimal(p_)&"")))));
    fi;
    fi;
    fi;
    %
    fi;
    endfor;
    if #2=360:
    draw cc if Hachures: withpen pencircle scaled2 fi;
    else:
    draw (subpath(0,length cc/2) of cc)--cycle if Hachures: withpen pencircle scaled2 fi;;
    fi;
    n:=0;
    if Legende:
    for p_=t:
    if string p_:
    n:=n+1;
    C[n]=A[n-1] rotatedabout(O,if Inverse:-1* fi(ang[n]-ang[n-1])/2);
    draw 0.95[O,C[n]]--1.05[O,C[n]];
    C[n]:=1.05[O,C[n]];
    Test(n);
    if (xpart(C[n])>xpart(O)) and (ypart(C[n])>ypart(O)):
    D[n]=C[n]+(0.5cm,0);
    draw C[n]--D[n];
    if Retour=false:label.urt(TEX(p_),D[n]);fi;
    fi;
    if (xpart(C[n])<xpart(O)) and (ypart(C[n])>ypart(O)):
    D[n]=C[n]-(0.5cm,0);
    draw C[n]--D[n];
    if Retour=false:label.ulft(TEX(p_),D[n]);fi;
    fi;
    if (xpart(C[n])<xpart(O)) and (ypart(C[n])<ypart(O)):
    D[n]=C[n]-(0.5cm,0);
    draw C[n]--D[n];
    if Retour=false:label.llft(TEX(p_),D[n]);fi;
    fi;
    if (xpart(C[n])>xpart(O)) and (ypart(C[n])<ypart(O)):
    D[n]=C[n]+(0.5cm,0);
    draw C[n]--D[n];
    if Retour=false:label.lrt(TEX(p_),D[n]);fi;
    fi;
    fi;
    endfor;
    fi;
    enddef;
    vardef Test(expr nb)=
    Retour:=false;
    op:=0;
    for l_=#4:
    if l_=nb:
    op:=op+1;
    fi;
    endfor;
    if op>0:
    Retour:=true;
    fi;
    enddef;    
    Figure(-10u,-10u,10u,10u);
    toto(#1);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={%
      Rayon:=\useKV[ClesStat]{Rayon};
      ecarthachures=\useKV[ClesStat]{EcartHachures};
      epaisseurhachures=\useKV[ClesStat]{EpaisseurHachures};
      boolean AffichageAngle;
      AffichageAngle=\useKV[ClesStat]{AffichageAngle};
      boolean AffichageDonnee;
      AffichageDonnee=\useKV[ClesStat]{AffichageDonnee};
      boolean Hachures;
      Hachures=\useKV[ClesStat]{Hachures};
      boolean Inverse;
      Inverse=\useKV[ClesStat]{LectureInverse};
      boolean Legende;
      Legende=\useKV[ClesStat]{Legende};
      boolean LegendeVide;
      LegendeVide=\useKV[ClesStat]{LegendeVide};
      boolean ACompleter;
      ACompleter=\useKV[ClesStat]{ACompleter};
    }]
    boolean Retour;
    Retour=false;
    pair A[],O,B[],C[],D[];
    O=(0,0);
    n:=0;
    numeric total[],ang[];
    total[0]=0;
    ang[0]:=0;
    path cc;
    cc=(fullcircle scaled (2*Rayon));
    % on r\'ecup\`ere les couleurs
    color Col[];
    n:=0;
    for p_=#3:
    n:=n+1;
    Col[n]=p_;
    endfor;
    if Inverse=false:
    A[0]=point(0) of cc;
    else:
    A[0]=point(180) of cc;
    fi;
    vardef toto(text t)=
    n:=0;
    for p_=t:
    if numeric p_:
    n:=n+1;
    total[n]:=total[n-1]+p_;
    fi;
    endfor;
    N=n;
    for k=1 upto N:
    ang[k]=(#2/total[N])*total[k];
    endfor;
    n:=0;
    for p_=t:
    if numeric p_:
    n:=n+1;
    if Inverse=false:
    A[n]=A[n-1] rotatedabout(O,p_*(#2/total[N]));
    else:
    A[n]=A[n-1] rotatedabout(O,-p_*(#2/total[N]));
    fi;
    %hachure ou pas ?
    if Hachures=false:
    fill (O--if Inverse=false:arccercle(A[n-1],A[n],O) else:
    arccercle(A[n],A[n-1],O) fi--cycle) withcolor if unknown Col[n]: white else:Col[n] fi;
    else:
    draw
    Hachurage((O--if Inverse=false:arccercle(A[n-1],A[n],O)
    else:arccercle(A[n],A[n-1],O) fi--cycle),p_*(#2/total[N]) if
    (n mod 2)=0: +90 else: -90 fi,ecarthachures,if (n mod 2)=0 : 0 else: 1 fi)
    withpen pencircle scaled epaisseurhachures if AffichageAngle: withcolor 0.5white fi;
    fi;
    if ACompleter=false:
    draw A[n-1]--O--A[n] if Hachures: withpen pencircle scaled2 fi;
    fi;
    % Affichage des angles associ\'es
    if AffichageAngle:
    if round(p_*(#2/total[N]))>15:
    if (n mod 2)=0:
    marque_a:=20*0.75*Rayon/cm;
    else:
    marque_a:=20*0.5*Rayon/cm;
    fi;
    if Hachures:
    if Inverse=false:
    undraw
    Codeangle(A[n-1],O,A[n],0,(((LATEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    else:
    undraw
    Codeangle(A[n],O,A[n-1],0,(((LATEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    fi;
    fill cercles(w shifted(marque_ang*unitvector(w-O)),3mm) withcolor
    blanc;
    fi;
    if Inverse=false:
    draw
    Codeangle(A[n-1],O,A[n],0,(((LATEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    else:
    draw
    Codeangle(A[n],O,A[n-1],0,(((LATEX("\ang{"&decimal(round(p_*(#2/total[N])))&"}")))));
    fi;
    fi;
    elseif AffichageDonnee:
    if round(p_*(#2/total[N]))>15:
    if (n mod 2)=0:
    marque_a:=20*0.75*Rayon/cm;
    else:
    marque_a:=20*0.5*Rayon/cm;
    fi;
    if Hachures:
    if Inverse=false:
    undraw
    Codeangle(A[n-1],O,A[n],0,LATEX(""&decimal(p_)&""));
    else:
    undraw
    Codeangle(A[n],O,A[n-1],0,(((LATEX(""&decimal(p_)&"")))));
    fi;
    fill cercles(w shifted(marque_ang*unitvector(w-O)),3mm) withcolor
    blanc;
    fi;
    if Inverse=false:
    draw
    Codeangle(A[n-1],O,A[n],0,(((LATEX(""&decimal(p_)&"")))));
    else:
    draw
    Codeangle(A[n],O,A[n-1],0,(((LATEX(""&decimal(p_)&"")))));
    fi;
    fi;
    fi;
    %
    fi;
    endfor;
    if #2=360:
    draw cc if Hachures: withpen pencircle scaled2 fi;
    else:
    draw (subpath(0,length cc/2) of cc)--cycle if Hachures: withpen pencircle scaled2 fi;;
    fi;
    n:=0;
    if Legende:
    for p_=t:
    if string p_:
    n:=n+1;
    C[n]=A[n-1] rotatedabout(O,if Inverse:-1* fi(ang[n]-ang[n-1])/2);
    draw 0.95[O,C[n]]--1.05[O,C[n]];
    C[n]:=1.05[O,C[n]];
    Test(n);
    if Retour=false:
    if (xpart(C[n])>xpart(O)) and (ypart(C[n])>ypart(O)):
    D[n]=C[n]+(0.5cm,0);
    draw C[n]--D[n];
    label.urt(LATEX(p_),D[n]);
    fi;
    if (xpart(C[n])<xpart(O)) and (ypart(C[n])>ypart(O)):
    D[n]=C[n]-(0.5cm,0);
    draw C[n]--D[n];
    label.ulft(LATEX(p_),D[n]);
    fi;
    if (xpart(C[n])<xpart(O)) and (ypart(C[n])<ypart(O)):
    D[n]=C[n]-(0.5cm,0);
    draw C[n]--D[n];
    label.llft(LATEX(p_),D[n]);
    fi;
    if (xpart(C[n])>xpart(O)) and (ypart(C[n])<ypart(O)):
    D[n]=C[n]+(0.5cm,0);
    draw C[n]--D[n];
    label.lrt(LATEX(p_),D[n]);
    fi;
    fi;
    fi;
    endfor;
    fi;
    enddef;
    vardef Test(expr nb)=
    Retour:=false;
    op:=0;
    for l_=#4:
    if l_=nb:
    op:=op+1;
    fi;
    endfor;
    if op>0:
    Retour:=true;
    fi;
    enddef;    
    Figure(-10u,-10u,10u,10u);
    toto(#1);
  \end{mpost}
  \fi
}%

%Pour la m\'ediane.
\DTLgnewdb{mtdb}%
\dtlexpandnewvalue%
\newcount\nbdonnees%
% 
\def\AjoutListEEaa#1\nil{\addtotok\tabtoksEEa{#1,}}%
\def\AjoutListEEab#1\nil{\addtotok\tabtoksEEa{#1/}}%
\def\AjoutListEEb#1\nil{\addtotok\tabtoksEEb{#1,}}%
\def\AjoutListEEx#1\nil{\addtotok\tabtoksEE{#1,}}%
\def\AjoutListEEy#1\nil{\addtotok\tabtoksEE{#1/}}%

\DTLgnewdb{mtdbEE}%
\DTLgnewdb{mtdbEEqual}%
%
\newcommand\Stat[2][]{%
  \useKVdefault[ClesStat]%
  \setKV[ClesStat]{#1}%
  \ifboolKV[ClesStat]{Representation}{%
    \setKV[TraceG]{Xmin=0,Ymin=0}%
    \setKV[TraceG]{#1}%
    \readlist*\ListePointsPlaces{#2}%
    \newtoks\toklistepoint%
    \foreachitem\compteur\in\ListePointsPlaces{\expandafter\Updatetoks\compteur\nil}%
    \MPPlacePoint[#1]{\the\toklistepoint}%
  }{%
    \ifboolKV[ClesStat]{Liste}{%
      \setsepchar{,}\ignoreemptyitems%
      \readlist*\Liste{#2}%
      \xdef\foo{}%
      \setsepchar[*]{,*/}\ignoreemptyitems%
      \xintFor* ##1 in {\xintSeq {1}{\Listelen}}\do{%
        \xdef\foo{\foo 1/\Liste[##1],}%
      }%
      \readlist*\ListeComplete{\foo}%
      \setKV[ClesStat]{Qualitatif}%
    }{%
      \ifboolKV[ClesStat]{Sondage}{%
        \setsepchar{,}\ignoreemptyitems%
        \readlist*\Liste{#2}%
        % "liste vide"
        \newtoks\tabtoksEEa%
        \tabtoksEEa{}%
        % 
        % "liste vide"
        \newtoks\tabtoksEEb%
        \tabtoksEEb{}%
        % 
        \readlist*\ListeSansDoublonsEE{999}%   %% Pour ne pas avoir une liste vide
        % 
        \newcount\cmptEE%
        \newcount\PasNumEE%    %% Permettra de savoir si ce sondage est qualitatif ou quantitatif
        \PasNumEE=0\relax%
        \DTLcleardb{mtdbEE}%
        % on range les resultats du sondage par ordre croissant.
        \foreachitem\x\in\Liste{%
          \DTLnewrow{mtdbEE}%
          \DTLnewdbentry{mtdbEE}{Numeric}{\x}%
        }%
        \dtlsort{Numeric}{mtdbEE}{\dtlicompare}%
        \DTLforeach{mtdbEE}{\nba=Numeric}{%
          \IfDecimal{\nba}{}{\PasNumEE=\numexpr\PasNumEE+1\relax}%
          \cmptEE=0\relax%
          \foreachitem\nbb\in\ListeSansDoublonsEE{%
            \ifthenelse{\equal{\nba}{\nbb}}{\cmptEE=\numexpr\cmptEE+1\relax}{}%
          }%
          \ifthenelse{\equal{\the\cmptEE}{0}}{%
            \expandafter\AjoutListEEb\nba\nil%
            \xdef\listEEa{\the\tabtoksEEb}%
            \ignoreemptyitems%
            \setsepchar{,}%
            \readlist*\ListeSansDoublonsEE\listEEa%    	%%% Enl\`eve tous les \'elements
            %%% identiques de Liste
          }{}%  
        }%	
        \foreachitem\nba\in\ListeSansDoublonsEE{%
          \cmptEE=0\relax%
          \DTLforeach{mtdbEE}{\nbb=Numeric}{%
            \ifthenelse{\equal{\nba}{\nbb}}{\cmptEE=\numexpr\cmptEE+1\relax}{}%
          }%
          \expandafter\AjoutListEEab\nba\nil%
          \expandafter\AjoutListEEaa\the\cmptEE\nil% 	%%% Compte tous les \'elements
          %%% identiques de Liste
        }%
        \xdef\listEEb{\the\tabtoksEEa}
        \ignoreemptyitems%
        \setsepchar[*]{,*/}%
        \readlist*\ListeComplete\listEEb%
        % 
        \ifthenelse{\equal{\the\PasNumEE}{0}}{\setKV[ClesStat]{Quantitatif}}{\setKV[ClesStat]{Qualitatif}}%
      }{%
        \ifboolKV[ClesStat]{Qualitatif}{%
          %  % on lit la liste \'ecrite sous la forme valeur/effectif
          \setsepchar[*]{,*/}\ignoreemptyitems%
          \readlist*\ListeInitiale{#2}%
          % "liste vide"
          \newtoks\tabtoksEE%
          \tabtoksEE{}%
          \DTLcleardb{mtdbEEqual}%
          \foreachitem\x\in\ListeInitiale{%
            \DTLnewrow{mtdbEEqual}%
            \itemtomacro\ListeInitiale[\xcnt,1]\x%
            \DTLnewdbentry{mtdbEEqual}{Val}{\x}%
            \itemtomacro\ListeInitiale[\xcnt,2]\y%
            \DTLnewdbentry{mtdbEEqual}{Eff}{\y}%
          }%
          \DTLforeach{mtdbEEqual}{\Val=Val,\Eff=Eff}{%  
            \expandafter\AjoutListEEy\Val\nil%
            \expandafter\AjoutListEEx\Eff\nil%
          }%
          \xdef\listEE{\the\tabtoksEE}
          \ignoreemptyitems%
          \setsepchar[*]{,*/}%
          \readlist*\ListeComplete\listEE%
        }{% Dans le qualitatif, on trie d'abord les valeurs.
          \setsepchar[*]{,*/}\ignoreemptyitems%
          \readlist*\ListeInitiale{#2}%
          % "liste vide"
          \newtoks\tabtoksEE%
          \tabtoksEE{}%
          \DTLcleardb{mtdbEEqual}%
          \foreachitem\x\in\ListeInitiale{%
            \DTLnewrow{mtdbEEqual}%
            \itemtomacro\ListeInitiale[\xcnt,1]\x%
            \DTLnewdbentry{mtdbEEqual}{Val}{\x}%
            \itemtomacro\ListeInitiale[\xcnt,2]\y%
            \DTLnewdbentry{mtdbEEqual}{Eff}{\y}%
          }%
          \dtlsort{Val}{mtdbEEqual}{\dtlicompare}%
          \DTLforeach{mtdbEEqual}{\Val=Val,\Eff=Eff}{%  
            \expandafter\AjoutListEEy\Val\nil%
            \expandafter\AjoutListEEx\Eff\nil%
          }%
          \xdef\listEE{\the\tabtoksEE}
          \ignoreemptyitems%
          \setsepchar[*]{,*/}%
          \readlist*\ListeComplete\listEE%
        }}}%
    % on cr\'ee la base de donn\'ees des valeurs dans le cas qualitatif
    \DTLcleardb{mtdb}%
    % on les trie pour la m\'ediane dans le cas qualitatif % Touhami / Texnique.fr
    \foreachitem\x\in\ListeComplete{%
      \DTLnewrow{mtdb}%
      \itemtomacro\ListeComplete[\xcnt,2]\y%
      \DTLnewdbentry{mtdb}{Numeric}{\y}%
    }%
    \dtlsort{Numeric}{mtdb}{\dtlicompare}%
    %  % on r\'einitialise les valeurs des crit\`eres de position et de
    % dispersion
    \renewcommand\NbDonnees{}%
    \renewcommand\SommeDonnees{}%
    \renewcommand\EffectifTotal{}%
    \renewcommand\Moyenne{}%
    \renewcommand\Etendue{}%
    \renewcommand\Mediane{}%
    \renewcommand\DonneeMax{0}%
    \renewcommand\EffectifMax{0}%
    \renewcommand\DonneeMin{999999999}%
    \ifboolKV[ClesStat]{Qualitatif}{%D\'ebut qualitatif
      % Calculs
      %  %% celui de la somme des donn\'ees
      \foreachitem\don\in\ListeComplete{\xdef\SommeDonnees{\fpeval{\SommeDonnees+\ListeComplete[\doncnt,2]}}}%
      %  %% celui de l'effectif total
      \ifboolKV[ClesStat]{EffectifTotal}{%
        \ifboolKV[ClesStat]{Liste}{L'effectif total de la s\'erie est
          \num{\ListeCompletelen}.\par}{%
          \foreachitem\don\in\ListeComplete{\xdef\EffectifTotal{\fpeval{\EffectifTotal+\ListeComplete[\doncnt,2]}}}%
          L'effectif total de la s\'erie est : \[\ListeComplete[1,2]\xintFor* ##1 in
            {\xintSeq {2}{\ListeCompletelen}}\do{%
              +\ListeComplete[##1,2]}=\num{\EffectifTotal}\]}
      }{}%
      \ifboolKV[ClesStat]{Liste}{\xdef\EffectifTotal{\ListeCompletelen}}{\xdef\EffectifTotal{\SommeDonnees}}%
      %  %% celui de la moyenne
      \xdef\Moyenne{\fpeval{\SommeDonnees/\ListeCompletelen}}%	
      \ifboolKV[ClesStat]{Moyenne}{%
        \ifboolKV[ClesStat]{Liste}{%
          La somme des donn\'ees de la s\'erie est :%
          \xintifboolexpr{\ListeCompletelen<\useKV[ClesStat]{Coupure}}{%
            \[
              \num{\ListeComplete[1,2]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}\xintFor* ##1 in {\xintSeq {2}{\ListeCompletelen}}\do{%
                +\num{\ListeComplete[##1,2]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
              }=\num{\SommeDonnees}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}%
            \]}{%
            \[
              \num{\ListeComplete[1,2]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}\xintFor* ##1 in {\xintSeq {2}{3}}\do{%
                +\num{\ListeComplete[##1,2]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}}+\dots\xintFor* ##1 in {\xintSeq {\ListeCompletelen-1}{\ListeCompletelen}}\do{%
                +\num{\ListeComplete[##1,2]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
              }=\num{\SommeDonnees}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}%
            \]%
          }%
          \ifboolKV[ClesStat]{SET}{}{Le nombre de donn\'ees de la s\'erie est \num{\ListeCompletelen}.\\}%
          Donc la moyenne de la s\'erie est \'egale \`a :%
          \[\frac{\num{\SommeDonnees}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}}{\num{\ListeCompletelen}}%\IfInteger{\fpeval{round(\fpeval{\SommeDonnees/\ListeCompletelen},\useKV[ClesStat]{Precision})}}{=}{\approx}
            \ifboolKV[ClesStat]{ValeurExacte}{}{%
              \opdiv*{\SommeDonnees}{\ListeCompletelen}{resultatmoy}{restemoy}%
              \opround{resultatmoy}{\useKV[ClesStat]{Precision}}{resultatmoy1}%
              \opcmp{resultatmoy}{resultatmoy1}\ifopeq=\else\approx\fi%
              \num{\fpeval{round(\SommeDonnees/\ListeCompletelen,\useKV[ClesStat]{Precision})}}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}%
            }%
          \]%
        }{Pas de moyenne possible pour une s\'erie de donn\'ees \`a caract\`ere qualitatif.}}{}%
      %    %  %% celui de l'\'etendue
      \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
        \xintifboolexpr{\ListeComplete[##1,2]>\DonneeMax}{%
          \xdef\DonneeMax{\ListeComplete[##1,2]}%
        }{}%
        \xintifboolexpr{\ListeComplete[##1,2]<\DonneeMin}{%
          \xdef\DonneeMin{\ListeComplete[##1,2]}%
        }{}%
      }%
      \xdef\EffectifMax{\DonneeMax}%
      \xdef\Etendue{\fpeval{\DonneeMax-\DonneeMin}}%
      \ifboolKV[ClesStat]{Etendue}{%
        \ifboolKV[ClesStat]{Liste}{%
          L'\'etendue de la s\'erie est \'egale \`a $\num{\DonneeMax}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}-\num{\DonneeMin}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}=\num{\Etendue}$\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}%
        }{Pas d'\'etendue possible pour une s\'erie de donn\'ees \`a caract\`ere qualitatif.}}{}%
      % celui de la mediane
      %%% Recuperation de la mediane %%%%%%%%%%%%%%%%%%%%% 
      \newcount\Recapmed%
      \newcount\Recapmeda%
      \ifodd\number\ListeCompletelen%odd impair
      \Recapmed=\fpeval{(\ListeCompletelen+1)/2}\relax%
      \else%
      \Recapmed=\fpeval{\ListeCompletelen/2}\relax%
      \Recapmeda=\numexpr\Recapmed+1\relax%
      \fi%
      \newcount\Recapk%
      \Recapk=0%
      \DTLforeach{mtdb}{\numeroDonnee=Numeric}{\Recapk=\numexpr\Recapk+1\relax%
        \ifnum\Recapk=\Recapmed%
        \ifodd\number\ListeCompletelen%
        \xdef\Mediane{\numeroDonnee}%
        \else%
        \xdef\Mediane{\numeroDonnee}%
        \fi%
        \fi%
        \ifnum\Recapk=\Recapmeda%
        \xdef\Mediane{\fpeval{(\Mediane+\numeroDonnee)/2}}%
        \fi%
      }%
      %%% 
      \ifboolKV[ClesStat]{Mediane}{%
        \ifboolKV[ClesStat]{Liste}{%    
          On range les donn\'ees par ordre croissant :%
          \nbdonnees=0%
          \xintifboolexpr{\ListeCompletelen<\useKV[ClesStat]{Coupure}}{%
            \[\DTLforeach{mtdb}{\numeroDonnee=Numeric}{\num{\numeroDonnee}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}\DTLiflastrow{.}{;}}\]%
          }{%
            \medskip%
            \begin{center}
              \begin{minipage}{0.9\linewidth}
                \DTLforeach*{mtdb}{\numeroDonnee=Numeric}{\num{\numeroDonnee}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}\DTLiflastrow{.}{;
                  }\nbdonnees=\fpeval{\nbdonnees+1}\modulo{\nbdonnees}{\useKV[ClesStat]{Coupure}}\xintifboolexpr{\remainder==0}{\\}{}}
              \end{minipage}
            \end{center}%
            \medskip%
          }%
          \newcount\med%
          \newcount\meda%
          \ifodd\number\ListeCompletelen%odd impair
          \med=\fpeval{(\ListeCompletelen+1)/2}\relax%
          L'effectif total de la s\'erie est \num{\ListeCompletelen}. Or, $\num{\ListeCompletelen}=\num{\fpeval{\med-1}}+1+\num{\fpeval{\med-1}}$.\\
          \else% pair
          \med=\fpeval{\ListeCompletelen/2}\relax%
          \meda=\numexpr\med+1\relax%
          L'effectif total de la s\'erie est \num{\ListeCompletelen}. Or, $\num{\ListeCompletelen}=\num{\the\med}+\num{\the\med}$.\\
          \fi%
          \newcount\k%
          \k=0%
          \DTLforeach{mtdb}{\numeroDonnee=Numeric}{\k=\numexpr\k+1\relax%
            \ifnum\k=\med %La m\'ediane vaut \numeroDonnee\fi
            \ifodd\number\ListeCompletelen%
            La m\'ediane de la s\'erie est la \the\med\ieme{} donn\'ee.\\Donc la m\'ediane de la s\'erie est \num{\numeroDonnee}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}%
            \xdef\Mediane{\numeroDonnee}%
            \else%
            La \the\med\ieme{} donn\'ee est \num{\numeroDonnee}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}. }{. }\xdef\Mediane{\numeroDonnee}%
            \fi%
            \fi%
            \ifnum\k=\meda
            La \the\meda\ieme{} donn\'ee est \num{\numeroDonnee}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.} Donc la m\'ediane de la s\'erie est \xdef\Mediane{\fpeval{(\Mediane+\numeroDonnee)/2}}\num{\Mediane}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}%
            \fi%
          }%
          %%%%%%% 
        }{Pas de m\'ediane possible pour une s\'erie de donn\'ees \`a caract\`ere qualitatif.}}{}
      %%% Quartile un
      \newcount\PfCQuartileUn%
      \modulo{\ListeCompletelen}{4}\relax%
      \ifnum\remainder=0%
      \PfCQuartileUn=\fpeval{\ListeCompletelen/4}%
      \else%
      \PfCQuartileUn=\fpeval{ceil(\ListeCompletelen/4)}%
      \fi%
      \newcount\PfCQunk%
      \PfCQunk=0%
      \DTLforeach{mtdb}{\numeroDonnee=Numeric}{\PfCQunk=\numexpr\PfCQunk+1\relax%
        \ifnum\PfCQunk=\PfCQuartileUn%
        \xdef\QuartileUn{\numeroDonnee}%
        \fi%
      }%
      %%% Quartile trois
      \newcount\PfCQuartileTrois%
      \modulo{\ListeCompletelen}{4}\relax%
      \ifnum\remainder=0%
      \PfCQuartileTrois=\fpeval{3*\ListeCompletelen/4}%
      \else%
      \PfCQuartileTrois=\fpeval{ceil(3*\ListeCompletelen/4)}%
      \fi%
      \newcount\PfCQtroisk%
      \PfCQtroisk=0%
      \DTLforeach{mtdb}{\numeroDonnee=Numeric}{\PfCQtroisk=\numexpr\PfCQtroisk+1\relax%
        \ifnum\PfCQtroisk=\PfCQuartileTrois%La m\'ediane vaut \numeroDonnee\fi
        \xdef\QuartileTrois{\numeroDonnee}%
        \fi%
      }%
      % Construction du tableau
      \ifboolKV[ClesStat]{Tableau}{%
        \ifboolKV[ClesStat]{Liste}{Pas de tableau possible avec la cl\'e Liste.\\Utilisez plut\^ot la cl\'e Sondage si vous voulez un tableau avec cette liste.}{\BuildtabStat}}{}%
      % Construction du graphique
      \ifboolKV[ClesStat]{Graphique}{%
        \ifboolKV[ClesStat]{Liste}{Pas de graphique possible avec la cl\'e Liste.\\Utilisez plut\^ot la cl\'e Sondage si vous voulez un graphique avec cette liste.}{%
          \ifboolKV[ClesStat]{Barre}{%
            \buildgraphbarhor%
          }{\ifboolKV[ClesStat]{Angle}{\buildgraphcq{360}}{\ifboolKV[ClesStat]{SemiAngle}{\buildgraphcq{180}}{\buildgraphq[#1]}}}%
        }}{}%
    }{%%%%%%%%%%%%%%%%%%%%%D\'ebut quantitatif
      %  % on effectue les calculs
      %  %% celui de la somme des donn\'ees
      \foreachitem\don\in\ListeComplete{\xdef\SommeDonnees{\fpeval{\SommeDonnees+\ListeComplete[\doncnt,1]*\ListeComplete[\doncnt,2]}}}%
      %  %% celui de l'effectif total
      \foreachitem\don\in\ListeComplete{\xdef\EffectifTotal{\fpeval{\EffectifTotal+\ListeComplete[\doncnt,2]}}}%
      %  %% celui de l'\'etendue
      \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
        \xintifboolexpr{\ListeComplete[##1,1]>\DonneeMax}{%
          \xdef\DonneeMax{\ListeComplete[##1,1]}%
        }{}%
        \xintifboolexpr{\ListeComplete[##1,1]<\DonneeMin}{%
          \xdef\DonneeMin{\ListeComplete[##1,1]}%
        }{}%
      }%
      % \xdef\EffectifMax{\DonneeMax}%
      \xdef\Etendue{\fpeval{\DonneeMax-\DonneeMin}}%%
      %  %% celui de la moyenne
      \xdef\Moyenne{\fpeval{\SommeDonnees/\EffectifTotal}}%
      \ifboolKV[ClesStat]{EffectifTotal}{%
        L'effectif total de la s\'erie est : \[\ListeComplete[1,2]\xintFor* ##1 in
          {\xintSeq {2}{\ListeCompletelen}}\do{%
            +\ListeComplete[##1,2]}=\num{\EffectifTotal}\]
      }{}%
      \ifboolKV[ClesStat]{Moyenne}{%
        La somme des donn\'ees de la s\'erie est :%
        \xintifboolexpr{\ListeCompletelen<\useKV[ClesStat]{Coupure}}{%
          \[
            \ifnum\ListeComplete[1,2]=1\else\num{\ListeComplete[1,2]}\times\fi\num{\ListeComplete[1,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}\xintFor* ##1 in {\xintSeq {2}{\ListeCompletelen}}\do{%
              +\ifnum\ListeComplete[##1,2]=1\else\num{\ListeComplete[##1,2]}\times\fi\num{\ListeComplete[##1,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
            }=\num{\SommeDonnees}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
          \]
        }{%
          \[
            \ifnum\ListeComplete[1,2]=1\else\num{\ListeComplete[1,2]}\times\fi\num{\ListeComplete[1,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}\xintFor* ##1 in {\xintSeq {2}{2}}\do{%
              +\ifnum\ListeComplete[##1,2]=1\else\num{\ListeComplete[##1,2]}\times\fi\num{\ListeComplete[##1,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
            }+\dots\xintFor* ##1 in {\xintSeq {\ListeCompletelen-1}{\ListeCompletelen}}\do{%
              +\ifnum\ListeComplete[##1,2]=1\else\num{\ListeComplete[##1,2]}\times\fi\num{\ListeComplete[##1,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
            }=\num{\SommeDonnees}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}
          \]
        }%
        \ifboolKV[ClesStat]{SET}{}{L'effectif total de la s\'erie est :%
          \ifboolKV[ClesStat]{Liste}{ \num{\EffectifTotal}\\}{%
            \[\num{\ListeComplete[1,2]}\xintFor* ##1 in {\xintSeq {2}{\ListeCompletelen}}\do{%
                +\num{\ListeComplete[##1,2]}
              }=\num{\EffectifTotal}
            \]%
          }%
        }%
        Donc la moyenne de la s\'erie est \'egale \`a :%
        \[\frac{\num{\SommeDonnees}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}}{\num{\EffectifTotal}}%
          \ifboolKV[ClesStat]{ValeurExacte}{}{%
            \opdiv*{\SommeDonnees}{\EffectifTotal}{resultatmoy}{restemoy}%
            \opround{resultatmoy}{\useKV[ClesStat]{Precision}}{resultatmoy1}%
            \opcmp{resultatmoy}{resultatmoy1}\ifopeq=\else\approx\fi%
            \num{\fpeval{round(\SommeDonnees/\EffectifTotal,\useKV[ClesStat]{Precision})}}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}%
          }%
        \]%
      }{}%
      %  % Affichage des r\'eponses.
      %  %% pour l'\'etendue
      \ifboolKV[ClesStat]{Etendue}{L'\'etendue de la s\'erie est \'egale \`a $\num{\ListeComplete[\ListeCompletelen,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}-\num{\ListeComplete[1,1]}\ifboolKV[ClesStat]{Concret}{~\text{\useKV[ClesStat]{Unite}}}{}=\num{\Etendue}$\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}}{}%
      % pour la m\'ediane
      %%% Recuperation Mediane
      \newcount\Recupmed%
      \newcount\Recupmeda%
      \ifodd\number\EffectifTotal%odd impair
      \Recupmed=\fpeval{(\EffectifTotal+1)/2}\relax%
      \else% pair
      \Recupmed=\fpeval{\EffectifTotal/2}\relax%
      \Recupmeda=\numexpr\Recupmed+1\relax%
      \fi%
      \newcount\Recupk%
      \Recupk=0%
      \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
        \xintFor* ##2 in {\xintSeq {1}{\ListeComplete[##1,2]}}\do{%
          \Recupk=\numexpr\Recupk+1\relax%
          \ifnum\Recupk=\Recupmed%
          \ifodd\number\EffectifTotal%
          \xdef\Mediane{\ListeComplete[##1,1]}%
          \else%
          \xdef\Mediane{\ListeComplete[##1,1]}%
          \fi%
          \fi%
          \ifnum\Recupk=\Recupmeda%
          \xdef\Mediane{\fpeval{(\Mediane+\ListeComplete[##1,1])/2}}%
          \fi%
        }%
      }%
      %%% 
      \ifboolKV[ClesStat]{Mediane}{%
        
        \newcount\med%
        \newcount\meda%
        \ifodd\number\EffectifTotal%odd impair
        \med=\fpeval{(\EffectifTotal+1)/2}\relax%
        L'effectif total de la s\'erie est \num{\EffectifTotal}. Or, $\num{\EffectifTotal}=\num{\fpeval{\med-1}}+1+\num{\fpeval{\med-1}}$. %
        \else% pair
        \med=\fpeval{\EffectifTotal/2}\relax%
        \meda=\numexpr\med+1\relax%
        L'effectif total de la s\'erie est \num{\EffectifTotal}. Or, $\num{\EffectifTotal}=\num{\fpeval{\med}}+\num{\fpeval{\med}}$. %
        \fi%
        \newcount\k%
        \k=0%
        \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
          \xintFor* ##2 in {\xintSeq {1}{\ListeComplete[##1,2]}}\do{%
            \k=\numexpr\k+1\relax%
            \ifnum\k=\med%
            \ifodd\number\EffectifTotal%
            La m\'ediane de la s\'erie est la \the\med\ieme{} donn\'ee. Donc la m\'ediane de la s\'erie est \num{\ListeComplete[##1,1]}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}%
            \else%
            La \the\med\ieme{} donn\'ee est \num{\ListeComplete[##1,1]}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}. }{. }\xdef\Mediane{\ListeComplete[##1,1]}%
            \fi%
            \fi%
            \ifnum\k=\meda%
            La \the\meda\ieme{} donn\'ee est \num{\ListeComplete[##1,1]}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}\\Donc la m\'ediane de la s\'erie est \xdef\Mediane{\fpeval{(\Mediane+\ListeComplete[##1,1])/2}}\num{\Mediane}\ifboolKV[ClesStat]{Concret}{~\useKV[ClesStat]{Unite}.}{.}%
            \fi%
          }%
        }%
      }{}%
      %%% Quartile un
      \newcount\PfCQuartileUn%
      \modulo{\EffectifTotal}{4}\relax%
      \ifnum\remainder=0%
      \PfCQuartileUn=\fpeval{\EffectifTotal/4}%
      \else%
      \PfCQuartileUn=\fpeval{ceil(\EffectifTotal/4)}%
      \fi%
      \newcount\PfCQunk%
      \PfCQunk=0%
      \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
        \xintFor* ##2 in {\xintSeq {1}{\ListeComplete[##1,2]}}\do{%
          \PfCQunk=\numexpr\PfCQunk+1\relax%
          \ifnum\PfCQunk=\PfCQuartileUn%
          \xdef\QuartileUn{\ListeComplete[##1,1]}%
          \fi%
        }%
      }%
      %%% Quartile trois
      \newcount\PfCQuartileTrois%
      \modulo{\EffectifTotal}{4}\relax%
      \ifnum\remainder=0%
      \PfCQuartileTrois=\fpeval{3*\EffectifTotal/4}%
      \else%
      \PfCQuartileTrois=\fpeval{ceil(3*\EffectifTotal/4)}%
      \fi%
      \newcount\PfCQtroisk%
      \PfCQtroisk=0%
      \xintFor* ##1 in {\xintSeq {1}{\ListeCompletelen}}\do{%
        \xintFor* ##2 in {\xintSeq {1}{\ListeComplete[##1,2]}}\do{%
          \PfCQtroisk=\numexpr\PfCQtroisk+1\relax%
          \ifnum\PfCQtroisk=\PfCQuartileTrois%
          \xdef\QuartileTrois{\ListeComplete[##1,1]}%
          \fi%
        }%
      }%
      % Construction de tableau
      \ifboolKV[ClesStat]{Tableau}{\BuildtabStat}{}%
      % Construction du graphique ??
      \ifboolKV[ClesStat]{Graphique}{%
        \ifboolKV[ClesStat]{Angle}{\buildgraphcq{360}}{\ifboolKV[ClesStat]{SemiAngle}{\buildgraphcq{180}}{\buildgraph[#1]}}
      }{}%
    }%
  }%
}%

%%%
% Radar
%%%
\setKVdefault[ClesRadar]{Rayon=3cm,Reference=20,MoyenneClasse=false,Disciplines=false,Pas=5}

\newtoks\toklisteradara%pour la moyenne de l'\'el\`eve
\newtoks\toklisteradarb%pour la discipline
\newtoks\toklisteradarc%pour la moyenne de classe

\def\UpdateRadara#1/#2/#3\nil{\addtotok\toklisteradara{#1,}}
\def\UpdateRadarb#1/#2/#3\nil{\addtotok\toklisteradarb{"#2",}}
\def\UpdateRadarc#1/#2/#3\nil{\addtotok\toklisteradarc{#3,}}

\newcommand\MPRadar[6]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    pair O;
    O=(0,0);
    path cc;
    cc=cercles(O,#1);
    %%etiquettage des disciplines
    n:=0;%compter le nombre de disciplines
    for p_=#2:
    n:=n+1;
    endfor;
    for k=1 upto n:
    N[k]=k*(360/n);
    trace segment(O,pointarc(cc,N[k]));% dashed evenly;
    endfor;
    p:=0;
    for p_=#2:
    p:=p+1;
    if (N[p]<90) or (N[p]=90):
    label.urt(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    if ((N[p]>90) and (N[p]<180)) or (N[p]=180):
    label.ulft(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    if (N[p]>180) and (N[p]<270):
    label.llft(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    if (N[p]>270) or (N[p]=270):
    label.lrt(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    endfor;
    % trac\'e des pas:
    pas=#4/#3;
    for k=1 upto pas-1:
    trace (k/pas)[O,pointarc(cc,N[1])] for l=2 upto n: --(k/pas)[O,pointarc(cc,N[l])] endfor
    --cycle dashed evenly withcolor 0.5white;
    endfor;
    trace pointarc(cc,N[1]) for l=2 upto n: --pointarc(cc,N[l]) endfor
    --cycle;
    % etiquettage des pas
    dotlabel.urt(TEX("\tiny"&decimal(#4)),pointarc(cc,0));
    dotlabel.urt(TEX("\tiny"&decimal(#3)),(1/pas)[O,pointarc(cc,0)]);
    % trac\'e des r\'esultats \'el\`eves
    pair El[];
    el=0;
    for p_=#5:
    el:=el+1;
    El[el]=(p_/#4)[O,pointarc(cc,N[el])];
    endfor;
    trace El[1] for p=2 upto n:--El[p] endfor --cycle withpen
    pencircle scaled 1.5 withcolor blue;
    % trac\'e des r\'esultats classe
    pair Cl[];
    cl=0;
    for p_=#6:
    cl:=cl+1;
    Cl[cl]=(p_/#4)[O,pointarc(cc,N[cl])];
    endfor;
    trace Cl[1] for p=2 upto n:--Cl[p] endfor --cycle withcolor rouge;
  \end{mplibcode}
  \else
  \begin{mpost}
    pair O;
    O=(0,0);
    path cc;
    cc=cercles(O,#1);
    %%etiquettage des disciplines
    n:=0;%compter le nombre de disciplines
    for p_=#2:
    n:=n+1;
    endfor;
    for k=1 upto n:
    N[k]=k*(360/n);
    trace segment(O,pointarc(cc,N[k]));% dashed evenly;
    endfor;
    p:=0;
    for p_=#2:
    p:=p+1;
    if (N[p]<90) or (N[p]=90):
    label.urt(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    if ((N[p]>90) and (N[p]<180)) or (N[p]=180):
    label.ulft(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    if (N[p]>180) and (N[p]<270):
    label.llft(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    if (N[p]>270) or (N[p]=270):
    label.lrt(TEX(p_),1.025[O,pointarc(cc,N[p])]);
    fi;
    endfor;
    % trac\'e des pas:
    pas=#4/#3;
    for k=1 upto pas-1:
    trace (k/pas)[O,pointarc(cc,N[1])] for l=2 upto n: --(k/pas)[O,pointarc(cc,N[l])] endfor
    --cycle dashed evenly withcolor 0.5white;
    endfor;
    trace pointarc(cc,N[1]) for l=2 upto n: --pointarc(cc,N[l]) endfor
    --cycle;
    % etiquettage des pas
    dotlabel.top(LATEX("\noexpand\tiny"&decimal(#4)&"") rotated -90,pointarc(cc,0));
    dotlabel.urt(LATEX("\noexpand\tiny"&decimal(#3)&""),(1/pas)[O,pointarc(cc,0)]);
    % trac\'e des r\'esultats \'el\`eves
    pair El[];
    el=0;
    for p_=#5:
    el:=el+1;
    El[el]=(p_/#4)[O,pointarc(cc,N[el])];
    endfor;
    trace El[1] for p=2 upto n:--El[p] endfor --cycle withpen
    pencircle scaled 1.5 withcolor blue;
    % trac\'e des r\'esultats classe
    pair Cl[];
    cl=0;
    for p_=#6:
    cl:=cl+1;
    Cl[cl]=(p_/#4)[O,pointarc(cc,N[cl])];
    endfor;
    trace Cl[1] for p=2 upto n:--Cl[p] endfor --cycle withcolor rouge;
  \end{mpost}
  \fi
}

\newcommand\Radar[2][]{%
  % 1 les param\`etres
  % 2 la r\'epartition des notes
  \useKVdefault[ClesRadar]%
  \setKV[ClesRadar]{#1}%
  \ignoreemptyitems%
  \setsepchar[*]{,}%
  \readlist*\ListeRadar{#2}%
  \toklisteradara{}%
  \foreachitem\compteur\in\ListeRadar{\expandafter\UpdateRadara\compteur\nil}%
  \ifboolKV[ClesRadar]{Disciplines}{}{%
    \toklisteradarb{}%
    \foreachitem\compteur\in\ListeRadar{\expandafter\UpdateRadarb\compteur\nil}%
  }%
  \ifboolKV[ClesRadar]{MoyenneClasse}{}{%
    \toklisteradarc{}%
    \foreachitem\compteur\in\ListeRadar{\expandafter\UpdateRadarc\compteur\nil}%
  }%
  \MPRadar{\useKV[ClesRadar]{Rayon}}{\the\toklisteradarb}{\useKV[ClesRadar]{Pas}}{\useKV[ClesRadar]{Reference}}{\the\toklisteradara}{\the\toklisteradarc}%
}

%%%
% Barres de niveaux
%%%
\setKVdefault[ClesBarre]{Niveau=false,LimiteI=25,LimiteF=50,LimiteS=75,TexteOrigine=0,TexteReference=100,CouleurGraduation=white,CouleurFond=gray!50,CouleurBarre=black,Graduation=false,Nom=D\'efaut,Pas=10,CouleurI=red,CouleurF=orange,CouleurS=yellow,CouleurM=green}

\newlength{\barrewidth}

\newcommand\Jauge[2][]{%
  \setlength{\barrewidth}{\linewidth-2\fboxsep}%
  \useKVdefault[ClesBarre]%
  \setKV[ClesBarre]{#1}%
  \xdef\NomComp{\useKV[ClesBarre]{Nom}}%
  \def\TexteOrigine{\useKV[ClesBarre]{TexteOrigine}}%
  \def\TexteReference{\useKV[ClesBarre]{TexteReference}}%
  \xdef\CouleurFond{\useKV[ClesBarre]{CouleurFond}}%
  \xdef\CouleurGrad{\useKV[ClesBarre]{CouleurGraduation}}%
  \xdef\CouleurBarre{\useKV[ClesBarre]{CouleurBarre}}%
  \xdef\CouleurI{\useKV[ClesBarre]{CouleurI}}%
  \xdef\CouleurF{\useKV[ClesBarre]{CouleurF}}%
  \xdef\CouleurS{\useKV[ClesBarre]{CouleurS}}%
  \xdef\CouleurM{\useKV[ClesBarre]{CouleurM}}%
  \ifboolKV[ClesBarre]{Niveau}{%
    \begin{tikzpicture}[rounded corners=2pt,very thin]
      \fill [gray!50] (0,0) rectangle (\barrewidth, 0.15);
      \xintifboolexpr{#2<\useKV[ClesBarre]{LimiteI}}{%
        \fill [\CouleurI] (0,0) rectangle (#2/100*\barrewidth, 0.15);
      }{\xintifboolexpr{#2<\useKV[ClesBarre]{LimiteF}}{%
          \fill [\CouleurF] (0,0) rectangle (#2/100*\barrewidth, 0.15);
        }{\xintifboolexpr{#2<\useKV[ClesBarre]{LimiteS}}{%
            \fill [\CouleurS] (0,0) rectangle (#2/100*\barrewidth, 0.15);
          }{\fill [\CouleurM] (0,0) rectangle (#2/100*\barrewidth, 0.15);}
        }%
      }%
      \node[anchor=south west] at (0,0.5em) {\NomComp};%
      \node[anchor=north] at (0,-0.25em) {\TexteOrigine};
      \node[anchor=north] at (\barrewidth,-0.25em) {\TexteReference};
      \ifboolKV[ClesBarre]{Graduation}{%
        \foreach \s in {1,...,\fpeval{\useKV[ClesBarre]{Pas}-1}}%
        {
          \draw[\CouleurGrad] (\s/\useKV[ClesBarre]{Pas}*\barrewidth,0)--(\s/\useKV[ClesBarre]{Pas}*\barrewidth,0.15);
        }
      }{}
      \foreach \s in {\useKV[ClesBarre]{LimiteI},\useKV[ClesBarre]{LimiteF},\useKV[ClesBarre]{LimiteS}}%
      {
        \draw[black] (\s/100*\barrewidth,-0.1)--(\s/100*\barrewidth,0.2);%
      }
    \end{tikzpicture}%
  }{%
    \begin{tikzpicture}[rounded corners=2pt,very thin]
      \fill [\CouleurFond] (0,0) rectangle (\barrewidth, 0.15);%
      \fill [\CouleurBarre] (0,0) rectangle (#2/100*\barrewidth, 0.15);%
      \node[anchor=south west] at (0,0.5em) {\NomComp};%
      \node[anchor=north] at (0,-0.25em) {\useKV[ClesBarre]{TexteOrigine}};%
      \node[anchor=north] at (\barrewidth,-0.25em) {\useKV[ClesBarre]{TexteReference}};%
      \ifboolKV[ClesBarre]{Graduation}{%
      \foreach \s in {1,...,\fpeval{\useKV[ClesBarre]{Pas}-1}}%
      {
        \draw[\CouleurGrad] (\s/\useKV[ClesBarre]{Pas}*\barrewidth,0)--(\s/\useKV[ClesBarre]{Pas}*\barrewidth,0.15);
      }}{}%
    \end{tikzpicture}%
  }
}

%%%
% Equations
%%%
\setKVdefault[ClesEquation]{Ecart=0.5,Fleches=false,FlecheDiv=false,Laurent=false,Decomposition=false,Terme=false,Composition=false,Symbole=false,Decimal=false,Entier=false,Lettre=x,Solution=false,LettreSol=true,Bloc=false,Simplification=false,CouleurTerme=black,CouleurCompo=black,CouleurSous=red,CouleurSymbole=orange,Verification=false,Nombre=0,Egalite=false,Produit=false,Facteurs=false,Carre=false,Exact=false,Pose=false,Equivalence=false}

\newcommand\rightcomment[4]{%
  \begin{tikzpicture}[remember picture,overlay]
    \draw[Cfleches,-stealth]
    ($({pic cs:#3}|-{pic cs:#1})+(\useKV[ClesEquation]{Ecart},0)$)
    .. controls +(0.2,-0.05) and +(0.2,0.1) ..
    node[right,align=left]{#4}
    ($({pic cs:#3}|-{pic cs:#2})+(\useKV[ClesEquation]{Ecart},0.1)$);
  \end{tikzpicture}%
}%

\newcommand\leftcomment[4]{%
  \begin{tikzpicture}[remember picture,overlay]
    \draw[Cfleches,-stealth]
    ($({pic cs:#3}|-{pic cs:#1})-(\useKV[ClesEquation]{Ecart},0)$)
    .. controls +(-0.2,-0.05) and +(-0.2,0.1) ..
    node[left,align=right]{#4}
    ($({pic cs:#3}|-{pic cs:#2})-(\useKV[ClesEquation]{Ecart},-0.1)$);
  \end{tikzpicture}%
}%

\newcommand\Rightcomment[4]{%
  \begin{tikzpicture}[remember picture,overlay]
    \draw[Cfleches,-stealth]
    ($({pic cs:#3}|-{pic cs:#1})+(\useKV[ClesEquation]{Ecart},0)$)
    .. controls +(0.2,-0.05) and +(0.2,0.1) ..
    node[right,align=left]{#4}
    ($({pic cs:#3}|-{pic cs:#2})+(\useKV[ClesEquation]{Ecart},0.1)$);
  \end{tikzpicture}%
}%
\newcommand\Leftcomment[4]{%
  \begin{tikzpicture}[remember picture,overlay]
    \draw[Cfleches,-stealth]
    ($({pic cs:#3}|-{pic cs:#1})-(\useKV[ClesEquation]{Ecart},0)$)
    .. controls +(-0.2,-0.05) and +(-0.2,0.1) ..
    node[left,align=right]{#4}
    ($({pic cs:#3}|-{pic cs:#2})-(\useKV[ClesEquation]{Ecart},-0.1)$);
  \end{tikzpicture}%
}%

% Pour "oublier" les tikzmarks. En cas de plusieurs utilisations de la macro \ResolEquation
\newcounter{Nbequa}
\setcounter{Nbequa}{0}

%CT
\newdimen\fdashwidth    \fdashwidth  = 0.8pt % \'epaisseur traits
\newdimen\fdashlength   \fdashlength = 0.5mm % longueur des pointill\'es et s\'eparation entre pointill\'es
\newdimen\fdashsep      \fdashsep    = 3pt % s\'eparateur entre contenu et traits

\def\fdash#1{%
  \leavevmode\begingroup%
  \setbox0\hbox{#1}%
  \def\hdash{\vrule height\fdashwidth width\fdashlength\relax}%
  \def\vdash{\hrule height\fdashlength width\fdashwidth\relax}%
  \def\dashblank{\kern\fdashlength}%
  \ifdim\fdashsep>0pt
  \setbox0\hbox{\vrule width0pt height\dimexpr\ht0+\fdashsep depth\dimexpr\dp0+\fdashsep\kern\fdashsep\unhbox0 \kern\fdashsep}%
  \fi
  \edef\hdash{\hbox to\the\wd0{\noexpand\color{Csymbole}\hdash\kern.5\fdashlength\xleaders\hbox{\hdash\dashblank}\hfil\hdash}}%
  \edef\vdash{\vbox to\the\dimexpr\ht0+\dp0+2\fdashwidth{\noexpand\color{Csymbole}\vdash\kern.5\fdashlength\xleaders\vbox{\vdash\dashblank}\vfil\vdash}}%
  \hbox{%
    \vdash
    \vtop{\vbox{\offinterlineskip\hdash\hbox{\unhbox0 }\hdash}}%
    \vdash}%
  \endgroup
}
% fin CT
\def\Fdash#1{\raisebox{-2\fdashsep+\fdashwidth}{\fdash{#1}}}

%Une simplification de a/b est possible ou non ?
\newboolean{Simplification}

\newcommand\SSimpliTest[2]{%
  % Test d'une simplification possible ou pas de #1/#2
  \newcount\numerateur\newcount\denominateur\newcount\valabsnum\newcount\valabsdeno%
  \numerateur=\number#1
  \denominateur=\number#2
  \ifnum\number#1<0
  \valabsnum=\numexpr0-\number#1
  \else
  \valabsnum=\number#1
  \fi
  \ifnum\number#2<0
  \valabsdeno=\numexpr0-\number#2
  \else
  \valabsdeno=\number#2
  \fi
  \ifnum\the\valabsnum=0
    \setboolean{Simplification}{true}
  \else
    \PGCD{\the\valabsnum}{\the\valabsdeno}
    \ifnum\pgcd>1
      \setboolean{Simplification}{true}
    \else
      \ifnum\the\numerateur<0
        \ifnum\the\denominateur<0
          \setboolean{Simplification}{true}
        \else
          \ifnum\valabsdeno=1\relax
            \setboolean{Simplification}{true}
          \else
          \setboolean{Simplification}{false}
          \fi
        \fi
      \else
        \ifnum\valabsdeno=1\relax
          \setboolean{Simplification}{true}
        \else
          \setboolean{Simplification}{false}
        \fi
      \fi
    \fi
  \fi
}

\definecolor{Cfleches}{RGB}{100,100,100}%

\newcommand\AffichageEqua[4]{%
  \def\LETTRE{\useKV[ClesEquation]{Lettre}}%
  \ensuremath{%
    % partie du x
    \xintifboolexpr{#1==0}{}{\xintifboolexpr{#1==1}{}{\xintifboolexpr{#1==-1}{-}{\num{#1}}}\LETTRE}%
    % partie du nombre
    \xintifboolexpr{#2==0}{\xintifboolexpr{#1==0}{0}{}}{\xintifboolexpr{#2>0}{\xintifboolexpr{#1==0}{}{+}\num{#2}}{\num{#2}}}%
    % egal
    =
    % partie du x
    \xintifboolexpr{#3==0}{}{\xintifboolexpr{#3==1}{}{\xintifboolexpr{#3==-1}{-}{\num{#3}}}\LETTRE}%
    % partie du nombre
    \xintifboolexpr{#4==0}{%
      \xintifboolexpr{#3==0}{0}{}
    }{%
      \xintifboolexpr{#4>0}{\xintifboolexpr{#3==0}{}{+}\num{#4}}{\num{#4}}%
    }
  }%
}%

\newcommand\EcrireSolutionEquation[4]{%
  L'équation \AffichageEqua{#1}{#2}{#3}{#4} a une unique solution : \opdiv*{\Coeffb}{\Coeffa}{solution}{resteequa}\opcmp{resteequa}{0}$\ifboolKV[ClesEquation]{LettreSol}{\useKV[ClesEquation]{Lettre}=}{}\displaystyle\ifopeq\opexport{solution}{\solution}\num{\solution}\else\ifboolKV[ClesEquation]{Entier}{\SSimplifie{\Coeffb}{\Coeffa}}{\frac{\num{\Coeffb}}{\num{\Coeffa}}}\fi$.
}%

\input{PfCEquationSoustraction2}%
\input{PfCEquationTerme1}%
\input{PfCEquationComposition2}%
\input{PfCEquationPose1}%
\input{PfCEquationSymbole1}%
\input{PfCEquationLaurent1}

\newcommand\ResolEquation[5][]{%
  \useKVdefault[ClesEquation]%
  \setKV[ClesEquation]{#1}%
  \colorlet{Cterme}{\useKV[ClesEquation]{CouleurTerme}}%
  \colorlet{Ccompo}{\useKV[ClesEquation]{CouleurCompo}}%
  \colorlet{Csymbole}{\useKV[ClesEquation]{CouleurSymbole}}%
  \colorlet{Cdecomp}{\useKV[ClesEquation]{CouleurSous}}%
  \ifboolKV[ClesEquation]{Carre}{%
    \ResolEquationCarre[#1]{#2}%
  }{%
    \ifboolKV[ClesEquation]{Produit}{%
      \ResolEquationProduit[#1]{#2}{#3}{#4}{#5}%
    }{%
      \ifboolKV[ClesEquation]{Verification}{%
        \Verification[#1]{#2}{#3}{#4}{#5}%
      }{%
        \ifboolKV[ClesEquation]{Symbole}{%
          \ResolEquationSymbole[#1]{#2}{#3}{#4}{#5}%
        }{%
          \ifboolKV[ClesEquation]{Laurent}{%
            \ResolEquationLaurent[#1]{#2}{#3}{#4}{#5}%
          }{%
            \ifboolKV[ClesEquation]{Terme}{%
              \ResolEquationTerme[#1]{#2}{#3}{#4}{#5}%
            }{\ifboolKV[ClesEquation]{Composition}{%
                \ResolEquationComposition[#1]{#2}{#3}{#4}{#5}%
              }{\ifboolKV[ClesEquation]{Pose}{%
                  \ResolEquationL[#1]{#2}{#3}{#4}{#5}%
                }{%
                  \ResolEquationSoustraction[#1]{#2}{#3}{#4}{#5}%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\newcommand\ResolEquationCarre[2][]{%
  \setKV[ClesEquation]{#1}%
  \xintifboolexpr{#2<0}{%
    Comme $\num{#2}$ est n\'egatif, alors l'\'equation $\useKV[ClesEquation]{Lettre}^2=\num{#2}$ n'a aucune solution.%
  }{\xintifboolexpr{#2==0}{%
      L'\'equation $\useKV[ClesEquation]{Lettre}^2=0$ a une unique solution : $\useKV[ClesEquation]{Lettre}=0$.%
    }{%
      Comme \num{#2} est positif, alors l'\'equation $\useKV[ClesEquation]{Lettre}^2=\num{#2}$ a deux solutions :%
      \begin{align*}
        \useKV[ClesEquation]{Lettre}&=\sqrt{\num{#2}}&&\text{et}&\useKV[ClesEquation]{Lettre}&=-\sqrt{\num{#2}}%\\
        \ifboolKV[ClesEquation]{Exact}{\\%
        \useKV[ClesEquation]{Lettre}&=\num{\fpeval{sqrt(#2)}}&&\text{et}&\useKV[ClesEquation]{Lettre}&=-\num{\fpeval{sqrt(#2)}}}{}%
      \end{align*}
    }%
  }%
}%

\newcommand\ResolEquationProduit[5][]{%
  \setKV[ClesEquation]{#1}%
  \ifboolKV[ClesEquation]{Equivalence}{}{C'est un produit nul donc \ifboolKV[ClesEquation]{Facteurs}{l'un au
      moins des facteurs est nul}{} :}%
  \ifboolKV[ClesEquation]{Equivalence}{%
          \[\Distri{#2}{#3}{#4}{#5}=0\]
    \begin{align*}%
      &\makebox[0pt]{$\Longleftrightarrow$}&\xintifboolexpr{#3==0}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}}}&=0&\quad&\makebox[0pt]{ou}\quad&\xintifboolexpr{#5==0}{\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}}{\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#5>0}{+\num{#5}}{-\num{\fpeval{0-#5}}}}&=0\\
      &\makebox[0pt]{$\Longleftrightarrow$}&\xintifboolexpr{#3==0}{\xdef\Coeffa{1}\xdef\Coeffb{\fpeval{0-#3}}\xintifboolexpr{#2==1}{&}{\useKV[ClesEquation]{Lettre}&=0}}{\xdef\Coeffa{#2}\xdef\Coeffb{\fpeval{0-#3}}\xintifboolexpr{\Coeffa==1}{}{\num{\Coeffa}}\useKV[ClesEquation]{Lettre}&=\num{\Coeffb}}&&&\xintifboolexpr{#5==0}{\xdef\Coeffc{1}\xdef\Coeffd{\fpeval{0-#5}}\xintifboolexpr{#4==1}{&}{\useKV[ClesEquation]{Lettre}&=0}}{\xdef\Coeffc{#4}\xdef\Coeffd{\fpeval{0-#5}}\xintifboolexpr{\Coeffc==1}{}{\num{\Coeffc}}\useKV[ClesEquation]{Lettre}&=\num{\Coeffd}}%\\
      \xintifboolexpr{\Coeffa==1 'and' \Coeffc==1}{}{\\%\ifnum\cmtd>1
      &\makebox[0pt]{$\Longleftrightarrow$}&\xintifboolexpr{\Coeffa==1}{&}{\useKV[ClesEquation]{Lettre}&=\frac{\num{\Coeffb}}{\num{\Coeffa}}}\xintifboolexpr{\Coeffc==1}{}{&&&\useKV[ClesEquation]{Lettre}&=\frac{\num{\Coeffd}}{\num{\Coeffc}}}
      % accolade%\\
      %%%% 
      \ifboolKV[ClesEquation]{Entier}{%
      \xdef\TSimp{}%
      \SSimpliTest{\Coeffb}{\Coeffa}\ifthenelse{\boolean{Simplification}}{\xintifboolexpr{#3==0}{\xdef\TSimp{0}}{\xdef\TSimp{1}}}{\xdef\TSimp{0}}
      \SSimpliTest{\Coeffd}{\Coeffc}\ifthenelse{\boolean{Simplification}}{\xintifboolexpr{#5==0}{}{\xdef\TSimp{\fpeval{\TSimp+1}}}}{}
      \xintifboolexpr{\TSimp==0}{}{\\
      \ifboolKV[ClesEquation]{Simplification}{%
      &\makebox[0pt]{$\Longleftrightarrow$}&\SSimpliTest{\Coeffb}{\Coeffa}\xintifboolexpr{\Coeffa==1}{&}{\ifthenelse{\boolean{Simplification}}{\useKV[ClesEquation]{Lettre}&=\SSimplifie{\Coeffb}{\Coeffa}}{&}%\\
      }
      }{}
      &&&\ifboolKV[ClesEquation]{Simplification}{%
      \SSimpliTest{\Coeffd}{\Coeffc}%
          \xintifboolexpr{\Coeffc==1}{}{\ifthenelse{\boolean{Simplification}}{\useKV[ClesEquation]{Lettre}&=\SSimplifie{\Coeffd}{\Coeffc}}{}%\\
      }
      }{}
      }
      }{}
      }
    \end{align*}
  }{%
    \begin{align*}
    \xintifboolexpr{#3==0}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}}}&=0&&\text{ou}&\xintifboolexpr{#5==0}{\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}}{\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#5>0}{+\num{#5}}{-\num{\fpeval{0-#5}}}}&=0\\
    \xintifboolexpr{#3==0}{\xdef\Coeffa{1}\xdef\Coeffb{\fpeval{0-#3}}\xintifboolexpr{#2==1}{&}{\useKV[ClesEquation]{Lettre}&=0}}{\xdef\Coeffa{#2}\xdef\Coeffb{\fpeval{0-#3}}\xintifboolexpr{\Coeffa==1}{}{\num{\Coeffa}}\useKV[ClesEquation]{Lettre}&=\num{\Coeffb}}&&&\xintifboolexpr{#5==0}{\xdef\Coeffc{1}\xdef\Coeffd{\fpeval{0-#5}}\xintifboolexpr{#4==1}{&}{\useKV[ClesEquation]{Lettre}&=0}}{\xdef\Coeffc{#4}\xdef\Coeffd{\fpeval{0-#5}}\xintifboolexpr{\Coeffc==1}{}{\num{\Coeffc}}\useKV[ClesEquation]{Lettre}&=\num{\Coeffd}}%\\
      \xintifboolexpr{\Coeffa==1 'and' \Coeffc==1}{}{\\%\ifnum\cmtd>1
      \xintifboolexpr{\Coeffa==1}{&}{\useKV[ClesEquation]{Lettre}&=\frac{\num{\Coeffb}}{\num{\Coeffa}}}\xintifboolexpr{\Coeffc==1}{}{&&&\useKV[ClesEquation]{Lettre}&=\frac{\num{\Coeffd}}{\num{\Coeffc}}}
       %accolade%\\
      %%%%   
      \ifboolKV[ClesEquation]{Entier}{%
      \xdef\TSimp{}
      \SSimpliTest{\Coeffb}{\Coeffa}\ifthenelse{\boolean{Simplification}}{\xintifboolexpr{#3==0}{\xdef\TSimp{0}}{\xdef\TSimp{1}}}{\xdef\TSimp{0}}
      \SSimpliTest{\Coeffd}{\Coeffc}\ifthenelse{\boolean{Simplification}}{\xintifboolexpr{#5==0}{}{\xdef\TSimp{\fpeval{\TSimp+1}}}}{}
      \xintifboolexpr{\TSimp==0}{}{\\
      \ifboolKV[ClesEquation]{Simplification}{%
      \SSimpliTest{\Coeffb}{\Coeffa}
      \xintifboolexpr{\Coeffa==1}{&}{\ifthenelse{\boolean{Simplification}}{\useKV[ClesEquation]{Lettre}&=\SSimplifie{\Coeffb}{\Coeffa}}{&}%\\
      }
      }{}
      &&&\ifboolKV[ClesEquation]{Simplification}{%
      \SSimpliTest{\Coeffd}{\Coeffc}%
          \xintifboolexpr{\Coeffc==1}{}{\ifthenelse{\boolean{Simplification}}{\useKV[ClesEquation]{Lettre}&=\SSimplifie{\Coeffd}{\Coeffc}}{}%\\
      }
      }{}
      }
      }{}
      }
    \end{align*}
  }%
  \ifboolKV[ClesEquation]{Solution}{L'\'equation $\xintifboolexpr{#3==0}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}}{(\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}})}\xintifboolexpr{#5==0}{\times\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}}{(\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#5>0}{+\num{#5}}{-\num{\fpeval{0-#5}}})}=0$ a deux solutions : \opdiv*{\Coeffb}{\Coeffa}{solution}{resteequa}\opcmp{resteequa}{0}$\ifboolKV[ClesEquation]{LettreSol}{\useKV[ClesEquation]{Lettre}=}{}\displaystyle\ifopeq\opexport{solution}{\solution}\num{\solution}\else\ifboolKV[ClesEquation]{Entier}{\SSimplifie{\Coeffb}{\Coeffa}}{\frac{\num{\Coeffb}}{\num{\Coeffa}}}\fi$ et \opdiv*{\Coeffd}{\Coeffc}{solution}{resteequa}\opcmp{resteequa}{0}$\ifboolKV[ClesEquation]{LettreSol}{\useKV[ClesEquation]{Lettre}=}{}\displaystyle\ifopeq\opexport{solution}{\solution}\num{\solution}\else\ifboolKV[ClesEquation]{Entier}{\SSimplifie{\Coeffd}{\Coeffc}}{\frac{\num{\Coeffd}}{\num{\Coeffc}}}\fi$.
  }{}%
}

\newcommand\Verification[5][]{%
  \setKV[ClesEquation]{#1}%
  \xdef\ValeurTest{\useKV[ClesEquation]{Nombre}}%
  Testons la valeur $\useKV[ClesEquation]{Lettre}=\num{\ValeurTest}$ :%
  \begin{align*}
    \xintifboolexpr{#2==0}{\num{#3}}{\num{#2}\times\xintifboolexpr{\ValeurTest<0}{(\num{\ValeurTest})}{\num{\ValeurTest}}\xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+\num{#3}}{\num{#3}}}}&&\xintifboolexpr{#4==0}{\num{#5}}{\num{#4}\times\xintifboolexpr{\ValeurTest<0}{(\num{\ValeurTest})}{\num{\ValeurTest}}\xintifboolexpr{#5==0}{}{\xintifboolexpr{#5>0}{+\num{#5}}{\num{#5}}}}\\
    \xintifboolexpr{#2==0}{}{\num{\fpeval{#2*\useKV[ClesEquation]{Nombre}}}\xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+\num{#3}}{\num{#3}}}}&&\xintifboolexpr{#4==0}{}{\num{\fpeval{#4*\useKV[ClesEquation]{Nombre}}}\xintifboolexpr{#5==0}{}{\xintifboolexpr{#5>0}{+\num{#5}}{\num{#5}}}}\\
    \xintifboolexpr{#2==0}{}{\num{\fpeval{#2*\useKV[ClesEquation]{Nombre}+#3}}}&&\xintifboolexpr{#4==0}{}{\num{\fpeval{#4*\useKV[ClesEquation]{Nombre}+#5}}}
  \end{align*}
  \xdef\Testa{\fpeval{#2*\useKV[ClesEquation]{Nombre}+#3}}\xdef\Testb{\fpeval{#4*\useKV[ClesEquation]{Nombre}+#5}}%
  \ifboolKV[ClesEquation]{Egalite}{%
    Comme \xintifboolexpr{\Testa==\Testb}{$\num{\Testa}=\num{\Testb}$}{$\num{\Testa}\not=\num{\Testb}$}, alors l'\'egalit\'e $\xintifboolexpr{#2==0}{\num{#3}}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}}}}=\xintifboolexpr{#4==0}{\num{#5}}{\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#5==0}{}{\xintifboolexpr{#5>0}{+\num{#5}}{-\num{\fpeval{0-#5}}}}}$ \xintifboolexpr{\Testa==\Testb}{ est v\'erifi\'ee }{ n'est pas v\'erifi\'ee } pour $\useKV[ClesEquation]{Lettre}=\num{\useKV[ClesEquation]{Nombre}}$.%
  }{\xintifboolexpr{\Testa==\Testb}{Comme $\num{\Testa}=\num{\Testb}$, alors $\useKV[ClesEquation]{Lettre}=\num{\useKV[ClesEquation]{Nombre}}$ est bien }{Comme $\num{\Testa}\not=\num{\Testb}$, alors $\useKV[ClesEquation]{Lettre}=\num{\useKV[ClesEquation]{Nombre}}$ n'est pas }une solution de l'\'equation $\xintifboolexpr{#2==0}{\num{#3}}{\xintifboolexpr{#2==1}{}{\num{#2}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}}}}=\xintifboolexpr{#4==0}{\num{#5}}{\xintifboolexpr{#4==1}{}{\num{#4}}\useKV[ClesEquation]{Lettre}\xintifboolexpr{#5==0}{}{\xintifboolexpr{#5>0}{+\num{#5}}{-\num{\fpeval{0-#5}}}}}$.}%
}%

%%%
% Proportionnalit\'e
%%%
\setKVdefault[ClesPropor]{GrandeurA=Grandeur A,GrandeurB=Grandeur B,Largeur=1cm,Math=false,Stretch=1,ColorFill=white,CouleurTab=gray!15,Vertical=false}%

\def\Updatetoksmath#1/#2\nil{\addtotok\tabtoksa{&#1}\addtotok\tabtoksb{&#2}}%
\def\updatetokspropor#1/#2\nil{\addtotok\tabtoksa{&\num{#1}}\addtotok\tabtoksb{&\num{#2}}}
\def\Buildtabpropor{%
  \setcounter{NbProporG}{0}%
  \setcounter{NbProporD}{0}%
  \renewcommand{\arraystretch}{\useKV[ClesPropor]{Stretch}}%
  \ifboolKV[ClesPropor]{Vertical}{%
    \begin{tabular}{c|*{2}{>{\centering\arraybackslash}p{\useKV[ClesPropor]{Largeur}}|}c}%
      \multicolumn{1}{c}{}&\multicolumn{1}{c}{\setcounter{NbPropor}{1}\TikzPH}&\multicolumn{1}{c}{\TikzPH}&\\
      \hhline{~--~}%
      &\cellcolor{\useKV[ClesPropor]{CouleurTab}}\useKV[ClesPropor]{GrandeurA}&\cellcolor{\useKV[ClesPropor]{CouleurTab}}\useKV[ClesPropor]{GrandeurB}&\\
      \hhline{~--~}%
      \xintFor* ##1 in {\xintSeq{1}{\fpeval{\ListeValeurlen}}}\do{%
      \stepcounter{NbProporG}\TikzPG&\ifboolKV[ClesPropor]{Math}{\ListeValeur[##1,1]}{\num{\ListeValeur[##1,1]}}&\ifboolKV[ClesPropor]{Math}{\ListeValeur[##1,2]}{\num{\ListeValeur[##1,2]}}&\stepcounter{NbProporD}\TikzPD\\
      \hhline{~--~}%
      }%
     \multicolumn{1}{c}{}&\multicolumn{1}{c}{\setcounter{NbPropor}{1}\TikzPB}&\multicolumn{1}{c}{\TikzPB}&\\
    \end{tabular}%
  }{%
    \tabtoksa{}\tabtoksb{}%
    \tabtoksa{\cellcolor{\useKV[ClesPropor]{CouleurTab}}\useKV[ClesPropor]{GrandeurA}}\tabtoksb{\cellcolor{\useKV[ClesPropor]{CouleurTab}}\useKV[ClesPropor]{GrandeurB}}%
    \ifboolKV[ClesPropor]{Math}{%
      \foreachitem\compteur\in\ListeValeur{\expandafter\Updatetoksmath\compteur\nil}%
    }{\foreachitem\compteur\in\ListeValeur{\expandafter\updatetokspropor\compteur\nil}%
    }%
    \xdef\LongListe{\ListeValeurlen}%
    \begin{tabular}{rc|*{\number\numexpr\ListeValeurlen}{>{\centering\arraybackslash}p{\useKV[ClesPropor]{Largeur}}|}l}%
      \multicolumn{1}{c}{}&\multicolumn{1}{c}{}\setcounter{NbPropor}{1}\xintFor* ##1 in {\xintSeq {1}{\ListeValeurlen}}\do{&\multicolumn{1}{c}{\TikzPH}}&\multicolumn{1}{c}{}\\%
      \hhline{~*{\number\numexpr\ListeValeurlen+1}{-}~}%
      \multicolumn{1}{c|}{\stepcounter{NbProporG}\TikzPG}&\the\tabtoksa&\multicolumn{1}{c}{\stepcounter{NbProporD}\TikzPD}\\%
      \hhline{~*{\number\numexpr\ListeValeurlen+1}{-}~}%
      \multicolumn{1}{c|}{\stepcounter{NbProporG}\TikzPG}&\the\tabtoksb&\multicolumn{1}{c}{\stepcounter{NbProporD}\TikzPD}\\%
      \hhline{~*{\number\numexpr\ListeValeurlen+1}{-}~}%
      \multicolumn{1}{c}{\stepcounter{NbProporG}\TikzPG}&\multicolumn{1}{c}{}\setcounter{NbPropor}{1}\xintFor* ##1 in {\xintSeq {1}{\ListeValeurlen}}\do{&\multicolumn{1}{c}{\TikzPB}}&\multicolumn{1}{c}{}\\%
    \end{tabular}%
  }%
  \renewcommand{\arraystretch}{1}%
}%

\newcounter{NbPropor}%

\newcommand\TikzPH{%
  \tikz[remember picture,overlay]{%
    \coordinate[name=ProporH-\theNbPropor,yshift=-\getstrut\dp*\arraystretch];}%
  \stepcounter{NbPropor}%
}%

\newcommand\TikzPB{%
  \tikz[remember picture, overlay]{%
    \coordinate[name=ProporB-\theNbPropor,yshift=\getstrut\ht*\arraystretch];}%
  \stepcounter{NbPropor}%
}%

\newcommand\TikzPG{%
  \tikz[remember picture,overlay]{%
    \coordinate[name=ProporG-\theNbProporG,xshift=\tabcolsep+\arrayrulewidth,yshift=\getstrut\dp];}%
}%
\newcommand\TikzPD{%
  \tikz[remember picture,overlay]{%
    \coordinate[name=ProporD-\theNbProporD,xshift=-\tabcolsep-\arrayrulewidth,yshift=\getstrut\dp];}%
}%

\newcommand\TikzPHD{%
  \setbox1=\hbox{\useKV[ClesPropor]{GrandeurA}}%
  \setbox2=\hbox{\useKV[ClesPropor]{GrandeurB}}%
  \xintifboolexpr{\wd1>\wd2}{%
    \tikz[remember picture,overlay]{%
      \coordinate[name=ProporHD,xshift=-0.5\wd1,yshift=-\getstrut\dp*\arraystretch];}%
  }{%
    \tikz[remember picture,overlay]{%
      \coordinate[name=ProporHD,xshift=-0.5\wd2,yshift=-\getstrut\dp*\arraystretch];}%
  }
}%

\newcommand\TikzPBD{%
  \setbox1=\hbox{\useKV[ClesPropor]{GrandeurA}}%
  \setbox2=\hbox{\useKV[ClesPropor]{GrandeurB}}%
  \xintifboolexpr{\wd1>\wd2}{%
    \tikz[remember picture, overlay]{%
      \coordinate[name=ProporBD,xshift=-0.5*\the\wd1,yshift=\getstrut\ht*\arraystretch];}%
  }{%
    \tikz[remember picture, overlay]{%
      \coordinate[name=ProporBD,xshift=-0.5*\the\wd2,yshift=\getstrut\ht*\arraystretch];}%
  }
  \stepcounter{NbPropor}%
}%
%
\newcommand\FlechesPH[3]{%
  \begin{tikzpicture}[remember picture,overlay]%
    \ifnum#1<#2\relax%
    \draw[-stealth,out=50,in=130] (ProporH-#1) to node[inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5, sloped]{#3}(ProporH-#2);%
  \else%
    \draw[-stealth,out=130,in=50] (ProporH-#1) to node[inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5, sloped]{#3}(ProporH-#2);%
    \fi%
  \end{tikzpicture}%
}%
%
\newcommand\FlechesPB[3]{%
  \ifnum\number#1<\number#2\relax%
  \begin{tikzpicture}[remember picture,overlay]%
    \draw[-stealth,out=-50,in=-130] (ProporB-#1) to node[inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5, sloped]{#3}(ProporB-#2);%
  \end{tikzpicture}%
  \else%
  \begin{tikzpicture}[remember picture,overlay]%
    \draw[-stealth,out=-130,in=-50] (ProporB-#1) to node[inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5, sloped]{#3}(ProporB-#2);%
  \end{tikzpicture}%
  \fi%
}%
%
\newcommand\FlechesPG[3]{%
  \begin{tikzpicture}[remember picture,overlay]%
    \ifnum#1<#2\relax%
    \draw[-stealth,out=-150,in=150] (ProporG-#1) to node[transform canvas={xshift=-1pt},inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5,left]{#3}(ProporG-#2);%
    \else%
    \draw[-stealth,out=150,in=-150] (ProporG-#1) to node[transform canvas={xshift=-1pt},inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5, left]{#3}(ProporG-#2);%
    \fi%
  \end{tikzpicture}%
}%

\newcommand\FlechesPD[3]{%
  \begin{tikzpicture}[remember picture,overlay]%
    \ifnum#1<#2\relax%
    \draw[-stealth,out=-30,in=30] (ProporD-#1) to node[transform canvas={xshift=1pt},inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5,right]{#3}(ProporD-#2);%
    \else%
    \draw[-stealth,out=30,in=-30] (ProporD-#1) to node[transform canvas={xshift=1pt},inner sep=0pt, inner xsep=1pt,fill=\colorfill, pos=0.5,right]{#3}(ProporD-#2);%
    \fi%
  \end{tikzpicture}%
}%

\newcommand\FlecheLineaireG[4]{%
  \begin{tikzpicture}[remember picture,overlay,node distance=1em]%
    \node[inner sep=0pt] (MilieuH) at ($(ProporG-#1)!0.5!(ProporG-#2)$) {};%
    \node[circle,draw,inner sep=0pt] [left of=MilieuH] (aux) {#4} ;%
    \coordinate[left of=aux] (aux1);%
    \draw[-stealth] (ProporG-#1) -| (aux);%
    \draw[-stealth] (ProporG-#2) -| (aux);%
    \draw[-stealth] (aux) -- (aux1) |- (ProporG-#3);%
  \end{tikzpicture}%
}%

\newcommand\FlecheLineaireD[4]{%
  \begin{tikzpicture}[remember picture,overlay,node distance=1em]%
    \node[inner sep=0pt] (MilieuH) at ($(ProporD-#1)!0.5!(ProporD-#2)$) {};%
    \node[circle,draw,inner sep=0pt] [right of=MilieuH] (aux) {#4} ;%
    \coordinate[right of=aux] (aux1);%
    \draw[-stealth] (ProporD-#1) -| (aux);%
    \draw[-stealth] (ProporD-#2) -| (aux);%
    \draw[-stealth] (aux) -- (aux1) |- (ProporD-#3);%
  \end{tikzpicture}%
}%

\newcounter{NbProporG}%
\newcounter{NbProporD}%

\newcommand\Propor[2][]{%
  \useKVdefault[ClesPropor]%
  \setKV[ClesPropor]{#1}%
  \xdef\colorfill{\useKV[ClesPropor]{ColorFill}}%
  \xdef\EcartLargeur{\useKV[ClesPropor]{Largeur}}%
  %  % on lit la liste \'ecrite sous la forme valeur/effectif
  \setsepchar[*]{,*/}\ignoreemptyitems%
  \readlist*\ListeValeur{#2}%
  \Buildtabpropor%
}%

\newcommand\FlecheCoef[2][\EcartLargeur]{%
  \begin{tikzpicture}[remember picture, overlay]%
    \node[] (Point1) at ($(ProporH-\LongListe)!0.1!(ProporB-\LongListe)$) {};%
    \node[] (Point2) at ($(ProporH-\LongListe)!0.9!(ProporB-\LongListe)$) {};%
    \coordinate[right of=Point1,node distance=0.5*#1+\tabcolsep] (point1);%
    \coordinate[right of=Point2,node distance=0.5*#1+\tabcolsep] (point2);%
    \draw[-stealth,out=-20,in=20] (point1) to node[midway,right,inner sep=1pt]{#2}(point2);%
  \end{tikzpicture}%
}%

\newcommand\FlecheCoefDebut[2][\tabcolsep+\arrayrulewidth]{%
  \begin{tikzpicture}[remember picture, overlay]%
    \node[] (Noeud1) at ($(ProporHD)!0.1!(ProporBD)$) {};%
    \node[] (Noeud2) at ($(ProporHD)!0.9!(ProporBD)$) {};%
    \coordinate[left of=Noeud1,node distance=#1] (noeud1);%
    \coordinate[left of=Noeud2,node distance=#1] (noeud2);%
    \draw[-stealth,out=160,in=-160] (noeud2) to node[midway,left,inner sep=1pt]{#2}(noeud1);%
  \end{tikzpicture}%
}%

\newcommand\FlecheCoefInv[2][1cm]{%
  \begin{tikzpicture}[remember picture, overlay]%
    \node[] (Point1) at ($(ProporH-\LongListe)!0.1!(ProporB-\LongListe)$) {};%
    \node[] (Point2) at ($(ProporH-\LongListe)!0.9!(ProporB-\LongListe)$) {};%
    \coordinate[right of=Point1,node distance=0.5*#1+\tabcolsep] (point1);%
    \coordinate[right of=Point2,node distance=0.5*#1+\tabcolsep] (point2);%
    \draw[-stealth,out=20,in=-20] (point2) to node[midway,right,inner sep=1pt]{#2}(point1);%
  \end{tikzpicture}%
}%

\newcommand\FlecheLineaireH[4]{%
  \begin{tikzpicture}[remember picture,overlay,node distance=\getstrut\ht]%
    \node[inner sep=0pt] (MilieuH) at ($(ProporH-#1)!0.5!(ProporH-#2)$) {};%
    \node[circle,draw,inner sep=0pt] [above of=MilieuH] (aux) {#4} ;%
    \coordinate[above of=aux] (aux1);%
    \draw[-stealth] (ProporH-#1) |- (aux);%
    \draw[-stealth] (ProporH-#2) |- (aux);%
    \draw[-stealth] (aux) -- (aux1) -| (ProporH-#3);%
  \end{tikzpicture}%
}%

\newcommand\FlecheLineaireB[4]{%
  \begin{tikzpicture}[remember picture,overlay,node distance=3mm]%
    \node[inner sep=0pt] (MilieuB) at ($(ProporB-#1)!0.5!(ProporB-#2)$) {};%
    \node[circle,draw,inner sep=0pt] [below of=MilieuB] (aux) {#4};%
    \coordinate[below of=aux,node distance=3mm] (aux1);%
    \draw[-stealth] (ProporB-#1) |- (aux);%
    \draw[-stealth] (ProporB-#2) |- (aux);%
    \draw[-stealth] (aux) -- (aux1) -| (ProporB-#3);%
  \end{tikzpicture}%
}%

%%%
% Application : pourcentage
%%%
\setKVdefault[ClesPourcentage]{Appliquer,Calculer=false,Augmenter=false,Reduire=false,Fractionnaire=false,Decimal,Formule=false,Unite=g,Concret=false,GrandeurA=Grandeur A,GrandeurB=Total,Largeur=1cm,MotReduction=diminution,AideTableau=false,ColorFill=white,CouleurTab=gray!15}
  
\newcommand\Pourcentage[3][]{%
  \useKVdefault[ClesPourcentage]%
  \setKV[ClesPourcentage]{#1}%
  \ifboolKV[ClesPourcentage]{Reduire}{%
    \ifboolKV[ClesPourcentage]{Formule}{%
        R\'eduire une quantit\'e de \num{#2}~\%, cela revient \`a multiplier cette quantit\'e par $1-\dfrac{\num{#2}}{100}$. Par cons\'equent, si on r\'eduit \num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{} de \num{#2}~\%, cela donne :
        \[\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\times\left(1-\frac{\num{#2}}{100}\right)=\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\times(1-\num{\fpeval{#2/100}})=\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\times\num{\fpeval{(1-#2/100)}}=\num{\fpeval{#3*(1-#2/100)}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\]
      }{%
        Calculons ce que repr\'esente la \useKV[ClesPourcentage]{MotReduction} de \num{#2}~\%.
        \ifboolKV[ClesPourcentage]{AideTableau}{%
          \xdef\NomA{\useKV[ClesPourcentage]{GrandeurA}}%
          \xdef\NomB{\useKV[ClesPourcentage]{GrandeurB}}%
          \xdef\NomCouleurTab{\useKV[ClesPourcentage]{CouleurTab}}%
          \xdef\NomLargeurTab{\useKV[ClesPourcentage]{Largeur}}%
          \begin{center}
            \Propor[Math,GrandeurA=\NomA,GrandeurB=\NomB,CouleurTab=\NomCouleurTab,Largeur=\NomLargeurTab]{/\num{#3},\num{#2}/100}
          \end{center}
          \FlecheCoefInv{\tiny$\times\num{\fpeval{#2/100}}$}%
          On obtient une \useKV[ClesPourcentage]{MotReduction} de $\num{\fpeval{#2/100}}\times\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\num{\fpeval{#3*#2/100}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}. Donc un total de $\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}-\num{\fpeval{#3*#2/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\num{\fpeval{#3*(1-#2/100)}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.%
        }{Pour calculer \num{#2}~\% de \num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}, on effectue le calcul :
        \[\ifboolKV[ClesPourcentage]{Fractionnaire}{\frac{\num{#2}}{100}}{\num{\fpeval{#2/100}}}\times\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\ifboolKV[ClesPourcentage]{Fractionnaire}{\frac{\num{\fpeval{#2*#3}}}{100}}{\num{\fpeval{#2*#3/100}}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\ifboolKV[ClesPourcentage]{Fractionnaire}{=\num{\fpeval{#2*#3/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}}{}\]%
       On obtient une \useKV[ClesPourcentage]{MotReduction} de $\num{\fpeval{#3*#2/100}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.\\Donc un total de $\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}-\num{\fpeval{#3*#2/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\num{\fpeval{#3*(1-#2/100)}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.}
      }
  }{%
    \ifboolKV[ClesPourcentage]{Augmenter}{%
      \ifboolKV[ClesPourcentage]{Formule}{%
        Augmenter de \num{#2}~\% une quantit\'e, cela revient \`a multiplier cette quantit\'e par $1+\dfrac{\num{#2}}{100}$. Par cons\'equent, si on augmente \num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{} de \num{#2}~\%, cela donne :
        \[\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\times\left(1+\frac{\num{#2}}{100}\right)=\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\times(1+\num{\fpeval{#2/100}})=\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\times\num{\fpeval{(1+#2/100)}}=\num{\fpeval{#3*(1+#2/100)}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\]
      }{%
        Calculons ce que repr\'esente l'augmentation de \num{#2}~\%. %
        \ifboolKV[ClesPourcentage]{AideTableau}{%
          \xdef\NomA{\useKV[ClesPourcentage]{GrandeurA}}%
          \xdef\NomB{\useKV[ClesPourcentage]{GrandeurB}}%
          \xdef\NomCouleurTab{\useKV[ClesPourcentage]{CouleurTab}}%
          \xdef\NomLargeurTab{\useKV[ClesPourcentage]{Largeur}}%
          \begin{center}%
            \Propor[Math,GrandeurA=\NomA,GrandeurB=\NomB,CouleurTab=\NomCouleurTab,Largeur=\NomLargeurTab]{/\num{#3},\num{#2}/100}%
          \end{center}%
          \FlecheCoefInv{\tiny$\times\num{\fpeval{#2/100}}$}%
          On obtient une augmentation de $\num{\fpeval{#2/100}}\times\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\num{\fpeval{#3*#2/100}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.\\Donc un total de $\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}+\num{\fpeval{#3*#2/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\num{\fpeval{#3*(1+#2/100)}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.%
        }{Pour calculer \num{#2}~\% de \num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}, on effectue le calcul :
          \[\ifboolKV[ClesPourcentage]{Fractionnaire}{\frac{\num{#2}}{100}}{\num{\fpeval{#2/100}}}\times\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\ifboolKV[ClesPourcentage]{Fractionnaire}{\frac{\num{\fpeval{#2*#3}}}{100}}{\num{\fpeval{#2*#3/100}}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\ifboolKV[ClesPourcentage]{Fractionnaire}{=\num{\fpeval{#2*#3/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}}{}\]%
          On obtient une augmentation de $\num{\fpeval{#3*#2/100}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.\\Donc un total de $\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}+\num{\fpeval{#3*#2/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\num{\fpeval{#3*(1+#2/100)}}$\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}.}
      }
    }{%
      \ifboolKV[ClesPourcentage]{Calculer}{%
        \xdef\NomA{\useKV[ClesPourcentage]{GrandeurA}}%
        \xdef\NomB{\useKV[ClesPourcentage]{GrandeurB}}%
        \xdef\NomCouleurTab{\useKV[ClesPourcentage]{CouleurTab}}%
        \xdef\NomLargeurTab{\useKV[ClesPourcentage]{Largeur}}%
        \Propor[Math,GrandeurA=\NomA,GrandeurB=\NomB,CouleurTab=\NomCouleurTab,Largeur=\NomLargeurTab]{\num{#2}/\num{#3},/100}%
        \xdef\colorfill{\useKV[ClesPourcentage]{ColorFill}}%
        \FlechesPB{2}{1}{\scriptsize$\times\num{\fpeval{#3/100}}$}%
        \FlechesPH{1}{2}{\scriptsize$\div\num{\fpeval{#3/100}}$}%
        \xdef\ResultatPourcentage{\fpeval{#2*100/#3}}%
      }{%
        Pour calculer \num{#2}~\% de \num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\useKV[ClesPourcentage]{Unite}}{}, on effectue le calcul :%
        \[\ifboolKV[ClesPourcentage]{Fractionnaire}{\frac{\num{#2}}{100}}{\num{\fpeval{#2/100}}}\times\num{#3}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}=\ifboolKV[ClesPourcentage]{Fractionnaire}{\frac{\num{\fpeval{#2*#3}}}{100}}{\num{\fpeval{#2*#3/100}}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}\ifboolKV[ClesPourcentage]{Fractionnaire}{=\num{\fpeval{#2*#3/100}}\ifboolKV[ClesPourcentage]{Concret}{~\text{\useKV[ClesPourcentage]{Unite}}}{}}{}\]%
      }%
    }%
  }%
}%

%%%
% Lien : ratio
%%%
\setKVdefault[ClesRatio]{FigureCours=false,Figure=false,Longueur=5cm,TexteTotal=quantit\'e,TextePart=part,Tableau=false,GrandeurA=Grandeur A,GrandeurB=Part(s),Largeur=1cm,Stretch=1,Nom=false,CouleurUn=gris,CouleurDeux=0.5gris+0.5blanc,CouleurTrois=white,CouleurTab=gray!15}

\newcommand\MPTest[9][]{%
  % #2 : Longueur de la barre unit\'e
  % #3 : premier nombre
  % #4 : deuxi\`eme nombre
  % #5 : troisi\`eme nombre
  % #6 : ne sert à rien. Laissé en attente.
  % #7 \`a #9: Couleurs de remplissage
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    vardef RatioTrois(expr long)(text t)=%longueur de la barre / quantit\'e \`a partager / textepart :) / t le ratio
    pair A,B,C,D;
    A=u*(1,1);
    B-A=(long,0);
    C-B=u*(0,0.5);
    D-C=A-B;
    n:=0;%n pour savoir si le ratio est a:b ou a:b:c
    numeric N[];%Pour sauvegarder les \'el\'ements du ratio
    for p_=t:
    n:=n+1;
    N[n]=p_;
    endfor;
    % on fait la somme totale "du ratio"
    somme=0;
    somme:=somme for k=1 upto n:+N[k] endfor;
    %Figure(0,0,long+2u,3u);
    remplis polygone(A,(N[1]/somme)[A,B],(N[1]/somme)[D,C],D)
    withcolor #7;
    remplis polygone(B,(N[1]/somme)[A,B],(N[1]/somme)[D,C],C)
    withcolor #8;
    if n>2:
    remplis
    polygone((N[1]/somme)[A,B],((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],(N[1]/somme)[D,C])
    withcolor #8;
    remplis
    polygone(B,((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],C)
    withcolor #9;
    fi;
    drawoptions(withpen pencircle scaled1.5bp);
    draw polygone(A,B,C,D);
    for k=1 upto somme-1:
    draw segment((k/somme)[A,B],(k/somme)[D,C]);
    endfor;
    drawoptions();
    % accolades
    labeloffset:=labeloffset/2;
    label.top(TEX("\footnotesize$\overbrace{\hbox
      to"&decimal(abs(A-B))&"pt{}}$"),iso(D,C));
    labeloffset:=labeloffset*2;
    label.bot(TEX("\footnotesize$\underbrace{\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-A))&"pt{}}$"),iso(A,(N[1]/somme)[A,B]));
    label.bot(TEX("\footnotesize$\underbrace{\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-((N[1]+N[2])/somme)[A,B]))&"pt{}}$"),iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    if n>2:
    label.bot(TEX("\footnotesize$\underbrace{\hbox
      to"&decimal(abs(((N[1]+N[2])/somme)[A,B]-B))&"pt{}}$"),iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
    enddef;
    RatioTrois(#2)(#3,#4,#5);
    %etiquettage
    labeloffset:=labeloffset*3;
    label.top(btex \useKV[ClesRatio]{TexteTotal} etex,iso(D,C));
    if #3>1:
    label.bot(btex #3~\useKV[ClesRatio]{TextePart}s
    etex,iso(A,(N[1]/somme)[A,B]));
    else:
    label.bot(btex #3~\useKV[ClesRatio]{TextePart} etex,iso(A,(N[1]/somme)[A,B]));
    fi;
    if #4>1:
    label.bot(btex #4~\useKV[ClesRatio]{TextePart}s etex,iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    else:
    label.bot(btex #4~\useKV[ClesRatio]{TextePart}
    etex,iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    fi;
    if n>2:
    if #5>1:
    label.bot(btex #5~\useKV[ClesRatio]{TextePart}s etex,iso(B,((N[1]+N[2])/somme)[A,B]));
    else:
    label.bot(btex #5~\useKV[ClesRatio]{TextePart} etex,iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
    fi;
  \end{mplibcode}
  \else
  \mpxcommands{%
    \usepackage{ProfCollege}
    \setKVdefault[ClesRatio]{TexteTotal=quantit\'e,TextePart=part}
    \setKV[ClesRatio]{#1}
  }
  \begin{mpost}
    vardef RatioTrois(expr long)(text t)=%longueur de la barre / quantit\'e \`a partager / textepart :) / t le ratio
    pair A,B,C,D;
    A=u*(1,1);
    B-A=(long,0);
    C-B=u*(0,0.5);
    D-C=A-B;
    n:=0;%n pour savoir si le ratio est a:b ou a:b:c
    numeric N[];%Pour sauvegarder les \'el\'ements du ratio
    for p_=t:
    n:=n+1;
    N[n]=p_;
    endfor;
    % on fait la somme totale "du ratio"
    somme=0;
    somme:=somme for k=1 upto n:+N[k] endfor;
    Figure(0,0,long+2u,3u);
    remplis polygone(A,(N[1]/somme)[A,B],(N[1]/somme)[D,C],D)
    withcolor #7;
    remplis polygone(B,(N[1]/somme)[A,B],(N[1]/somme)[D,C],C)
    withcolor #8;
    if n>2:
    remplis
    polygone((N[1]/somme)[A,B],((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],(N[1]/somme)[D,C])
    withcolor #8;
    remplis
    polygone(B,((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],C)
    withcolor #9;
    fi;
    drawoptions(withpen pencircle scaled1.5bp);
    draw polygone(A,B,C,D);
    for k=1 upto somme-1:
    draw segment((k/somme)[A,B],(k/somme)[D,C]);
    endfor;
    drawoptions();
    %accolades
    label.top(LATEX("\noexpand\footnotesize$\noexpand\overbrace{\noexpand\hbox
      to"&decimal(abs(A-B))&"pt{}}$"),iso(D,C));
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\underbrace{\noexpand\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-A))&"pt{}}$"),iso(A,(N[1]/somme)[A,B]));
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\underbrace{\noexpand\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-((N[1]+N[2])/somme)[A,B]))&"pt{}}$"),iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    if n>2:
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\underbrace{\noexpand\hbox
      to"&decimal(abs(((N[1]+N[2])/somme)[A,B]-B))&"pt{}}$"),iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
    enddef;
    RatioTrois(#2)(#3,#4,#5);
    %etiquettage
    labeloffset:=labeloffset*3;
    label.top(\btex \useKV[ClesRatio]{TexteTotal} etex,iso(D,C));
    if #3>1:
    label.bot(btex #3\unexpanded{~\useKV[ClesRatio]{TextePart}}s etex,iso(A,(N[1]/somme)[A,B]));
    else:
    label.bot(btex #3\unexpanded{~\useKV[ClesRatio]{TextePart}} etex,iso(A,(N[1]/somme)[A,B]));
    fi;
    if #4>1:
    label.bot(btex #4\unexpanded{~\useKV[ClesRatio]{TextePart}}s etex,iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    else:
    label.bot(btex #4\unexpanded{~\useKV[ClesRatio]{TextePart}} etex,iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    fi;
    if n>2:
    if #5>1:
    label.bot(btex #5\unexpanded{~\useKV[ClesRatio]{TextePart}}s etex,iso(B,((N[1]+N[2])/somme)[A,B]));
    else:
    label.bot(btex #5\unexpanded{~\useKV[ClesRatio]{TextePart}} etex,iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
    fi;
  \end{mpost}
  \fi
}%

\newcommand\MPTestCours[9][]{%
  % #2 : Longueur de la barre unit\'e
  % #3 : premier nombre
  % #4 : deuxi\`eme nombre
  % #5 : troisi\`eme nombre
  % #6 : Valeurs du ratio
  % #7 \`a #9: Couleurs de remplissage
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    vardef RatioTrois(expr long)(text t)=%longueur de la barre / quantit\'e \`a partager / textepart :) / t le ratio
    pair A,B,C,D;
    A=u*(1,1);
    B-A=(long,0);
    C-B=u*(0,0.5);
    D-C=A-B;
    n:=0;%n pour savoir si le ratio est a:b ou a:b:c
    numeric N[];%Pour sauvegarder les \'el\'ements du ratio
    for p_=t:
    n:=n+1;
    N[n]=p_;
    endfor;
    % on fait la somme totale "du ratio"
    somme=0;
    somme:=somme for k=1 upto n:+N[k] endfor;
    %%Figure(0,0,long+2u,3u);
    remplis polygone(A,(N[1]/somme)[A,B],(N[1]/somme)[D,C],D)
    withcolor #7;
    remplis polygone(B,(N[1]/somme)[A,B],(N[1]/somme)[D,C],C)
    withcolor #8;
    if n>2:
    remplis
    polygone((N[1]/somme)[A,B],((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],(N[1]/somme)[D,C])
    withcolor #8;
    remplis
    polygone(B,((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],C)
    withcolor #9;
    fi;
    drawoptions(withpen pencircle scaled1.5bp);
    draw polygone(A,B,C,D);
    for k=1 upto somme-1:
    draw segment((k/somme)[A,B],(k/somme)[D,C]);
    endfor;
    drawoptions();
    % accolades
    label.bot(TEX("\footnotesize$\underbrace{\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-A))&"pt{}}$"),iso(A,(N[1]/somme)[A,B]));
    label.bot(TEX("\footnotesize$\underbrace{\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-((N[1]+N[2])/somme)[A,B]))&"pt{}}$"),iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    if n>2:
    label.bot(TEX("\footnotesize$\underbrace{\hbox
      to"&decimal(abs(((N[1]+N[2])/somme)[A,B]-B))&"pt{}}$"),iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
    enddef;
    RatioTrois(#2)(#3,#4,#5);
    %etiquettage
    labeloffset:=labeloffset*3;
    label.bot(btex $a$ etex,iso(A,(N[1]/somme)[A,B]));
    label.bot(btex $b$ etex,iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    if n>2:
    label.bot(btex $c$ etex,iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}
    vardef RatioTrois(expr long)(text t)=%longueur de la barre / quantit\'e \`a partager / textepart :) / t le ratio
    pair A,B,C,D;
    A=u*(1,1);
    B-A=(long,0);
    C-B=u*(0,0.5);
    D-C=A-B;
    n:=0;%n pour savoir si le ratio est a:b ou a:b:c
    numeric N[];%Pour sauvegarder les \'el\'ements du ratio
    for p_=t:
    n:=n+1;
    N[n]=p_;
    endfor;
    % on fait la somme totale "du ratio"
    somme=0;
    somme:=somme for k=1 upto n:+N[k] endfor;
    %Figure(0,0,long+2u,3u);
    remplis polygone(A,(N[1]/somme)[A,B],(N[1]/somme)[D,C],D)
    withcolor #7;
    remplis polygone(B,(N[1]/somme)[A,B],(N[1]/somme)[D,C],C)
    withcolor #8;
    if n>2:
    remplis
    polygone((N[1]/somme)[A,B],((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],(N[1]/somme)[D,C])
    withcolor #8;
    remplis
    polygone(B,((N[1]+N[2])/somme)[A,B],((N[1]+N[2])/somme)[D,C],C)
    withcolor #9;
    fi;
    drawoptions(withpen pencircle scaled1.5bp);
    draw polygone(A,B,C,D);
    for k=1 upto somme-1:
    draw segment((k/somme)[A,B],(k/somme)[D,C]);
    endfor;
    drawoptions();
    % accolades
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\underbrace{\noexpand\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-A))&"pt{}}$"),iso(A,(N[1]/somme)[A,B]));
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\underbrace{\noexpand\hbox
      to"&decimal(abs((N[1]/somme)[A,B]-((N[1]+N[2])/somme)[A,B]))&"pt{}}$"),iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    if n>2:
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\underbrace{\noexpand\hbox
      to"&decimal(abs(((N[1]+N[2])/somme)[A,B]-B))&"pt{}}$"),iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
    enddef;
    RatioTrois(#2)(#3,#4,#5);
    %etiquettage
    labeloffset:=labeloffset*3;
    label.bot(btex $a$ etex,iso(A,(N[1]/somme)[A,B]));
    label.bot(btex $b$ etex,iso(((N[1]+N[2])/somme)[A,B],(N[1]/somme)[A,B]));
    if n>2:
    label.bot(btex $c$ etex,iso(B,((N[1]+N[2])/somme)[A,B]));
    fi;
  \end{mpost}
  \fi
}

\newtoks\toklisteratio
\def\UpdateRatio#1\nil{\addtotok\toklisteratio{#1,}}

\def\updateratiotoks#1/#2/#3\nil{\addtotok\tabtoksa{&\ifx\bla#2\bla\else\num{#2}\fi}\addtotok\tabtoksb{&\ifx\bla#3\bla\else\num{#3}\fi}\addtotok\tabtoksc{&#1}}

\def\buildtabratio{%
  \tabtoksa{}\tabtoksb{}\tabtoksc{}%
  \tabtoksa{\useKV[ClesRatio]{GrandeurA}}\tabtoksb{\useKV[ClesRatio]{GrandeurB}}
  \foreachitem\compteur\in\ListeRatio{\expandafter\updateratiotoks\compteur\nil}%
  \xdef\LongListe{\ListeRatiolen}%
  \renewcommand{\arraystretch}{\useKV[ClesRatio]{Stretch}}%
  \begin{tabular}{|>{\columncolor{\useKV[ClesRatio]{CouleurTab}}}c|*{\number\numexpr\ListeRatiolen}{>{\centering\arraybackslash}p{\useKV[ClesRatio]{Largeur}}|}l}
    \ifboolKV[ClesRatio]{Nom}{%
    \hhline{~*{\number\numexpr\ListeRatiolen}{-}}
    \multicolumn{1}{c|}{}\the\tabtoksc\\
    }{}
    \hhline{*{\number\numexpr\ListeRatiolen+1}{-}}%
    \the\tabtoksa&\setcounter{NbPropor}{1}\TikzRH\\%
    \hhline{*{\number\numexpr\ListeRatiolen+1}{-}}%
    \the\tabtoksb&\setcounter{NbPropor}{1}\TikzRB\\%
    \hhline{*{\number\numexpr\ListeRatiolen+1}{-}}%
  \end{tabular}%
}%

\newcommand\TikzRH{%
   \tikz[remember picture,overlay]{%
   \coordinate[name=ProporH-\theNbPropor,yshift=\getstrut\ht*\arraystretch];}%
   \stepcounter{NbPropor}%
 }%

 \newcommand\TikzRB{%
   \tikz[remember picture, overlay]{%
     \coordinate[name=ProporB-\theNbPropor,yshift=-\getstrut\dp*\arraystretch];}%
   \stepcounter{NbPropor}%
 }%
 
\newcommand\FlecheRatio[2][\EcartLargeur]{%
  \begin{tikzpicture}[remember picture, overlay]%
    \node[] (Point1) at ($(ProporH-1)!0.1!(ProporB-1)$) {};%
    \node[] (Point2) at ($(ProporH-1)!0.9!(ProporB-1)$) {};%
    \coordinate[right of=Point1,node distance=0*#1-\tabcolsep] (point1);%
    \coordinate[right of=Point2,node distance=0*#1-\tabcolsep] (point2);%
    \draw[-stealth,out=-20,in=20] (point1) to node[midway,right,inner sep=1pt]{#2}(point2);%
\end{tikzpicture}%
}%

\newcommand\FlecheInvRatio[2][\EcartLargeur]{%
  \begin{tikzpicture}[remember picture, overlay]%
    \node[] (Point1) at ($(ProporH-1)!0.1!(ProporB-1)$) {};%
    \node[] (Point2) at ($(ProporH-1)!0.9!(ProporB-1)$) {};%
    \coordinate[right of=Point1,node distance=0*#1-\tabcolsep] (point1);%
    \coordinate[right of=Point2,node distance=0*#1-\tabcolsep] (point2);%
    \draw[-stealth,out=20,in=-20] (point2) to node[midway,right,inner sep=1pt]{#2}(point1);%
\end{tikzpicture}%
}%

\newcommand\Ratio[2][]{%
  \useKVdefault[ClesRatio]%
  \setKV[ClesRatio]{#1}%
  \xdef\EcartLargeur{\useKV[ClesRatio]{Largeur}}%
  \ifboolKV[ClesRatio]{FigureCours}{%
    \setsepchar{,}\ignoreemptyitems%
    \readlist*\ListeRatio{#2}%
    \toklisteratio{}%
    \foreachitem\compteur\in\ListeRatio{\expandafter\UpdateRatio\compteur\nil}%
    \itemtomacro\ListeRatio[1]\NbUn%
    \itemtomacro\ListeRatio[2]\NbDeux%
    \xintifboolexpr{\ListeRatiolen>2}{\itemtomacro\ListeRatio[3]\NbTrois}{\xdef\NbTrois{}}%
    \MPTestCours[#1]{\useKV[ClesRatio]{Longueur}}{\NbUn}{\NbDeux}{\NbTrois}{\the\toklisteratio}{\useKV[ClesRatio]{CouleurUn}}{\useKV[ClesRatio]{CouleurDeux}}{\useKV[ClesRatio]{CouleurTrois}}%
  }{%
    \ifboolKV[ClesRatio]{Figure}{%
      \setsepchar{,}\ignoreemptyitems%
      \readlist*\ListeRatio{#2}%
      \toklisteratio{}%
      \foreachitem\compteur\in\ListeRatio{\expandafter\UpdateRatio\compteur\nil}%
      \itemtomacro\ListeRatio[1]\NbUn%
      \itemtomacro\ListeRatio[2]\NbDeux%
      \xintifboolexpr{\ListeRatiolen>2}{\itemtomacro\ListeRatio[3]\NbTrois}{\xdef\NbTrois{}}%
      \MPTest[#1]{\useKV[ClesRatio]{Longueur}}{\NbUn}{\NbDeux}{\NbTrois}{\the\toklisteratio}{\useKV[ClesRatio]{CouleurUn}}{\useKV[ClesRatio]{CouleurDeux}}{\useKV[ClesRatio]{CouleurTrois}}%
    }{%
      \ifboolKV[ClesRatio]{Tableau}{%
        \setsepchar[*]{,*/}\ignoreemptyitems%
        \readlist*\ListeRatio{#2}%
        \buildtabratio%
      }{}%
    }%
  }%
}%
%%% 
% Cartes Mentales
%%%
\setKVdefault[ClesMentales]{Nom={Bulle}, Largeur=5cm, Ancre={0,0},Pointilles=false,CTrace=black,CFond=white,Epaisseur=1pt,Rayon=1}%
\newenvironment{Mind}{\begin{tikzpicture}}{\end{tikzpicture}}%

\newlength{\RoundedBoxWidth}%

\NewEnviron{Bulle}[1][]{%
  \setKV[ClesMentales]{#1}%
  \setlength{\RoundedBoxWidth}{\useKV[ClesMentales]{Largeur}}%
  \xdef\Pointilles{\ifboolKV[ClesMentales]{Pointilles}{dashed}{}}%
  \xdef\CouleurTrace{\useKV[ClesMentales]{CTrace}}%
  \xdef\CouleurFond{\useKV[ClesMentales]{CFond}}%
  \xdef\EpaisseurLigne{\useKV[ClesMentales]{Epaisseur}}%
  \xdef\RayonCoin{\useKV[ClesMentales]{Rayon}}%
  \node(\useKV[ClesMentales]{Nom}) [align=justify,draw=\CouleurTrace,line width=\EpaisseurLigne,\Pointilles,fill=\CouleurFond,rounded corners=\RayonCoin,text width=\RoundedBoxWidth] at (\useKV[ClesMentales]{Ancre}) {\begin{minipage}{\RoundedBoxWidth}\BODY\end{minipage}};%
  \multido{\i=1+1}{9}{%
    \xdef\x{\fpeval{\i/10}}
    \coordinate (\useKV[ClesMentales]{Nom}-H-\i) at ($(\useKV[ClesMentales]{Nom}.north west)!\x!(\useKV[ClesMentales]{Nom}.north east)$);
    \coordinate (\useKV[ClesMentales]{Nom}-D-\i) at ($(\useKV[ClesMentales]{Nom}.north east)!\x!(\useKV[ClesMentales]{Nom}.south east)$);
    \coordinate (\useKV[ClesMentales]{Nom}-B-\i) at ($(\useKV[ClesMentales]{Nom}.south east)!\x!(\useKV[ClesMentales]{Nom}.south west)$);
    \coordinate (\useKV[ClesMentales]{Nom}-G-\i) at ($(\useKV[ClesMentales]{Nom}.south west)!\x!(\useKV[ClesMentales]{Nom}.north west)$);
  }
}

%%%
% Ppt\'es des droites (6eme)
%%%
\setKVdefault[ClesDroites]{Brouillon=false,CitePropriete=false,Num=1,Figure=false,Remediation=false}

\newcommand\Redaction[4][]{%
  \ifboolKV[ClesDroites]{Remediation}{%
    \xintifboolexpr{\useKV[ClesDroites]{Num}==1}{%
      \ifboolKV[ClesDroites]{CitePropriete}{%
        Les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles. Les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles.%
        
        Or, si deux droites sont parall\`eles, alors toute droite parall\`ele \`a l'une est parall\`ele \`a l'autre.%
        
        Donc les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles.%
      }{%
        Comme les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont toutes les deux parall\`eles \`a la m\^eme droite $(\hbox to2em{\dotfill})$, alors les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles.%
      }
    }{\xintifboolexpr{\useKV[ClesDroites]{Num}==2}{%
        \ifboolKV[ClesDroites]{CitePropriete}{%
          Les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont perpendiculaires. Les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont perpendiculaires.%
          
          Or, si deux droites sont perpendiculaires \`a une m\^eme droite, alors elles sont parall\`eles.%
          
          Donc les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont perpendiculaires.
        }{%
          Comme les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont toutes les deux perpendiculaires \`a la m\^eme droite $(\hbox to2em{\dotfill})$, alors les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles.
        }
      }{%
        \ifboolKV[ClesDroites]{CitePropriete}{%
          Les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles. Les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont perpendiculaires.%
          
          Or, si deux droites sont parall\`eles, alors toute droite droite perpendiculaire \`a l'une est perpendiculaire \`a l'autre.%
          
          Donc les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont perpendiculaires.
        }{%
          Comme les droites $(\hbox to2em{\dotfill})$ et $(\hbox to2em{\dotfill})$ sont parall\`eles, alors la droite $(\hbox to2em{\dotfill})$ qui est perpendiculaire \`a $(\hbox to2em{\dotfill})$ est \'egalement perpendiculaire \`a la droite $(\hbox to2em{\dotfill})$.
        }
      }
    }%
  }{%
    \xintifboolexpr{\useKV[ClesDroites]{Num}==1}{%
      \ifboolKV[ClesDroites]{CitePropriete}{%
        Les droites $(#2)$ et $(#4)$ sont parall\`eles. Les droites $(#3)$ et $(#4)$ sont parall\`eles.%
        
        Or, si deux droites sont parall\`eles, alors toute droite parall\`ele \`a l'une est parall\`ele \`a l'autre.%
        
        Donc les droites $(#2)$ et $(#3)$ sont parall\`eles.
      }{%
        Comme les droites $(#2)$ et $(#3)$ sont toutes les deux parall\`eles \`a la m\^eme droite $(#4)$, alors les droites $(#2)$ et $(#3)$ sont parall\`eles.
      }
    }{\xintifboolexpr{\useKV[ClesDroites]{Num}==2}{%
        \ifboolKV[ClesDroites]{CitePropriete}{%
          Les droites $(#2)$ et $(#4)$ sont perpendiculaires. Les droites $(#3)$ et $(#4)$ sont perpendiculaires.%
          
          Or, si deux droites sont perpendiculaires \`a une m\^eme droite, alors elles sont parall\`eles.%
          
          Donc les droites $(#2)$ et $(#3)$ sont perpendiculaires.
        }{%
          Comme les droites $(#2)$ et $(#3)$ sont toutes les deux perpendiculaires \`a la m\^eme droite $(#4)$, alors les droites $(#2)$ et $(#3)$ sont parall\`eles.
        }
      }{%
        \ifboolKV[ClesDroites]{CitePropriete}{%
          Les droites $(#2)$ et $(#4)$ sont parall\`eles. Les droites $(#3)$ et $(#4)$ sont perpendiculaires.%
          
          Or, si deux droites sont parall\`eles, alors toute droite droite perpendiculaire \`a l'une est perpendiculaire \`a l'autre.%
          
          Donc les droites $(#2)$ et $(#3)$ sont perpendiculaires.
        }{%
          Comme les droites $(#2)$ et $(#4)$ sont parall\`eles, alors la droite $(#3)$ qui est perpendiculaire \`a $(#4)$ est \'egalement perpendiculaire \`a la droite $(#2)$.
        }%
      }%
    }%
  }%
}%

\newcommand\Brouillon[4][]{%
  \setlength{\abovedisplayskip}{0pt}
  \ifboolKV[ClesDroites]{Remediation}{%
    \xintifboolexpr{\useKV[ClesDroites]{Num}==1}{%
      \[\left.
          \begin{array}{l}
            (\hbox to2em{\dotfill})//(\hbox to2em{\dotfill})\\
            \\
            (\hbox to2em{\dotfill})//(\hbox to2em{\dotfill})
          \end{array}
        \right\}(\hbox to2em{\dotfill})//(\hbox to2em{\dotfill})
      \]
    }{\xintifboolexpr{\useKV[ClesDroites]{Num}==2}{%
        \[\left.
            \begin{array}{l}
              (\hbox to2em{\dotfill})\perp(\hbox to2em{\dotfill})\\
              \\
              (\hbox to2em{\dotfill})\perp(\hbox to2em{\dotfill})\\
            \end{array}
          \right\}(\hbox to2em{\dotfill})//(\hbox to2em{\dotfill})
        \]
      }{%
        \[\left.
            \begin{array}{l}
              (\hbox to2em{\dotfill})//(\hbox to2em{\dotfill})\\
              \\
              (\hbox to2em{\dotfill})\perp(\hbox to2em{\dotfill})\\
            \end{array}
          \right\}(\hbox to2em{\dotfill})\perp(\hbox to2em{\dotfill})
        \]
      }
    }
  }{
    \xintifboolexpr{\useKV[ClesDroites]{Num}==1}{%
      \[\left.
          \begin{array}{l}
            (#2)//(#4)\\
            \\
            (#3)//(#4)
          \end{array}
        \right\}(#2)//(#3)
      \]
    }{\xintifboolexpr{\useKV[ClesDroites]{Num}==2}{%
        \[\left.
            \begin{array}{l}
              (#2)\perp(#4)\\
              \\
              (#3)\perp(#4)\\
            \end{array}
          \right\}(#2)//(#3)
        \]
      }{%
        \[\left.
            \begin{array}{l}
              (#2)//(#4)\\
              \\
              (#3)\perp(#4)\\
            \end{array}
          \right\}(#2)\perp(#3)
        \]
      }%
    }%
  }%
}%

\def\MPFigureDroite#1#2{%
  \ifluatex
  %\mplibcodeinherit{enable}
  \mplibforcehmode
  \begin{mplibcode}
    pair A,B,C,D,E,F,G,H,I,J,K;
    u:=7.5mm;
    A=u*(1,3);
    B-A=u*(3,2);
    C-A=u*(2,-1);
    E-C=u*(1,-1.5);
    G-E=u*(1.5,0);
    I-A=whatever*(B-A);
    I-G=whatever*((B-A) rotated 90);
    D-B=C-A;
    F-D=E-C;
    H=1.1[G,I];
    J=(C--D) intersectionpoint (G--H);
    K=(E--F) intersectionpoint (G--H);
    path Codeperp[];
    pair M[];
    M1-I=7*unitvector(B-I);
    M3-I=7*unitvector(J-I);
    M2-M3=M1-I;
    Codeperp1=M1--M2--M3;
    Codeperp2=Codeperp1 shifted(J-I);
    picture Codepara[];
    pair R,S,T;
    path cd;
    Codepara1=image(
    R=1/3[A,B];
    T=1/3[E,F];
    S=1/3[R,T];
    cd=(fullcircle scaled 6mm) shifted S;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((R{dir(210+angle(R-T))}..{dir(150+angle(R-T))}S) cutafter cd);
    drawarrow reverse((T{dir(210+angle(T-R))}..{dir(150+angle(T-R))}S) cutafter cd);
    draw cd;
    label(btex $//$ etex ,S);
    drawoptions();
    );
    Codepara2=image(
    R:=1/2[C,D];
    T:=1/2[E,F];
    S:=1/2[R,T];
    cd:=(fullcircle scaled 6mm) shifted S;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((R{dir(210+angle(R-T))}..{dir(150+angle(R-T))}S) cutafter cd);
    drawarrow reverse((T{dir(210+angle(T-R))}..{dir(150+angle(T-R))}S) cutafter cd);
    draw cd;
    label(btex $//$ etex ,S);
    drawoptions();
    );
    path d[];
    d1=A--B;
    d2=C--D;
    d3=E--F;
    d4=G--H;
    picture reste;
    reste=image(
    %trac\'es des droites
    draw d1;
    if #1=2:
    draw d2;
    elseif #1=3:
    draw d3;
    fi;
    if #2=3:
    draw d3;
    elseif #2=4:
    draw d4;
    fi;
    % trac\'es des codes
    if (#1=2) and (#2=3):
    draw Codepara1; draw Codepara2;
    fi;
    if (#1=2) and (#2=4):
    draw Codeperp1; draw Codeperp2;
    fi;
    if (#1=3) and (#2=4):
    draw Codepara1; draw Codeperp1;
    fi;
    );
    reste:=reste rotatedabout(u*(3,3),-90+uniformdeviate(180));
    draw reste;
  \end{mplibcode}
  %\mplibcodeinherit{disable}
  \else
  \begin{mpost}
    pair A,B,C,D,E,F,G,H,I,J,K;
    u:=7.5mm;
    A=u*(1,3);
    B-A=u*(3,2);
    C-A=u*(2,-1);
    E-C=u*(1,-1.5);
    G-E=u*(1.5,0);
    I-A=whatever*(B-A);
    I-G=whatever*((B-A) rotated 90);
    D-B=C-A;
    F-D=E-C;
    H=1.1[G,I];
    J=(C--D) intersectionpoint (G--H);
    K=(E--F) intersectionpoint (G--H);
    path Codeperp[];
    pair M[];
    M1-I=7*unitvector(B-I);
    M3-I=7*unitvector(J-I);
    M2-M3=M1-I;
    Codeperp1=M1--M2--M3;
    Codeperp2=Codeperp1 shifted(J-I);
    picture Codepara[];
    pair R,S,T;
    path cd;
    Codepara1=image(
    R=1/3[A,B];
    T=1/3[E,F];
    S=1/3[R,T];
    cd=(fullcircle scaled 6mm) shifted S;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((R{dir(210+angle(R-T))}..{dir(150+angle(R-T))}S) cutafter cd);
    drawarrow reverse((T{dir(210+angle(T-R))}..{dir(150+angle(T-R))}S) cutafter cd);
    draw cd;
    label(btex $//$ etex ,S);
    drawoptions();
    );
    Codepara2=image(
    R:=1/2[C,D];
    T:=1/2[E,F];
    S:=1/2[R,T];
    cd:=(fullcircle scaled 6mm) shifted S;
    drawoptions(withcolor 0.75*white);
    drawarrow reverse((R{dir(210+angle(R-T))}..{dir(150+angle(R-T))}S) cutafter cd);
    drawarrow reverse((T{dir(210+angle(T-R))}..{dir(150+angle(T-R))}S) cutafter cd);
    draw cd;
    label(btex $//$ etex ,S);
    drawoptions();
    );
    path d[];
    d1=A--B;
    d2=C--D;
    d3=E--F;
    d4=G--H;
    picture reste;
    reste=image(
    %trac\'es des droites
    draw d1;
    if #1=2:
    draw d2;
    elseif #1=3:
    draw d3;
    fi;
    if #2=3:
    draw d3;
    elseif #2=4:
    draw d4;
    fi;
    % trac\'es des codes
    if (#1=2) and (#2=3):
    draw Codepara1; draw Codepara2;
    fi;
    if (#1=2) and (#2=4):
    draw Codeperp1; draw Codeperp2;
    fi;
    if (#1=3) and (#2=4):
    draw Codepara1; draw Codeperp1;
    fi;
    );
    reste:=reste rotatedabout(u*(3,3),-90+uniformdeviate(180));
    draw reste;
  \end{mpost}
  \fi
}

\newcommand\FaireFigure[4][]{%
  \setlength{\abovedisplayskip}{0pt}
  \xintifboolexpr{\useKV[ClesDroites]{Num}==1}{%
    \MPFigureDroite{2}{3}%
  }{\xintifboolexpr{\useKV[ClesDroites]{Num}==2}{%
      \MPFigureDroite{2}{4}%
    }{%
      \MPFigureDroite{3}{4}%
    }%
  }%
}%

\newcommand\ProprieteDroites[4][]{%
  \useKVdefault[ClesDroites]%
  \setKV[ClesDroites]{#1}%
  \ifboolKV[ClesDroites]{Figure}{%
    \begin{multicols}{2}%
      \begin{center}%
        \FaireFigure[#1]{#2}{#3}{#4}%
      \end{center}%
      \columnbreak
      \ifboolKV[ClesDroites]{Brouillon}{\Brouillon[#1]{#2}{#3}{#4}}{}%
      \Redaction[#1]{#2}{#3}{#4}%
      \par%
    \end{multicols}
  }{%
      \ifboolKV[ClesDroites]{Brouillon}{\Brouillon[#1]{#2}{#3}{#4}}{}%
      \Redaction[#1]{#2}{#3}{#4}%
  }%
}%

%%%
% Fonction Affine
%%%
\setKVdefault[ClesAffine]{Nom=f,Variable=x,Ligne=false,Image=false,Antecedent=false,Graphique=false,Retrouve=false,ProgCalcul=false,Unitex=1,Unitey=1,VoirCoef=false,ACoef=0,Redaction=false,Ecriture=false,Definition=false}%ACoefficient=false%: inutile ?

\newcommand\FonctionAffine[5][]{%
  % #1 nombre ou abscisse premier point
  % #2 a ou ordonn\'ee premier point
  % #3 b ou abscisse deuxi\`eme point
  % #4 {} ou ordonn\'ee deuxi\`eme point
  \useKVdefault[ClesAffine]%A supprimer car appel r\'ecursif avec Redaction
  \setKV[ClesAffine]{#1}%
  \ifboolKV[ClesAffine]{Image}{%
    \ifboolKV[ClesAffine]{Ligne}{%
      \ensuremath{\useKV[ClesAffine]{Nom}(\num{#2})=\num{#3}\times\xintifboolexpr{#2<0}{(\num{#2})}{\num{#2}}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{-\num{\fpeval{0-#4}}}}=\num{\fpeval{#2*#3}}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{-\num{\fpeval{0-#4}}}}\xintifboolexpr{#4==0}{}{=\num{\fpeval{#2*#3+#4}}}}%
    }{%
      \ifboolKV[ClesAffine]{ProgCalcul}{%
        \begin{align*}
          \useKV[ClesAffine]{Nom}&:\useKV[ClesAffine]{Variable}\stackrel{\times\xintifboolexpr{#3<0}{(\num{#3})}{\num{#3}}}{\longrightarrow}\num{#3}\useKV[ClesAffine]{Variable}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{\stackrel{+\num{#4}}{\longrightarrow}}{\stackrel{\num{#4}}{\longrightarrow}}\num{#3}\useKV[ClesAffine]{Variable}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{\num{#4}}}}\\
          \useKV[ClesAffine]{Nom}&:\num{#2}\stackrel{\times\xintifboolexpr{#3<0}{(\num{#3})}{\num{#3}}}{\longrightarrow}\num{\fpeval{#3*#2}}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{\stackrel{+\num{#4}}{\longrightarrow}}{\stackrel{\num{#4}}{\longrightarrow}}\num{\fpeval{#3*#2+#4}}}
        \end{align*}    
      }{%
        \begin{align*}
          \useKV[ClesAffine]{Nom}(\num{#2})&=\num{#3}\times\xintifboolexpr{#2<0}{(\num{#2})}{\num{#2}}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{-\num{\fpeval{0-#4}}}}\\
          \useKV[ClesAffine]{Nom}(\num{#2})&=\num{\fpeval{#3*#2}}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{-\num{\fpeval{0-#4}}}}%\\
          \xintifboolexpr{#4==0}{}{\\
          \useKV[ClesAffine]{Nom}(\num{#2})&=\num{\fpeval{#3*#2+#4}}%\\
          }
        \end{align*}
      }%
    }%
  }{\ifboolKV[ClesAffine]{Antecedent}{%
      \ifboolKV[ClesAffine]{ProgCalcul}{%
        La fonction affine $\useKV[ClesAffine]{Nom}$ est d\'efinie par :
        \begin{align*}
          \useKV[ClesAffine]{Nom}&:\useKV[ClesAffine]{Variable}\stackrel{\times\xintifboolexpr{#3<0}{(\num{#3})}{\num{#3}}}{\longrightarrow}\num{#3}\useKV[ClesAffine]{Variable}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{\stackrel{+\num{#4}}{\longrightarrow}}{\stackrel{\num{#4}}{\longrightarrow}}\num{#3}\useKV[ClesAffine]{Variable}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{\num{#4}}}}
        \end{align*}
        Nous cherchons le nombre $\useKV[ClesAffine]{Variable}$ tel que son image par la fonction $\useKV[ClesAffine]{Nom}$ soit $\num{#2}$. Donc on obtient :
        \begin{align*}
          \useKV[ClesAffine]{Nom}&:\frac{\num{\fpeval{#2-#4}}}{\num{#3}}\stackrel{\div\xintifboolexpr{#3<0}{(\num{#3})}{\num{#3}}}{\longleftarrow}\num{\fpeval{#2-#4}}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{\stackrel{-\num{#4}}{\longleftarrow}}{\stackrel{+\num{\fpeval{0-#4}}}{\longleftarrow}}\num{#2}}
        \end{align*}    
      }{%
        On cherche l'ant\'ec\'edent de $\num{#2}$ par la fonction
        $\useKV[ClesAffine]{Nom}$, c'est-\`a-dire le nombre
        $\useKV[ClesAffine]{Variable}$ tel que
        $\useKV[ClesAffine]{Nom}(\useKV[ClesAffine]{Variable})=\num{#2}$. Or,
        la fonction $\useKV[ClesAffine]{Nom}$ est d\'efinie par : \[%
          \useKV[ClesAffine]{Nom}(\useKV[ClesAffine]{Variable})=\xintifboolexpr{#3==0}{}{\num{#3}\useKV[ClesAffine]{Variable}}\xintifboolexpr{#3==0}{\num{#4}}{\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{-\num{\fpeval{0-#4}}}}}
        \]
        Par cons\'equent, on a :
        \begin{align*}
            \num{#3}\useKV[ClesAffine]{Variable}\xintifboolexpr{#4==0}{}{\xintifboolexpr{#4>0}{+\num{#4}}{-\num{\fpeval{0-#4}}}}&=\num{#2}\\
          \xintifboolexpr{#4==0}{\useKV[ClesAffine]{Variable}\uppercase{&}=\frac{\num{#2}}{\num{#3}}%\\
          }{\num{#3}\useKV[ClesAffine]{Variable}&=\num{\fpeval{#2-#4}}\\
          \useKV[ClesAffine]{Variable}&=\frac{\num{\fpeval{#2-#4}}}{\num{#3}}%\\
          }
        \end{align*}
      }%
    }{%
      \ifboolKV[ClesAffine]{Retrouve}{%
        On sait que $\useKV[ClesAffine]{Nom}$ est une fonction affine. Donc elle s'\'ecrit sous la forme : \[\useKV[ClesAffine]{Nom}(\useKV[ClesAffine]{Variable})=a\useKV[ClesAffine]{Variable}+b\]
        Or, $\useKV[ClesAffine]{Nom}(\num{#2})=\num{#3}$ et $\useKV[ClesAffine]{Nom}(\num{#4})=\num{#5}$. Par cons\'equent, d'apr\`es la propri\'et\'e des accroissements :
        \begin{align*}
          a&=\frac{\useKV[ClesAffine]{Nom}(\num{#2})-\useKV[ClesAffine]{Nom}(\num{#4})}{\num{#2}-\xintifboolexpr{#4<0}{(\num{#4})}{\num{#4}}}\\
          a&=\frac{\num{#3}-\xintifboolexpr{#5<0}{(\num{#5})}{\num{#5}}}{\num{\fpeval{#2-#4}}}\\
          a&=\frac{\num{\fpeval{#3-#5}}}{\num{\fpeval{#2-#4}}}%\\
          \SSimpliTest{\fpeval{#3-#5}}{\fpeval{#2-#4}}\ifthenelse{\boolean{Simplification}}{\\a&=\SSimplifie{\fpeval{#3-#5}}{\fpeval{#2-#4}}}{}%
        \end{align*}
        La fonction $\useKV[ClesAffine]{Nom}$ s'\'ecrit alors sous la forme $\displaystyle\useKV[ClesAffine]{Nom}(\useKV[ClesAffine]{Variable})=\SSimplifie{\fpeval{#3-#5}}{\fpeval{#2-#4}}\useKV[ClesAffine]{Variable}+b$.
        \\De plus, comme $\useKV[ClesAffine]{Nom}(\num{#2})=\num{#3}$, alors :
        \begin{align*}
          \SSimplifie{\fpeval{#3-#5}}{\fpeval{#2-#4}}\times\xintifboolexpr{#2<0}{(\num{#2})}{\num{#2}}+b&=\num{#3}\\
          \SSimplifie{\fpeval{(#3-#5)*#2}}{\fpeval{#2-#4}}+b&=\num{#3}\\
          b&=\num{\fpeval{#3-(#3-#5)*#2/(#2-#4)}}
        \end{align*}
        \xdef\OrdOrigine{\fpeval{#3-(#3-#5)*#2/(#2-#4)}}
        La fonction affine $\useKV[ClesAffine]{Nom}$ cherch\'ee est :
        \[\useKV[ClesAffine]{Nom}:\useKV[ClesAffine]{Variable}\mapsto\SSimplifie{\fpeval{#3-#5}}{\fpeval{#2-#4}}\useKV[ClesAffine]{Variable}\xintifboolexpr{\OrdOrigine==0}{}{\xintifboolexpr{\OrdOrigine>0}{+\num{\OrdOrigine}}{-\num{\fpeval{0-\OrdOrigine}}}}\]
      }{%
        %
      }%
    }%
  }%
  \ifboolKV[ClesAffine]{Graphique}{%
    \ifboolKV[ClesAffine]{VoirCoef}{%
      \MPFonctionAffine{\useKV[ClesAffine]{Unitex}}{\useKV[ClesAffine]{Unitey}}{#2}{#3}{#4}{#5}{\useKV[ClesAffine]{ACoef}}%
    }{%
      \MPFonctionAffine{\useKV[ClesAffine]{Unitex}}{\useKV[ClesAffine]{Unitey}}{#2}{#3}{#4}{#5}{""}}{}%
  }{}%
  \ifboolKV[ClesAffine]{Redaction}{%
    \xintifboolexpr{#2==0}{Comme la fonction $\useKV[ClesAffine]{Nom}$
      est une fonction constante, alors sa repr\'esentation graphique est une droite parall\`ele \`a l'axe des abscisses passant par le point de coordonn\'ees $(0;\num{#3})$.}%
    {\xintifboolexpr{#3==0}{Comme la fonction $\useKV[ClesAffine]{Nom}$ est une fonction lin\'eaire, alors sa repr\'esentation graphique est une droite passant par l'origine du rep\`ere.\\Je choisis $\useKV[ClesAffine]{Variable}=\num{#4}$. Son image est \xdef\NomFonctionA{\useKV[ClesAffine]{Nom}}\FonctionAffine[Nom=\NomFonctionA,Image,Ligne]{#4}{#2}{#3}{#5}. On place le point de coordonn\'ees $(\num{#4};\num{\fpeval{#2*#4+#3}})$.
      }{%
        Comme $\useKV[ClesAffine]{Nom}$ est une fonction affine, alors sa repr\'esentation graphique est une droite.\\Je choisis $\useKV[ClesAffine]{Variable}=\num{#4}$. Son image est \xdef\NomVariable{\useKV[ClesAffine]{Variable}}\xdef\NomFonction{\useKV[ClesAffine]{Nom}}\FonctionAffine[Nom=\NomFonction,Image,Ligne]{#4}{#2}{#3}{#5}. On place le point de coordonn\'ees $(\num{#4};\num{\fpeval{#2*#4+#3}})$.\\Je choisis \setKV[ClesAffine]{Variable=\NomVariable}$\useKV[ClesAffine]{Variable}=\num{#5}$. Son image est \FonctionAffine[Nom=\NomFonction,Image,Ligne]{#5}{#2}{#3}{#4}. On place le point de coordonn\'ees $(\num{#5};\num{\fpeval{#2*#5+#3}})$.%        
      }%
    }%
  }%
  {}%
  \ifboolKV[ClesAffine]{Ecriture}{\ensuremath{\useKV[ClesAffine]{Nom}(\useKV[ClesAffine]{Variable})=\xintifboolexpr{#2==0}{}{\num{#2}\useKV[ClesAffine]{Variable}}\xintifboolexpr{#2==0}{\num{#3}}{\xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}}}}}}{}%
  \ifboolKV[ClesAffine]{Definition}{\ensuremath{\useKV[ClesAffine]{Nom}:\useKV[ClesAffine]{Variable}\mapsto\xintifboolexpr{#2==0}{}{\num{#2}\useKV[ClesAffine]{Variable}}\xintifboolexpr{#2==0}{\num{#3}}{\xintifboolexpr{#3==0}{}{\xintifboolexpr{#3>0}{+\num{#3}}{-\num{\fpeval{0-#3}}}}}}}{}%
}%

\def\MPFonctionAffine#1#2#3#4#5#6#7{%
  % #1 Unitex #2 Unitey
    % #2 a pour f1 - #4 b pour f1
    % #5 abscisse du premier point
    % #6 abscisse du deuxi\`eme point
  \ifluatex
   \mplibforcehmode
  \begin{mplibcode}
    XMin=-2;
    XMax=2;
    if #5<XMin:
    XMin:=#5;
    fi;
    if #6<XMin:
    XMin:=#6;
    fi;
    if #5>XMax:
    XMax:=#5;
    fi;
    if #6>XMax:
    XMax:=#6;
    fi;
    YMax=2;
    YMin=-2;
    if (#5*#3+(#4))>YMax:
    YMax:=(#5*#3+(#4));
    fi;
    if (#6*#3+(#4))>YMax:
    YMax:=(#6*#3+(#4));
    fi;
    if (#5*#3+(#4))<YMin:
    YMin:=(#5*#3+(#4));
    fi;
    if (#6*#3+(#4))<YMin:
    YMin:=(#6*#3+(#4));
    fi;
    unitex:=#1*cm;
    unitey:=#2*cm;
    XMax:=XMax+2;
    XMin:=XMin-2;
    YMax:=YMax+2;
    YMin:=YMin-2;
    %On trace la grille
    drawoptions(withcolor 0.95white);
    for k=0 upto (XMax-XMin):
    draw ((XMin+k)*unitex,YMin*unitey)--((XMin+k)*unitex,YMax*unitey);
    endfor;
    for k=0 upto (YMax-YMin):
    draw (XMin*unitex,(YMin+k)*unitey)--(XMax*unitex,(YMin+k)*unitey);
    endfor;
    drawoptions();
    %On trace les axes
    drawarrow (XMin*unitex,0)--(XMax*unitex,0);
    drawarrow (0,YMin*unitey)--(0,YMax*unitey);
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,(unitex,0));
    dotlabel.lft(btex 1 etex,(0,unitey));
    % On trace la droite
    pair A[];
    A1=(#5*unitex,(#5*#3+(#4))*unitey);
    A2=(#6*unitex,(#6*#3+(#4))*unitey);
    draw 2[A1,A2]--2[A2,A1];
    clip currentpicture to ((XMin*unitex,YMin*unitey)--(XMax*unitex,YMin*unitey)--(XMax*unitex,YMax*unitey)--(XMin*unitex,YMax*unitey)--cycle);
    %On labellise les points
    fill (fullcircle scaled 1mm) shifted A1;
    fill (fullcircle scaled 1mm) shifted A2;
    draw (xpart(A1),0)--A1--(0,ypart(A1)) dashed evenly;
    draw (xpart(A2),0)--A2--(0,ypart(A2)) dashed evenly;
    if (#5*#3+(#4))=0:
    else:
    if (#5*#3+(#4))<0:
    label.top(TEX("\num{"&decimal(#5)&"}"),(xpart(A1),0));
    else:
    label.bot(TEX("\num{"&decimal(#5)&"}"),(xpart(A1),0));
    fi;
    fi;
    if (#6*#3+(#4))=0:
    else:
    if (#6*#3+(#4))<0:
    label.top(TEX("\num{"&decimal(#6)&"}"),(xpart(A2),0));
    else:
    label.bot(TEX("\num{"&decimal(#6)&"}"),(xpart(A2),0));
    fi;
    fi;
    if #3=0:
    label.urt(TEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    else:
    if #3>0:
    if (#5*#3+(#4))=0:
    else:
    if (#5*#3+(#4))<0:
    label.rt(TEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    else:
    label.lft(TEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    fi;
    fi;
    if (#6*#3+(#4))=0:
    else:
    if (#6*#3+(#4))<0:
    label.rt(TEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    else:
    label.lft(TEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    fi;
    fi;
    else:
    if (#5*#3+(#4))=0:
    else:
    if (#5*#3+(#4))<0:
    label.lft(TEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    else:
    label.rt(TEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    fi;
    fi;
    if (#6*#3+(#4))=0:
    else:
    if (#6*#3+(#4))<0:
    label.lft(TEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    else:
    label.rt(TEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    fi;
    fi;
    fi;
    fi;
    % On affiche ou pas "la marche" du coef directeur
    for p_=#7:
    if numeric p_:
    draw ((#7*unitex,(#7*#3+(#4))*unitey)--((#7+1)*unitex,(#7*#3+(#4))*unitey)--((#7+1)*unitex,((#7+1)*#3+(#4))*unitey)) withcolor red;
    fi;
    endfor;
  \end{mplibcode}
  \else
  \begin{mpost}
    % On d\'efinit les constantes
    XMin=-2;
    XMax=2;
    if #5<XMin:
    XMin:=#5;
    fi;
    if #6<XMin:
    XMin:=#6;
    fi;
    if #5>XMax:
    XMax:=#5;
    fi;
    if #6>XMax:
    XMax:=#6;
    fi;
    YMax=2;
    YMin=-2;
    if (#5*#3+(#4))>YMax:
    YMax:=(#5*#3+(#4));
    fi;
    if (#6*#3+(#4))>YMax:
    YMax:=(#6*#3+(#4));
    fi;
    if (#5*#3+(#4))<YMin:
    YMin:=(#5*#3+(#4));
    fi;
    if (#6*#3+(#4))<YMin:
    YMin:=(#6*#3+(#4));
    fi;
    unitex:=#1*cm;
    unitey:=#2*cm;
    XMax:=XMax+2;
    XMin:=XMin-2;
    YMax:=YMax+2;
    YMin:=YMin-2;
    %On trace la grille
    drawoptions(withcolor 0.95white);
    for k=0 upto (XMax-XMin):
    draw ((XMin+k)*unitex,YMin*unitey)--((XMin+k)*unitex,YMax*unitey);
    endfor;
    for k=0 upto (YMax-YMin):
    draw (XMin*unitex,(YMin+k)*unitey)--(XMax*unitex,(YMin+k)*unitey);
    endfor;
    drawoptions();
    %On trace les axes
    drawarrow (XMin*unitex,0)--(XMax*unitex,0);
    drawarrow (0,YMin*unitey)--(0,YMax*unitey);
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,(unitex,0));
    dotlabel.lft(btex 1 etex,(0,unitey));
    % On trace la droite
    pair A[];
    A1=(#5*unitex,(#5*#3+(#4))*unitey);
    A2=(#6*unitex,(#6*#3+(#4))*unitey);
    draw 2[A1,A2]--2[A2,A1];
    clip currentpicture to ((XMin*unitex,YMin*unitey)--(XMax*unitex,YMin*unitey)--(XMax*unitex,YMax*unitey)--(XMin*unitex,YMax*unitey)--cycle);
    %On labellise les points
    fill (fullcircle scaled 1mm) shifted A1;
    fill (fullcircle scaled 1mm) shifted A2;
    draw (xpart(A1),0)--A1--(0,ypart(A1)) dashed evenly;
    draw (xpart(A2),0)--A2--(0,ypart(A2)) dashed evenly;
    if (#5*#3+(#4))=0:
    else:
    if (#5*#3+(#4))<0:
    label.top(LATEX("\num{"&decimal(#5)&"}"),(xpart(A1),0));
    else:
    label.bot(LATEX("\num{"&decimal(#5)&"}"),(xpart(A1),0));
    fi;
    fi;
    if (#6*#3+(#4))=0:
    else:
    if (#6*#3+(#4))<0:
    label.top(LATEX("\num{"&decimal(#6)&"}"),(xpart(A2),0));
    else:
    label.bot(LATEX("\num{"&decimal(#6)&"}"),(xpart(A2),0));
    fi;
    fi;
    if #3=0:
    label.urt(LATEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    else:
    if #3>0:
    if (#5*#3+(#4))=0:
    else:
    if (#5*#3+(#4))<0:
    label.rt(LATEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    else:
    label.lft(LATEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    fi;
    fi;
    if (#6*#3+(#4))=0:
    else:
    if (#6*#3+(#4))<0:
    label.rt(LATEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    else:
    label.lft(LATEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    fi;
    fi;
    else:
    if (#5*#3+(#4))=0:
    else:
    if (#5*#3+(#4))<0:
    label.lft(LATEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    else:
    label.rt(LATEX("\num{"&decimal(#5*#3+(#4))&"}"),(0,ypart(A1)));
    fi;
    fi;
    if (#6*#3+(#4))=0:
    else:
    if (#6*#3+(#4))<0:
    label.lft(LATEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    else:
    label.rt(LATEX("\num{"&decimal(#6*#3+(#4))&"}"),(0,ypart(A2)));
    fi;
    fi;
    fi;
    fi;
    % On affiche ou pas "la marche" du coef directeur
    for p_=#7:
    if numeric p_:
    draw ((#7*unitex,(#7*#3+(#4))*unitey)--((#7+1)*unitex,(#7*#3+(#4))*unitey)--((#7+1)*unitex,((#7+1)*#3+(#4))*unitey)) withcolor red;
    fi;
    endfor;
  \end{mpost}
  \fi
}


%%%
% Fonction
%%%
\setKVdefault[ClesFonction]{Nom=f,Variable=x,Calcul=x,Tableau=false,Largeur=5mm,Ecriture=false,Definition=false,Points=false,Tangentes=false,PasX=1,PasY=1,UniteX=1,UniteY=1,Prolonge=false,Trace=false,Catmull=false,Epaisseur=1,Couleur=black,PointsCourbe=true,Codes=false}
\defKV[ClesFonction]{Traces=\setKV[ClesFonction]{Codes}}%

\newtoks\toklistePtsFn%pour la discipline

\def\UpdatePtsFn#1/#2/#3/#4\nil{\addtotok\toklistePtsFn{#1,(#2,#3),#4,}}%
\def\UpdatePtsFN#1/#2/#3/#4\nil{\addtotok\toklistePtsFn{(#2,#3),}}%

\def\MPCourbePoints#1#2#3#4#5#6{%
  % #1 la liste des points
  % #2: pas en x
  % #3: pas en y
  % #4: unit\'e en x
  % #5: unit\'e en y
  % #6 : prolongement avant et apr\`es les premier et dernier points ?
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    x.u:=#2;
    y.u:=#3;
    X.u:=#4;
    Y.u:=#5;
    numeric dirav[],dirap[];
    pair Fn[],Gn[];
    n=0;
    for p_=#1:
    Gn[n]=p_;
    Fn[n]=cm*(X.u*xpart(p_),Y.u*ypart(p_));
    n:=n+1;
    endfor;
    N:=(n-1);
    MinX=999;
    MaxX=-999;
    MinY=999;
    MaxY=-999;
    for k=0 upto N:
    if xpart(Gn[k])<MinX:
    MinX:=xpart(Gn[k]);
    fi;
    if xpart(Gn[k])>MaxX:
    MaxX:=xpart(Gn[k]);
    fi;
    if ypart(Gn[k])<MinY:
    MinY:=ypart(Gn[k]);
    fi;
    if ypart(Gn[k])>MaxY:
    MaxY:=ypart(Gn[k]);
    fi;
    endfor;
    if #6=0:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX-1)*X.u,k*Y.u)--cm*((MaxX+1)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX-1 step x.u until MaxX+1:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    else:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX)*X.u,k*Y.u)--cm*((MaxX)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX step x.u until MaxX:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    fi;
    if #6=0:
    for k=0 upto N:
    fill cercles(Fn[k],0.5mm);
    endfor;
    else:
    for k=1 upto N-1:
    fill cercles(Fn[k],0.5mm);
    endfor;
    fi;
    if #6=0:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX-1)*X.u*cm,0)--((MaxX+1)*X.u*cm,0);
    else:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX)*X.u*cm,0)--((MaxX)*X.u*cm,0);
    fi;
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,cm*X.u*(1,0));
    dotlabel.lft(btex 1 etex,cm*Y.u*(0,1));
    draw Fn[0]
    for k=1 upto N:
    ..Fn[k]
    endfor withpen pencircle scaled \useKV[ClesFonction]{Epaisseur};
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric Epaisseur; Epaisseur=\useKV[ClesFonction]{Epaisseur};}]
    x.u:=#2;
    y.u:=#3;
    X.u:=#4;
    Y.u:=#5;
    numeric dirav[],dirap[];
    pair Fn[],Gn[];
    n=0;
    for p_=#1:
    Gn[n]=p_;
    Fn[n]=cm*(X.u*xpart(p_),Y.u*ypart(p_));
    n:=n+1;
    endfor;
    N:=(n-1);
    MinX=999;
    MaxX=-999;
    MinY=999;
    MaxY=-999;
    for k=0 upto N:
    if xpart(Gn[k])<MinX:
    MinX:=xpart(Gn[k]);
    fi;
    if xpart(Gn[k])>MaxX:
    MaxX:=xpart(Gn[k]);
    fi;
    if ypart(Gn[k])<MinY:
    MinY:=ypart(Gn[k]);
    fi;
    if ypart(Gn[k])>MaxY:
    MaxY:=ypart(Gn[k]);
    fi;
    endfor;
    if #6=0:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX-1)*X.u,k*Y.u)--cm*((MaxX+1)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX-1 step x.u until MaxX+1:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    else:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX)*X.u,k*Y.u)--cm*((MaxX)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX step x.u until MaxX:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    fi;
    if #6=0:
    for k=0 upto N:
    fill cercles(Fn[k],0.5mm);
    endfor;
    else:
    for k=1 upto N-1:
    fill cercles(Fn[k],0.5mm);
    endfor;
    fi;
    if #6=0:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX-1)*X.u*cm,0)--((MaxX+1)*X.u*cm,0);
    else:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX)*X.u*cm,0)--((MaxX)*X.u*cm,0);
    fi;
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,cm*X.u*(1,0));
    dotlabel.lft(btex 1 etex,cm*Y.u*(0,1));
    draw Fn[0]
    for k=1 upto N:
    ..Fn[k]
    endfor withpen pencircle scaled Epaisseur;
  \end{mpost}
  \fi
}

\def\MPCourbe#1#2#3#4#5#6{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    x.u:=#2;
    y.u:=#3;
    X.u:=#4;
    Y.u:=#5;
    numeric dirav[],dirap[];
    pair Fn[],Gn[];
    n=0;
    for p_=#1:
    if (n mod 3)=0:
    dirav[n div 3]=p_;
    fi;
    if (n mod 3)=1:
    Gn[n div 3]=p_;
    Fn[n div 3]=cm*(X.u*xpart(p_),Y.u*ypart(p_));
    fi;
    if (n mod 3)=2:
    dirap[n div 3]=p_;
    fi;
    n:=n+1;
    endfor;
    N:=(n-1) div 3;
    MinX=999;
    MaxX=-999;
    MinY=999;
    MaxY=-999;
    for k=0 upto N:
    if xpart(Gn[k])<MinX:
    MinX:=xpart(Gn[k]);
    fi;
    if xpart(Gn[k])>MaxX:
    MaxX:=xpart(Gn[k]);
    fi;
    if ypart(Gn[k])<MinY:
    MinY:=ypart(Gn[k]);
    fi;
    if ypart(Gn[k])>MaxY:
    MaxY:=ypart(Gn[k]);
    fi;
    endfor;
        if #6=0:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX-1)*X.u,k*Y.u)--cm*((MaxX+1)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX-1 step x.u until MaxX+1:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    else:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX)*X.u,k*Y.u)--cm*((MaxX)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX step x.u until MaxX:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    fi;
    if #6=0:
    for k=0 upto N:
    fill cercles(Fn[k],0.5mm);
    endfor;
    else:
    for k=1 upto N-1:
    fill cercles(Fn[k],0.5mm);
    endfor;
    fi;
    if #6=0:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX-1)*X.u*cm,0)--((MaxX+1)*X.u*cm,0);
    else:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX)*X.u*cm,0)--((MaxX)*X.u*cm,0);
    fi;
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,cm*X.u*(1,0));
    dotlabel.lft(btex 1 etex,cm*Y.u*(0,1));
    draw Fn[0]{dir dirap[0]}
    for k=1 upto (N-1):
    ..{dir dirav[k]}Fn[k]{dir dirap[k]}
    endfor
    ..{dir dirav[N]}Fn[N] withpen pencircle scaled \useKV[ClesFonction]{Epaisseur};
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric Epaisseur; Epaisseur=\useKV[ClesFonction]{Epaisseur};}]
    x.u:=#2;
    y.u:=#3;
    X.u:=#4;
    Y.u:=#5;
    numeric dirav[],dirap[];
    pair Fn[],Gn[];
    n=0;
    for p_=#1:
    if (n mod 3)=0:
    dirav[n div 3]=p_;
    fi;
    if (n mod 3)=1:
    Gn[n div 3]=p_;
    Fn[n div 3]=cm*(X.u*xpart(p_),Y.u*ypart(p_));
    fi;
    if (n mod 3)=2:
    dirap[n div 3]=p_;
    fi;
    n:=n+1;
    endfor;
    N:=(n-1) div 3;
    MinX=999;
    MaxX=-999;
    MinY=999;
    MaxY=-999;
    for k=0 upto N:
    if xpart(Gn[k])<MinX:
    MinX:=xpart(Gn[k]);
    fi;
    if xpart(Gn[k])>MaxX:
    MaxX:=xpart(Gn[k]);
    fi;
    if ypart(Gn[k])<MinY:
    MinY:=ypart(Gn[k]);
    fi;
    if ypart(Gn[k])>MaxY:
    MaxY:=ypart(Gn[k]);
    fi;
    endfor;
    if #6=0:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX-1)*X.u,k*Y.u)--cm*((MaxX+1)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX-1 step x.u until MaxX+1:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    else:
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX)*X.u,k*Y.u)--cm*((MaxX)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX step x.u until MaxX:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    fi;
    if #6=0:
    for k=0 upto N:
    fill cercles(Fn[k],0.5mm);
    endfor;
    else:
    for k=1 upto N-1:
    fill cercles(Fn[k],0.5mm);
    endfor;
    fi;
    if #6=0:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX-1)*X.u*cm,0)--((MaxX+1)*X.u*cm,0);
    else:
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX)*X.u*cm,0)--((MaxX)*X.u*cm,0);
    fi;
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,cm*X.u*(1,0));
    dotlabel.lft(btex 1 etex,cm*Y.u*(0,1));
    draw Fn[0]{dir dirap[0]}
    for k=1 upto (N-1):
    ..{dir dirav[k]}Fn[k]{dir dirap[k]}
    endfor
    ..{dir dirav[N]}Fn[N] withpen pencircle scaled Epaisseur;
  \end{mpost}
  \fi
}

\def\MPCatmull#1#2#3#4#5{%
  % #1 la liste des points
  % #2: pas en x
  % #3: pas en y
  % #4: unit\'e en x
  % #5: unit\'e en y
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    boolean PointsCourbe;
    PointsCourbe=\useKV[ClesFonction]{PointsCourbe};

    boolean Code;
    Code=\useKV[ClesFonction]{Codes};
        
    x.u:=#2;
    y.u:=#3;
    X.u:=#4;
    Y.u:=#5;

    pair Fn[],Gn[];
    n=0;
    for p_=#1:
    Gn[n]=p_;
    Fn[n]=cm*(X.u*xpart(p_),Y.u*ypart(p_));
    n:=n+1;
    endfor;
    N:=(n-1);
    MinX=999;
    MaxX=-999;
    MinY=999;
    MaxY=-999;
    debutbalai=0;
    finbalai=N;
    if \useKV[ClesFonction]{Prolonge}:
    debutbalai:=2;
    finbalai:=N-2;
    fi;
    for k=debutbalai upto finbalai:
    if xpart(Gn[k])<MinX:
    MinX:=xpart(Gn[k]);
    fi;
    if xpart(Gn[k])>MaxX:
    MaxX:=xpart(Gn[k]);
    fi;
    if ypart(Gn[k])<MinY:
    MinY:=ypart(Gn[k]);
    fi;
    if ypart(Gn[k])>MaxY:
    MaxY:=ypart(Gn[k]);
    fi;
    endfor;
    if MaxY<1:
    MaxY:=2;
    fi;
    if MinY>-1:
    MinY:=-2;
    fi;
    %
    path cadreexterieur;
    cadreexterieur=(((MinX-1)*X.u*cm,(MinY-1)*Y.u*cm)--((MaxX+1)*X.u*cm,(MinY-1)*Y.u*cm)--((MaxX+1)*X.u*cm,(MaxY+1)*Y.u*cm)--((MinX-1)*X.u*cm,(MaxY+1)*Y.u*cm)--cycle);
    draw Fn[1]
    for k=2 upto N-1:
    ..{dir angle(Fn[k+1]-Fn[k-1])}Fn[k]{dir angle(Fn[k+1]-Fn[k-1])}
    endfor withpen pencircle scaled \useKV[ClesFonction]{Epaisseur} withcolor \useKV[ClesFonction]{Couleur};
    clip currentpicture to cadreexterieur;
    picture RetiensCourbe;
    RetiensCourbe=currentpicture;
    currentpicture:=nullpicture;
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX-1)*X.u,k*Y.u)--cm*((MaxX+1)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX-1 step x.u until MaxX+1:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    if PointsCourbe:
    for k=debutbalai upto finbalai:
    fill cercles(Fn[k],0.5mm);
    endfor;
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX-1)*X.u*cm,0)--((MaxX+1)*X.u*cm,0);
    %
    draw RetiensCourbe;
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,cm*X.u*(1,0));
    dotlabel.lft(btex 1 etex,cm*Y.u*(0,1));
    fi;
    if Code:
    \useKV[ClesFonction]{Traces};
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={numeric Epaisseur; Epaisseur=\useKV[ClesFonction]{Epaisseur}; color CouleurCourbe; CouleurCourbe=\useKV[ClesFonction]{Couleur};boolean PointsCourbe;PointsCourbe=\useKV[ClesFonction]{PointsCourbe};}]
    x.u:=#2;
    y.u:=#3;
    X.u:=#4;
    Y.u:=#5;
    pair Fn[],Gn[];
    n=0;
    for p_=#1:
    Gn[n]=p_;
    Fn[n]=cm*(X.u*xpart(p_),Y.u*ypart(p_));
    n:=n+1;
    endfor;
    N:=(n-1);
    MinX=999;
    MaxX=-999;
    MinY=999;
    MaxY=-999;
    debutbalai=0;
    finbalai=N;
    if \useKV[ClesFonction]{Prolonge}:
    debutbalai:=2;
    finbalai:=N-2;
    fi;
    for k=debutbalai upto finbalai:
    if xpart(Gn[k])<MinX:
    MinX:=xpart(Gn[k]);
    fi;
    if xpart(Gn[k])>MaxX:
    MaxX:=xpart(Gn[k]);
    fi;
    if ypart(Gn[k])<MinY:
    MinY:=ypart(Gn[k]);
    fi;
    if ypart(Gn[k])>MaxY:
    MaxY:=ypart(Gn[k]);
    fi;
    endfor;
    if MaxY<1:
    MaxY:=2;
    fi;
    if MinY>-1:
    MinY:=-2;
    fi;
    %
    path cadreexterieur;
    cadreexterieur=(((MinX-1)*X.u*cm,(MinY-1)*Y.u*cm)--((MaxX+1)*X.u*cm,(MinY-1)*Y.u*cm)--((MaxX+1)*X.u*cm,(MaxY+1)*Y.u*cm)--((MinX-1)*X.u*cm,(MaxY+1)*Y.u*cm)--cycle);
    draw Fn[1]
    for k=2 upto N-1:
    ..{dir angle(Fn[k+1]-Fn[k-1])}Fn[k]{dir angle(Fn[k+1]-Fn[k-1])}
    endfor withpen pencircle scaled \useKV[ClesFonction]{Epaisseur} withcolor \useKV[ClesFonction]{Couleur};
    clip currentpicture to cadreexterieur;
    picture RetiensCourbe;
    RetiensCourbe=currentpicture;
    currentpicture:=nullpicture;
    for k=MinY-1 step y.u until MaxY+1:
    draw cm*((MinX-1)*X.u,k*Y.u)--cm*((MaxX+1)*X.u,k*Y.u) withcolor 0.75white;
    endfor;
    for k=MinX-1 step x.u until MaxX+1:
    draw cm*(k*X.u,(MinY-1)*Y.u)--cm*(k*X.u,(MaxY+1)*Y.u) withcolor 0.75white;
    endfor;
    if PointsCourbe:
    for k=debutbalai upto finbalai:
    fill cercles(Fn[k],0.5mm);
    endfor;
    drawarrow (0,(MinY-1)*Y.u*cm)--(0,(MaxY+1)*Y.u*cm);
    drawarrow ((MinX-1)*X.u*cm,0)--((MaxX+1)*X.u*cm,0);
    %
    draw RetiensCourbe;
    label.llft(btex O etex,(0,0));
    dotlabel.bot(btex 1 etex,cm*X.u*(1,0));
    dotlabel.lft(btex 1 etex,cm*Y.u*(0,1));
    fi;
  \end{mpost}
  \fi
}%

\newcommand\Fonction[2][]{%
  \useKVdefault[ClesFonction]%
  \setKV[ClesFonction]{#1}%
  \ifboolKV[ClesFonction]{Trace}{%
    \useKVdefault[TraceG]%
    \setKV[TraceG]{#1}%
    \MPTraceFonction[#1]{\useKV[ClesFonction]{Calcul}}%
  }{%
    \ifboolKV[ClesFonction]{Points}{%
      \toklistePtsFn{}%
      \setsepchar[*]{§*/}%\ignoreemptyitems%
      \readlist*\ListePoints{#2}%
      \ifboolKV[ClesFonction]{Catmull}{%
        \xdef\PfCFooListePoints{(\ListePoints[1,2],\ListePoints[1,3]),}
        \foreachitem\compteur\in\ListePoints{%
          \xdef\PfCFooListePoints{\PfCFooListePoints (\ListePoints[\compteurcnt,2],\ListePoints[\compteurcnt,3]),}%
        }%
        \xdef\PfCFooListePoints{\PfCFooListePoints (\ListePoints[\ListePointslen,2],\ListePoints[\ListePointslen,3]),}%
        \MPCatmull{\PfCFooListePoints}{\useKV[ClesFonction]{PasX}}{\useKV[ClesFonction]{PasY}}{\useKV[ClesFonction]{UniteX}}{\useKV[ClesFonction]{UniteY}}%
      }{%
        \ifboolKV[ClesFonction]{Tangentes}{%
          \foreachitem\compteur\in\ListePoints{%
            \expandafter\UpdatePtsFn\compteur\nil%
          }%
          \ifboolKV[ClesFonction]{Prolonge}{%
            \MPCourbe{\the\toklistePtsFn}{\useKV[ClesFonction]{PasX}}{\useKV[ClesFonction]{PasY}}{\useKV[ClesFonction]{UniteX}}{\useKV[ClesFonction]{UniteY}}{1}%
          }{%
            \MPCourbe{\the\toklistePtsFn}{\useKV[ClesFonction]{PasX}}{\useKV[ClesFonction]{PasY}}{\useKV[ClesFonction]{UniteX}}{\useKV[ClesFonction]{UniteY}}{0}%
          }%
        }{%
          \foreachitem\compteur\in\ListePoints{%
            \expandafter\UpdatePtsFN\compteur\nil%
          }%
          \ifboolKV[ClesFonction]{Prolonge}{%
            \MPCourbePoints{\the\toklistePtsFn}{\useKV[ClesFonction]{PasX}}{\useKV[ClesFonction]{PasY}}{\useKV[ClesFonction]{UniteX}}{\useKV[ClesFonction]{UniteY}}{1}%
          }{%
            \MPCourbePoints{\the\toklistePtsFn}{\useKV[ClesFonction]{PasX}}{\useKV[ClesFonction]{PasY}}{\useKV[ClesFonction]{UniteX}}{\useKV[ClesFonction]{UniteY}}{0}%
          }%
        }%
      }%
    }{%
      \setsepchar{,}\ignoreemptyitems%
      \readlist*\ListeFonction{#2}%
      \StrSubstitute{\useKV[ClesFonction]{Calcul}}{\useKV[ClesFonction]{Variable}}{\i}[\temp]%
      \StrSubstitute{\useKV[ClesFonction]{Calcul}}{**}{^}[\tempa]%
      \StrSubstitute{\tempa}{*}{}[\tempab]%
      \ifboolKV[ClesFonction]{Ecriture}{%
        \ensuremath{\useKV[ClesFonction]{Nom}(\useKV[ClesFonction]{Variable})=\tempab}%
      }{}%
      \ifboolKV[ClesFonction]{Definition}{%
        \ensuremath{\useKV[ClesFonction]{Nom}:\useKV[ClesFonction]{Variable}\mapsto\tempab}%
      }{}%
      \ifboolKV[ClesFonction]{Tableau}{%
        \buildtabfonction%
      }{}%
      \reademptyitems%
    }%
  }%
}%

\def\buildtabfonction{%
  \[%
    \begin{array}{|>{\columncolor{gray!15}}c|*{\number\numexpr\ListeFonctionlen}{>{\centering\arraybackslash}p{\useKV[ClesFonction]{Largeur}}|}}%
      \hline
      \useKV[ClesFonction]{Variable}\xintFor* ##1 in {\xintSeq {1}{\ListeFonctionlen}}\do{&\num{\ListeFonction[##1]}}\\
      \hline
      \useKV[ClesFonction]{Nom}(\useKV[ClesFonction]{Variable})\xintFor* ##1 in {\xintSeq {1}{\ListeFonctionlen}}\do{&  \StrSubstitute{\useKV[ClesFonction]{Calcul}}{\useKV[ClesFonction]{Variable}}{(\ListeFonction[##1])}[\tempab]\num{\fpeval{\tempab}}}
      \\\hline
    \end{array}%
  \]%
}%

%%%
% Diff\'erentes représentations graphiques
%%%
\setKVdefault[TraceG]{Grille=false,Graduations=false,PasGradX=1,PasGradY=1,PasGrilleX=1,PasGrilleY=1,Xmin=-5.5,Xmax=5.5,Xstep=1,Ymin=-5.5,Ymax=5.5,Ystep=1,Bornea=-5.5,Borneb=5.5,LabelX={},LabelY={},LabelC=0.5,NomCourbe={},Origine={(5.5,5.5)},Fonction=false,Points=false,Invisible=false,CouleurPoint=red,CouleurTrace=black,Epaisseur=1,Relie=false,RelieSegment=false,Marque=dot,Code=false}%
\defKV[TraceG]{Traces=\setKV[TraceG]{Code}}%

\newcommand\TraceGraphique[2][]{%
  \useKVdefault[TraceG]%
  \setKV[TraceG]{#1}%
  \ifboolKV[TraceG]{Fonction}{%
    \MPTraceFonction[#1]{#2}%
  }{%
    \setKV[TraceG]{Xmin=0,Ymin=0}
    \setKV[TraceG]{#1}%
    \readlist*\ListePointsPlaces{#2}%
    \newtoks\toklistepoint%
    \foreachitem\compteur\in\ListePointsPlaces{\expandafter\Updatetoks\compteur\nil}%
    \MPPlacePoint[#1]{\the\toklistepoint}
  }%
}%

\newcommand\MPPlacePoint[2][]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    xmin=\useKV[TraceG]{Xmin};
    xmax=\useKV[TraceG]{Xmax};
    ymin=\useKV[TraceG]{Ymin};
    ymax=\useKV[TraceG]{Ymax};
    pasx=\useKV[TraceG]{Xstep};
    pasy=\useKV[TraceG]{Ystep};
    x.u=1cm/\useKV[TraceG]{Xstep};
    y.u=1cm/\useKV[TraceG]{Ystep};
    grillex=\useKV[TraceG]{PasGrilleX};
    grilley=\useKV[TraceG]{PasGrilleY};
    pos=\useKV[TraceG]{LabelC};

    marque_p:=str \useKV[TraceG]{Marque};
    m_c:=m_c*2;
    
    color colorpoint,colortrace;
    colorpoint=\useKV[TraceG]{CouleurPoint};
    colortrace=\useKV[TraceG]{CouleurTrace};
    boolean Grille;
    Grille=\useKV[TraceG]{Grille};

    boolean Graduations;
    Graduations=\useKV[TraceG]{Graduations};

    boolean Relie;
    Relie=\useKV[TraceG]{Relie};

    boolean RelieSegment;
    RelieSegment=\useKV[TraceG]{RelieSegment};

    boolean Invisible;
    Invisible=\useKV[TraceG]{Invisible};
    
    pair Origine;
    Origine=(0,0);
    
    if Grille:
    drawoptions(withcolor 0.75white);
    for k=0 step grillex until (xmax-xmin):
    trace (k*x.u,ypart(Origine))--(x.u*k,y.u*(ymax-ymin));
    endfor;
    for k=0 step grilley until (ymax-ymin):
    trace (xpart(Origine),k*y.u)--(x.u*(xmax-xmin),y.u*k);
    endfor;
    drawoptions();
    fi;
    
    if Graduations:
    for k=0 step grillex until (xmax-xmin):
    trace ((0,-0.5mm)--(0,0.5mm)) shifted ((k*x.u,0) shifted Origine) withpen pencircle scaled1.25;
    label.bot(TEX("\num{"&decimal(xmin+k)&"}"),(k*x.u,0) shifted Origine);
    endfor;
    label.ulft(TEX("\num{"&decimal(ymin)&"}"),(0,0) shifted Origine);
    for k=grilley step grilley until (ymax-ymin):
    trace ((-0.5mm,0)--(0.5mm,0)) shifted ((0,k*y.u) shifted Origine) withpen pencircle scaled1.25;
    label.lft(TEX("\num{"&decimal(ymin+k)&"}"),(0,k*y.u) shifted Origine);
    endfor;
    fi;
    drawoptions(withpen pencircle scaled1.5);
    drawarrow Origine--(xpart(Origine),y.u*(ymax-ymin));
    drawarrow Origine--((xmax-xmin)*x.u,ypart(Origine));
    drawoptions();

    % On relie éventuellement les points
    if Relie:
    pair N[];
    nbpoint=0;
    for p_=#2:
    nbpoint:=nbpoint+1;
    N[nbpoint]=(x.u*(xpart(p_)-xmin),y.u*(ypart(p_)-ymin));
    endfor;
    draw N[1] for k=2 upto nbpoint:
    ..N[k]
    endfor withcolor colortrace;
    fi;
    if RelieSegment:
    pair N[];
    nbpoint=0;
    for p_=#2:
    nbpoint:=nbpoint+1;
    N[nbpoint]=(x.u*(xpart(p_)-xmin),y.u*(ypart(p_)-ymin));
    endfor;
    draw N[1] for k=2 upto nbpoint:
    --N[k]
    endfor withcolor colortrace;
    fi;
    
    % On place les points
    if Invisible=false:
    drawoptions(withcolor colorpoint);
    for p_=#2:
    if marque_p="dot":
    dotlabel("",(x.u*(xpart(p_)-xmin),y.u*(ypart(p_)-ymin)));
    elseif marque_p="croix":
    pointe((x.u*(xpart(p_)-xmin),y.u*(ypart(p_)-ymin)));
    fi;
    endfor;
    drawoptions();
    fi;
    %on labelise les axes
    label.urt(btex \useKV[TraceG]{LabelX} etex,(x.u*(xmax-xmin),ypart(Origine)));
    label.urt(btex \useKV[TraceG]{LabelY} etex,(xpart(Origine),y.u*(ymax-ymin)));
  \end{mplibcode}
  \else
  \mpxcommands{%
    \usepackage{ProfCollege}
    \setKV[TraceG]{#1}
  }
  \begin{mpost}[mpsettings={xmin=\useKV[TraceG]{Xmin};xmax=\useKV[TraceG]{Xmax};ymin=\useKV[TraceG]{Ymin};ymax=\useKV[TraceG]{Ymax};pasx=\useKV[TraceG]{Xstep};pasy=\useKV[TraceG]{Ystep};xu=1cm/\useKV[TraceG]{Xstep};yu=1cm/\useKV[TraceG]{Ystep};grillex=\useKV[TraceG]{PasGrilleX};grilley=\useKV[TraceG]{PasGrilleY};pos=\useKV[TraceG]{LabelC};color colorpoint,colortrace;colorpoint=\useKV[TraceG]{CouleurPoint};colortrace=\useKV[TraceG]{CouleurTrace};boolean Grille;Grille=\useKV[TraceG]{Grille};boolean Graduations;Graduations=\useKV[TraceG]{Graduations};boolean Relie;Relie=\useKV[TraceG]{Relie};boolean RelieSegment;RelieSegment=\useKV[TraceG]{RelieSegment};boolean Invisible;Invisible=\useKV[TraceG]{Invisible};}]    
    pair Origine;
    Origine=(0,0);
    
    if Grille:
    drawoptions(withcolor 0.75white);
    for k=0 step grillex until (xmax-xmin):
    trace (k*xu,ypart(Origine))--(xu*k,yu*(ymax-ymin));
    endfor;
    for k=0 step grilley until (ymax-ymin):
    trace (xpart(Origine),k*yu)--(xu*(xmax-xmin),yu*k);
    endfor;
    drawoptions();
    fi;
    
    if Graduations:
    for k=0 step grillex until (xmax-xmin):
    trace ((0,-0.5mm)--(0,0.5mm)) shifted ((k*xu,0) shifted Origine) withpen pencircle scaled1.25;
    label.bot(LATEX("\num{"&decimal(xmin+k)&"}"),(k*xu,0) shifted Origine);
    endfor;
    label.ulft(LATEX("\num{"&decimal(ymin)&"}"),(0,0) shifted Origine);
    for k=grilley step grilley until (ymax-ymin):
    trace ((-0.5mm,0)--(0.5mm,0)) shifted ((0,k*yu) shifted Origine) withpen pencircle scaled1.25;
    label.lft(LATEX("\num{"&decimal(ymin+k)&"}"),(0,k*yu) shifted Origine);
    endfor;
    fi;
    drawoptions(withpen pencircle scaled1.5);
    drawarrow Origine--(xpart(Origine),yu*(ymax-ymin));
    drawarrow Origine--((xmax-xmin)*xu,ypart(Origine));
    drawoptions();

    % On relie éventuellement les points
    if Relie:
    pair N[];
    nbpoint=0;
    for p_=#2:
    nbpoint:=nbpoint+1;
    N[nbpoint]=(xu*(xpart(p_)-xmin),yu*(ypart(p_)-ymin));
    endfor;
    draw N[1] for k=2 upto nbpoint:
    ..N[k]
    endfor withcolor colortrace;
    fi;
    if RelieSegment:
    pair N[];
    nbpoint=0;
    for p_=#2:
    nbpoint:=nbpoint+1;
    N[nbpoint]=(xu*(xpart(p_)-xmin),yu*(ypart(p_)-ymin));
    endfor;
    draw N[1] for k=2 upto nbpoint:
    --N[k]
    endfor withcolor colortrace;
    fi;
    
    % On place les points
    if Invisible=false:
    drawoptions(withcolor colorpoint);
    for p_=#2:
    dotlabel("",(xu*(xpart(p_)-xmin),yu*(ypart(p_)-ymin)));
    endfor;
    drawoptions();
    fi;
    %on labelise les axes
    label.urt(btex \unexpanded{\useKV[TraceG]{LabelX}} etex,(xu*(xmax-xmin),ypart(Origine)));
    label.urt(btex \unexpanded{\useKV[TraceG]{LabelY}} etex,(xpart(Origine),yu*(ymax-ymin)));
  \end{mpost}
  \fi
}

\newcommand\MPTraceFonction[2][]{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    borneinf=\useKV[TraceG]{Bornea};
    bornesup=\useKV[TraceG]{Borneb};
    xmin=\useKV[TraceG]{Xmin};
    xmax=\useKV[TraceG]{Xmax};
    ymin=\useKV[TraceG]{Ymin};
    ymax=\useKV[TraceG]{Ymax};
    pasx=\useKV[TraceG]{Xstep};
    pasy=\useKV[TraceG]{Ystep};
    x.u=1cm/\useKV[TraceG]{Xstep};
    y.u=1cm/\useKV[TraceG]{Ystep};
    grillex=\useKV[TraceG]{PasGrilleX};
    grilley=\useKV[TraceG]{PasGrilleY};
    gradx=\useKV[TraceG]{PasGradX};
    grady=\useKV[TraceG]{PasGradY};
    pos=\useKV[TraceG]{LabelC};
    Epaisseur:=\useKV[TraceG]{Epaisseur};
    
    color colortrace;
    colortrace=\useKV[TraceG]{CouleurTrace};
    
    pair Origine;
    Origine=(xmin,ymin)+\useKV[TraceG]{Origine};

    boolean Grille;
    Grille=\useKV[TraceG]{Grille};

    boolean Graduations;
    Graduations=\useKV[TraceG]{Graduations};

    vardef sin(expr t) = sind(c*t) enddef;

    vardef cos(expr t) = cosd(c*t) enddef;
    
    vardef tan(expr t) = sin(t)/cos(t) enddef;
    
    vardef exp(expr t) = e**t enddef;
    
    vardef ch(expr x)=(exp(x)+exp(-x))/2 enddef;
    
    vardef sh(expr x)=(exp(x)-exp(-x))/2 enddef;
    
    vardef ln(expr t) = mlog(t)/256 enddef;
    
    vardef arcsin(expr x)=%Définition mathématique en radian
    pi*angle((sqrt(1-x**2),x))/180
    enddef;
    
    vardef arccos(expr x)=%Définition mathématique en radian
    pi*angle((x,sqrt(1-x**2)))/180
    enddef;

    def enplace=
    xscaled x.u yscaled y.u shifted (Origine*cm)
    enddef;

    vardef placepoint(expr q,r)=
    (q,r) enplace
    enddef;
    
    path Cb[];
    
    vardef courbe[](expr a,b,nb)(text texte)=
    path Courbe;
    for i:=0 upto nb :
    x@[i]:=(a+i*(b-a)/nb);
    x:=x@[i];
    y@[i]:=texte;
    endfor ;
    Cb@:=(x@.0*x.u,y@.0*y.u)
    for i:=1 upto nb :
    ..(x@[i]*x.u,y@[i]*y.u)
    endfor;
    Cb@:=Cb@ shifted (Origine*cm);
    Courbe=Cb@;
    Courbe
    enddef;

    if Grille:
    drawoptions(withcolor 0.75white);
    for k=xpart(Origine) step grillex until xmax:
    trace u*(k,ymin)--u*(k,ymax);
    endfor;
    for k=xpart(Origine) step -grillex until xmin:
    trace u*(k,ymin)--u*(k,ymax);
    endfor;
    for k=ypart(Origine) step grilley until ymax:
    trace u*(xmin,k)--u*(xmax,k);
    endfor;
    for k=ypart(Origine) step -grilley until ymin:
    trace u*(xmin,k)--u*(xmax,k);
    endfor;
    drawoptions();
    fi;
    if Graduations:
    for k=gradx step gradx until bornesup:%xmax*gradx/grillex:
    dotlabel.bot(TEX("\num{"&decimal(k)&"}"),(k*x.u+xpart(Origine*cm),ypart(Origine*cm)));
    endfor;
    for k=-gradx step -gradx until borneinf:%xmin*gradx/grillex:
    dotlabel.bot(TEX("\num{"&decimal(k)&"}"),(k*x.u+xpart(Origine*cm),ypart(Origine*cm)));
    endfor;
    for k=grady step grady until ymax*grady/grilley:
    dotlabel.lft(TEX("\num{"&decimal(k)&"}"),(xpart(Origine*cm),k*y.u+ypart(Origine*cm)));
    endfor;
    for k=-grady step -grady until ymin*grady/grilley:
    dotlabel.lft(TEX("\num{"&decimal(k)&"}"),(xpart(Origine*cm),k*y.u+ypart(Origine*cm)));
    endfor;
    fi;

    drawoptions(withpen pencircle scaled(1));
    drawarrow (u*(0,ymin)--u*(0,ymax)) shifted (u*(xpart(Origine),0));
    drawarrow (u*(xmin,0)--u*(xmax,0)) shifted (u*(0,ypart(Origine)));
    label.llft(btex 0 etex,u*Origine);
    drawoptions();
    draw courbe1(borneinf,bornesup,100)(#2) withpen (pencircle scaled Epaisseur) withcolor colortrace;
    % labelisation
    numeric t;
    t=pos*length Cb1;
    pair PT,Tangente;
    PT:=point (pos*length Cb1) of Cb1;
    Tangente:=unitvector(direction t of Cb1);
    label(TEX("\useKV[TraceG]{NomCourbe}") rotated angle(Tangente),PT+2mm*(Tangente rotated 90));
    % fin labelisation
    clip currentpicture to polygone(u*(xmin,ymin),u*(xmax,ymin),u*(xmax,ymax),u*(xmin,ymax));
    label.rt(btex \useKV[TraceG]{LabelX} etex,u*(xmax,ypart(Origine)));
    label.top(btex \useKV[TraceG]{LabelY} etex,u*(xpart(Origine),ymax));
    if \useKV[TraceG]{Code}:
    \useKV[TraceG]{Traces}
    fi;
  \end{mplibcode}
  \else
  \mpxcommands{%
    \usepackage{ProfCollege}
    \setKV[TraceG]{#1}
  }
  \begin{mpost}[mpsettings={borneinf=\useKV[TraceG]{Bornea};bornesup=\useKV[TraceG]{Borneb};xmin=\useKV[TraceG]{Xmin};xmax=\useKV[TraceG]{Xmax};ymin=\useKV[TraceG]{Ymin};ymax=\useKV[TraceG]{Ymax};pasx=\useKV[TraceG]{Xstep};pasy=\useKV[TraceG]{Ystep};xu=1cm/\useKV[TraceG]{Xstep};yu=1cm/\useKV[TraceG]{Ystep};grillex=\useKV[TraceG]{PasGrilleX};grilley=\useKV[TraceG]{PasGrilleY};pos=\useKV[TraceG]{LabelC};Epaisseur=\useKV[TraceG]{Epaisseur}; color colortrace;colortrace=\useKV[TraceG]{CouleurTrace};boolean Grille;Grille=\useKV[TraceG]{Grille};boolean Graduations;Graduations=\useKV[TraceG]{Graduations};
    pair Origine;
    Origine=(xmin,ymin)+\useKV[TraceG]{Origine};}]

    vardef sin(expr t) = sind(c*t) enddef;

    vardef cos(expr t) = cosd(c*t) enddef;
    
    vardef tan(expr t) = sin(t)/cos(t) enddef;
   
    vardef exp(expr t) = e**t enddef;
   
    vardef ch(expr x)=(exp(x)+exp(-x))/2 enddef;
    
    vardef sh(expr x)=(exp(x)-exp(-x))/2 enddef;
    
    vardef ln(expr t) = mlog(t)/256 enddef;
    
    vardef arcsin(expr x)=%Définition mathématique en radian
    pi*angle((sqrt(1-x**2),x))/180
    enddef;
    
    vardef arccos(expr x)=%Définition mathématique en radian
    pi*angle((x,sqrt(1-x**2)))/180
    enddef;
    
    path Cb[];
    
    vardef courbe[](expr a,b,nb)(text texte)=
    path Courbe;
    for i:=0 upto nb :
    x@[i]:=(a+i*(b-a)/nb);
    x:=x@[i];
    y@[i]:=texte;
    endfor ;
    Cb@:=(x@.0*xu,y@.0*yu)
    for i:=1 upto nb :
    ..(x@[i]*xu,y@[i]*yu)
    endfor;
    Cb@:=Cb@ shifted (Origine*cm);
    Courbe=Cb@;
    Courbe
    enddef;

    if Grille:
    drawoptions(withcolor 0.75white);
    for k=xpart(Origine) step grillex until xmax:
    trace u*(k,ymin)--u*(k,ymax);
    endfor;
    for k=xpart(Origine) step -grillex until xmin:
    trace u*(k,ymin)--u*(k,ymax);
    endfor;
    for k=ypart(Origine) step grilley until ymax:
    trace u*(xmin,k)--u*(xmax,k);
    endfor;
    for k=ypart(Origine) step -grilley until ymin:
    trace u*(xmin,k)--u*(xmax,k);
    endfor;
    drawoptions();
    fi;
    if Graduations:
    for k=1 upto xmax/grillex:
    dotlabel.bot(LATEX("\num{"&decimal(k)&"}"),(k*xu+xpart(Origine*cm),ypart(Origine*cm)));
    endfor;
    for k=-1 downto xmin/grillex:
    dotlabel.bot(LATEX("\num{"&decimal(k)&"}"),(k*xu+xpart(Origine*cm),ypart(Origine*cm)));
    endfor;
    for k=1 upto ymax/grilley:
    dotlabel.lft(LATEX("\num{"&decimal(k)&"}"),(xpart(Origine*cm),k*yu+ypart(Origine*cm)));
    endfor;
    for k=-1 downto ymin/grilley:
    dotlabel.lft(LATEX("\num{"&decimal(k)&"}"),(xpart(Origine*cm),k*yu+ypart(Origine*cm)));
    endfor;
    fi;
    drawoptions(withpen pencircle scaled1.5);
    drawarrow (u*(0,ymin)--u*(0,ymax)) shifted (u*(xpart(Origine),0));
    drawarrow (u*(xmin,0)--u*(xmax,0)) shifted (u*(0,ypart(Origine)));
    drawoptions();
    draw courbe1(borneinf,bornesup,100)(#2) withpen (pencircle scaled Epaisseur) withcolor colortrace;
%    % labelisation
    numeric t;
    t=pos*length Cb1;
    pair PT,Tangente;
    PT:=point (pos*length Cb1) of Cb1;
    Tangente:=unitvector(direction t of Cb1);
    label(btex \noexpand\useKV[TraceG]{NomCourbe} etex rotated angle(Tangente),PT+2mm*(Tangente rotated 90));
%    % fin labelisation
    clip currentpicture to polygone(u*(xmin,ymin),u*(xmax,ymin),u*(xmax,ymax),u*(xmin,ymax));
    label.rt(btex \useKV[TraceG]{LabelX} etex,u*(xmax,ypart(Origine)));
    label.top(btex \useKV[TraceG]{LabelY} etex,u*(xpart(Origine),ymax));
  \end{mpost}
  \fi
}

%%%
% Formules
%%%
\setKVdefault[ClesFormule]{Perimetre=false,Aire=false,Volume=false,Surface=carr\'e,Solide=pav\'e,Angle=0,Ancre={(0,0)},Largeur=5cm,Couleur=white,EchelleEspace=70,Echelle=1cm}

\def\MPFigureCarre{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2,0);
    C=rotation(A,B,-90);
    D-C=A-B;
    draw polygone(A,B,C,D);
    draw codeperp(A,B,C,5);
    draw codeperp(B,C,D,5);
    draw codeperp(C,D,A,5);
    draw codeperp(D,A,B,5);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,B,C,C,D,D,A,2);
    marque_s:=marque_s*3;
    draw appelation(A,B,-3mm,btex $c$ etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2,0);
    C=rotation(A,B,-90);
    D-C=A-B;
    draw polygone(A,B,C,D);
    draw codeperp(A,B,C,5);
    draw codeperp(B,C,D,5);
    draw codeperp(C,D,A,5);
    draw codeperp(D,A,B,5);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,B,C,C,D,D,A,2);
    marque_s:=marque_s*3;
    draw appelation(A,B,-3mm,btex $c$ etex);
  \end{mpost}
  \fi
}

\def\MPFigurePolygone{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    pair A,B,C,D,E,F;
    A=u*(1,1);
    B-A=u*(2,0);
    C=3/5[B,rotation(A,B,-120)];
    D-C=u*(0,1);
    E-D=u*(-1.25,-1);
    F-E=u*(-1,1);
    draw polygone(A,B,C,D,E,F);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    pair A,B,C,D,E,F;
    A=u*(1,1);
    B-A=u*(2,0);
    C=3/5[B,rotation(A,B,-120)];
    D-C=u*(0,1);
    E-D=u*(-1.25,-1);
    F-E=u*(-1,1);
    draw polygone(A,B,C,D,E,F);
  \end{mpost}
  \fi
}

\def\MPFigureParallelogramme{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesFormule]{Echelle};
    vardef marque_para(expr dd,ee,pa)=
  save im;
  picture im;
  pair kk,ll,mn,mo;
  kk=point(pa*length dd) of dd;
  ll=projection(kk,point(0.25*length ee) of ee,point(0.5*length ee) of ee);
  mn=iso(kk,ll);
  mo=(mn--kk) intersectionpoint cercles(mn,3mm);
  im=image(
    drawarrow mo--kk;
    drawarrow symetrie(mo,mn)--ll;
    label(btex $//$ etex,mn);
    );
  im
  enddef;
     
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2.25,0.25);
    D=4/5[A,rotation(B,A,40)];
    C-D=B-A;
    draw polygone(A,B,C,D);
    drawoptions(withcolor gris);
    draw marque_para(droite(A,B),droite(C,D),0.455);
    draw marque_para(droite(B,C),droite(A,D),0.43);
    draw segment(B,2.5[C,B]) dashed evenly;
    draw segment(A,1.5[D,A]) dashed evenly;
    draw segment(A,1.55[B,A]) dashed evenly;
    draw segment(D,2[C,D]) dashed evenly;
    drawoptions();
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    vardef marque_para(expr dd,ee,pa)=
  save im;
  picture im;
  pair kk,ll,mn,mo;
  kk=point(pa*length dd) of dd;
  ll=projection(kk,point(0.25*length ee) of ee,point(0.5*length ee) of ee);
  mn=iso(kk,ll);
  mo=(mn--kk) intersectionpoint cercles(mn,3mm);
  im=image(
    drawarrow mo--kk;
    drawarrow symetrie(mo,mn)--ll;
    label(btex $//$ etex,mn);
    );
  im
  enddef;
  
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2.25,0.25);
    D=4/5[A,rotation(B,A,40)];
    C-D=B-A;
    draw polygone(A,B,C,D);
    drawoptions(withcolor gris);
    draw marque_para(droite(A,B),droite(C,D),0.455);
    draw marque_para(droite(B,C),droite(A,D),0.43);
    draw segment(B,2.5[C,B]) dashed evenly;
    draw segment(A,1.5[D,A]) dashed evenly;
    draw segment(A,1.55[B,A]) dashed evenly;
    draw segment(D,2[C,D]) dashed evenly;
    drawoptions();
  \end{mpost}
  \fi
}

\def\MPFigureParallelogrammeAire{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,10u,5u);
    pair A,B,C,D,I,J;
    A=u*(1,1);
    B-A=u*(2,0.5);
    D=3/5[A,rotation(B,A,40)];
    C-D=B-A;
    I=projection(D,A,B);
    draw polygone(A,B,C,D) withcolor gris;
    draw segment(A,B);
    draw segment(D,I);
    draw codeperp(D,I,B,5);
    A:=A+3*u*(1,0);
    B:=A+u*(2,0.5);
    D:=3/5[A,rotation(B,A,40)];
    C:=D+B-A;
    J=projection(B,A,D);
    draw polygone(A,B,C,D) withcolor gris;
    draw segment(D,1.5[A,D]) dashed evenly withcolor gris;
    draw segment(A,D);
    draw segment(B,J);
    draw codeperp(B,J,A,5);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,10u,5u);
    pair A,B,C,D,I,J;
    A=u*(1,1);
    B-A=u*(2,0.5);
    D=3/5[A,rotation(B,A,40)];
    C-D=B-A;
    I=projection(D,A,B);
    draw polygone(A,B,C,D) withcolor gris;
    draw segment(A,B);
    draw segment(D,I);
    draw codeperp(D,I,B,5);
    A:=A+3*u*(1,0);
    B:=A+u*(2,0.5);
    D:=3/5[A,rotation(B,A,40)];
    C:=D+B-A;
    J=projection(B,A,D);
    draw polygone(A,B,C,D) withcolor gris;
    draw segment(D,1.5[A,D]) dashed evenly withcolor gris;
    draw segment(A,D);
    draw segment(B,J);
    draw codeperp(B,J,A,5);
  \end{mpost}
  \fi
}

\def\MPFigureSphere{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    typetrace:="3D";
    Initialisation(5,0,10,\useKV[ClesFormule]{EchelleEspace});
    color O,A,B,C;
    O=(0,0,0);
    A-O=(0,1/2,0);
    C-O=(-1/2,0,0);
    B-O=(0,0,1/2);
    path cc,cd;
    cc=cercles(O,A,O,A,C);
    cd=cercles(O,A,O,A,B);
    draw cd;
    draw (subpath(0,length cc/2) of cc) dashed evenly;
    draw subpath(length cc/2,length cc) of cc;
    draw cotationmil(O,A,0,18,btex rayon $r$ etex);
    marque_p:="plein";
    pointe(O);
    marque_p:="non";
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    typetrace:="3D";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,0,10,v);
    color O,A,B,C;
    O=(0,0,0);
    A-O=(0,1/2,0);
    C-O=(-1/2,0,0);
    B-O=(0,0,1/2);
    path cc,cd;
    cc=cercles(O,A,O,A,C);
    cd=cercles(O,A,O,A,B);
    draw cd;
    draw (subpath(0,length cc/2) of cc) dashed evenly;
    draw subpath(length cc/2,length cc) of cc;
    draw cotationmil(O,A,0,18,btex rayon $r$ etex);
    marque_p:="plein";
    pointe(O);
    marque_p:="non";
  \end{mpost}
  \fi
}

\def\MPFigurePave{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,30,20,115);
    color A,B,C,D,E,F,G,H;
    draw Pave(A,B,C,D,E,F,G,H)(0.5,1,1/3) withcolor gris;
    draw segment(A,B);
    draw segment(E,F);
    draw segment(A,F);
    draw appelation(A,B,-2mm,btex $\ell$ etex);
    draw appelation(F,E,2mm,btex $p$ etex);
    draw appelation(A,F,2mm,btex $h$ etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,30,20,115);
    color A,B,C,D,E,F,G,H;
    draw Pave(A,B,C,D,E,F,G,H)(0.5,1,1/3) withcolor gris;
    draw segment(A,B);
    draw segment(E,F);
    draw segment(A,F);
    draw appelation(A,B,-2mm,\btex $\ell$ etex);
    draw appelation(F,E,2mm,\btex $p$ etex);
    draw appelation(A,F,2mm,\btex $h$ etex);
  \end{mpost}
  \fi
}

\def\MPFigurePrisme{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,30,20,\useKV[ClesFormule]{EchelleEspace});
    color A,B,C,D,E,F,G,H;
    D=(0.75,0,0);
    G=(0,1,0);
    H=(0,0,0);
    A-D=(0,0,0.5);
    C-D=G-H;
    E-H=A-D;
    F-E=(0,0.6,0);
    B-A=F-E;
    NbS:=8;
    Sommet1:=A;
    Sommet2:=B;
    Sommet3:=C;
    Sommet4:=D;
    Sommet5:=E;
    Sommet6:=F;
    Sommet7:=G;
    Sommet8:=H;
    NF:=6;
    Fc[100]:=4;Fc[101]:=1;Fc[102]:=4;Fc[103]:=3;Fc[104]:=2;
    Fc[200]:=4;Fc[201]:=4;Fc[202]:=1;Fc[203]:=5;Fc[204]:=8;
    Fc[300]:=4;Fc[301]:=4;Fc[302]:=8;Fc[303]:=7;Fc[304]:=3;
    Fc[400]:=4;Fc[401]:=8;Fc[402]:=5;Fc[403]:=6;Fc[404]:=7;
    Fc[500]:=4;Fc[501]:=1;Fc[502]:=2;Fc[503]:=6;Fc[504]:=5;
    Fc[600]:=4;Fc[601]:=2;Fc[602]:=3;Fc[603]:=7;Fc[604]:=6;
    CoulTrace:=gris;
    DessineObjet;
    drawoptions(withcolor gris);
    draw codeperp(B,A,E,5);
    draw codeperp(A,B,F,5);
    draw codeperp(H,D,C,5);
    draw codeperp(D,C,G,5);
    drawoptions();
    draw polygone(A,B,C,D);
    draw hachurage(polygone(A,B,C,D),60,0.3,0);
    draw segment(A,E);
    draw appelation(A,E,3mm,btex hauteur etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,30,20,115);
    color A,B,C,D,E,F,G,H;
    D=(0.75,0,0);
    G=(0,1,0);
    H=(0,0,0);
    A-D=(0,0,0.5);
    C-D=G-H;
    E-H=A-D;
    F-E=(0,0.6,0);
    B-A=F-E;
    NbS:=8;
    Sommet1:=A;
    Sommet2:=B;
    Sommet3:=C;
    Sommet4:=D;
    Sommet5:=E;
    Sommet6:=F;
    Sommet7:=G;
    Sommet8:=H;
    NF:=6;
    Fc[100]:=4;Fc[101]:=1;Fc[102]:=4;Fc[103]:=3;Fc[104]:=2;
    Fc[200]:=4;Fc[201]:=4;Fc[202]:=1;Fc[203]:=5;Fc[204]:=8;
    Fc[300]:=4;Fc[301]:=4;Fc[302]:=8;Fc[303]:=7;Fc[304]:=3;
    Fc[400]:=4;Fc[401]:=8;Fc[402]:=5;Fc[403]:=6;Fc[404]:=7;
    Fc[500]:=4;Fc[501]:=1;Fc[502]:=2;Fc[503]:=6;Fc[504]:=5;
    Fc[600]:=4;Fc[601]:=2;Fc[602]:=3;Fc[603]:=7;Fc[604]:=6;
    CoulTrace:=gris;
    DessineObjet;
    drawoptions(withcolor gris);
    draw codeperp(B,A,E,5);
    draw codeperp(A,B,F,5);
    draw codeperp(H,D,C,5);
    draw codeperp(D,C,G,5);
    drawoptions();
    draw polygone(A,B,C,D);
    draw hachurage(polygone(A,B,C,D),60,0.3,0);
    draw segment(A,E);
    draw appelation(A,E,3mm,btex hauteur etex);
  \end{mpost}
  \fi
}

\def\MPFigureCylindre{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,0,20,\useKV[ClesFormule]{EchelleEspace});
    color O,O',A,A',B,B',C,C';
    O=(0,0,0);
    O'-O=(0,0,1);
    A-O=(0,1,0);
    A'-A=O'-O;
    C=symetrie(A,O);
    C'-C=O'-O;
    B-O=(-1/2,0,0);
    B'-B=O'-O;
    path cc,cd;
    cc=cercles(O,A,O,A,B);
    cd=cercles(O',A',O',A',B');
    draw cd;
    draw segment(C,C');
    draw segment(A,A');
    draw (subpath(0,length cc/2) of cc) dashed evenly;
    draw subpath(length cc/2,length cc) of cc;
    draw segment(O,A);
    draw cotationmil(C,C',3mm,25,btex hauteur $h$ etex);
    draw appelation(O,A,2mm,btex rayon $r$ etex);
    marque_p:="croix";
    pointe(O);
    marque_p:="non";
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,0,20,70);
    color O,O',A,A',B,B',C,C';
    O=(0,0,0);
    O'-O=(0,0,1);
    A-O=(0,1,0);
    A'-A=O'-O;
    C=symetrie(A,O);
    C'-C=O'-O;
    B-O=(-1/2,0,0);
    B'-B=O'-O;
    path cc,cd;
    cc=cercles(O,A,O,A,B);
    cd=cercles(O',A',O',A',B');
    draw cd;
    draw segment(C,C');
    draw segment(A,A');
    draw (subpath(0,length cc/2) of cc) dashed evenly;
    draw subpath(length cc/2,length cc) of cc;
    draw segment(O,A);
    draw cotationmil(C,C',3mm,25,btex hauteur $h$ etex);
    draw appelation(O,A,2mm,btex rayon $r$ etex);
    marque_p:="croix";
    pointe(O);
    marque_p:="non";
  \end{mpost}
  \fi
}

\def\MPFigureCone{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,0,10,\useKV[ClesFormule]{EchelleEspace});
    color O,O',A,B,C;
    O=(0,0,0);
    O'-O=(0,0,1.5);
    A-O=(0,1,0);
    C=symetrie(A,O);
    B-O=(-1/2,0,0);
    path cc;
    cc=cercles(O,A,O,A,B);
    draw chemin(C,O',A);
    draw (subpath(0,length cc/2) of cc) dashed evenly;
    draw subpath(length cc/2,length cc) of cc;
    draw chemin(O',O,A);
    draw appelation(O,O',2mm,btex hauteur etex);
    draw appelation(O,A,1mm,btex rayon $r$ etex);
    marque_p:="croix";
    pointe(O);
    marque_p:="non";
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,0,10,70);
    color O,O',A,B,C;
    O=(0,0,0);
    O'-O=(0,0,1.5);
    A-O=(0,1,0);
    C=symetrie(A,O);
    B-O=(-1/2,0,0);
    path cc;
    cc=cercles(O,A,O,A,B);
    draw chemin(C,O',A);
    draw (subpath(0,length cc/2) of cc) dashed evenly;
    draw subpath(length cc/2,length cc) of cc;
    draw chemin(O',O,A);
    draw appelation(O,O',2mm,btex hauteur etex);
    draw appelation(O,A,1mm,btex rayon $r$ etex);
    marque_p:="croix";
    pointe(O);
    marque_p:="non";
  \end{mpost}
  \fi
}

\def\MPFigurePyramide{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    u:=0.5cm;
    z0=(-0.5,0)*u;
    z1=(2.5,0.5)*u;
    z2=(4,2)*u;
    z3=(-0.5,2.75)*u;
    z4=(-3,1.5)*u;
    z5=(0.5,6)*u;
    z6=(0.5,1.5)*u;
    z7=z6 shifted (5u,0);
    draw z5--z0 withcolor gris;
    draw z5--z1 withcolor gris;
    draw z5--z2 withcolor gris;
    draw z5--z4 withcolor gris;
    draw z5--z3 dashed evenly withcolor gris;
    draw hachurage(polygone(z4,z0,z1,z2,z3,z4),60,0.4,0);
    remplis codeperp(z7,z6,z5,8)--z6--cycle withcolor white;
    draw z4--z0--z1--z2;
    draw z2--z3--z4 dashed evenly;
    draw z5--z6 dashed evenly;
    draw codeperp(z7,z6,z5,8);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    Figure(-10u,-10u,10u,10u);
    u:=0.5cm;
    z0=(-0.5,0)*u;
    z1=(2.5,0.5)*u;
    z2=(4,2)*u;
    z3=(-0.5,2.75)*u;
    z4=(-3,1.5)*u;
    z5=(0.5,6)*u;
    z6=(0.5,1.5)*u;
    z7=z6 shifted (5u,0);
    draw z5--z0 withcolor gris;
    draw z5--z1 withcolor gris;
    draw z5--z2 withcolor gris;
    draw z5--z4 withcolor gris;
    draw z5--z3 dashed evenly withcolor gris;
    draw hachurage(polygone(z4,z0,z1,z2,z3,z4),60,0.4,0);
    remplis codeperp(z7,z6,z5,8)--z6--cycle withcolor white;
    draw z4--z0--z1--z2;
    draw z2--z3--z4 dashed evenly;
    draw z5--z6 dashed evenly;
    draw codeperp(z7,z6,z5,8);
  \end{mpost}
  \fi
}

\def\MPFigureCube{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    drawoptions( dashed dashpattern(on1cm));
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,30,20,80);
    color A,B,C,D,E,F,G,H;
    draw Cube(A,B,C,D,E,F,G,H) withcolor gris;
    draw segment(E,H);
    draw appelation(E,H,2mm,btex $a$ etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={v:=\useKV[ClesFormule]{EchelleEspace};}]
    typetrace:="3D";
    typerepre:="persp";
    Figure(-10u,-10u,10u,10u);
    Initialisation(5,30,20,80);
    color A,B,C,D,E,F,G,H;
    draw Cube(A,B,C,D,E,F,G,H) withcolor gris;
    draw segment(E,H);
    draw appelation(E,H,2mm,btex $a$ etex);
  \end{mpost}
  \fi
}

\def\MPFigureLosange{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2,0.5);
    D=rotation(B,A,40);
    C-D=B-A;
    draw polygone(A,B,C,D);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,B,C,C,D,D,A,2);
    marque_s:=marque_s*3;
    draw appelation(A,B,-3mm,btex $c$ etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2,0.5);
    D=rotation(B,A,40);
    C-D=B-A;
    draw polygone(A,B,C,D);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,B,C,C,D,D,A,2);
    marque_s:=marque_s*3;
    draw appelation(A,B,-3mm,btex $c$ etex);
  \end{mpost}
  \fi
}

\def\MPFigureLosangeAire{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2,0.5);
    D=rotation(B,A,40);
    C-D=B-A;
    draw polygone(A,B,C,D) withcolor gris;
    draw segment(A,C);
    draw segment(B,D);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,B,C,C,D,D,A,2);
    marque_s:=marque_s*3;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(2,0.5);
    D=rotation(B,A,40);
    C-D=B-A;
    draw polygone(A,B,C,D) withcolor gris;
    draw segment(A,C);
    draw segment(B,D);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,B,C,C,D,D,A,2);
    marque_s:=marque_s*3;
  \end{mpost}
  \fi
}

\def\MPFigureRectangle{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(3,0);
    C=2/3[B,rotation(A,B,-90)];
    D-C=A-B;
    draw polygone(A,B,C,D);
    draw codeperp(A,B,C,5);
    draw codeperp(B,C,D,5);
    draw codeperp(C,D,A,5);
    draw codeperp(D,A,B,5);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,C,D,2);
    draw Codelongueur(A,D,C,B,5);
    marque_s:=marque_s*3;
    draw appelation(A,B,-3mm,btex $L$ etex);
    label.lft(btex $\ell$ etex,iso(A,D));
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    pair A,B,C,D;
    A=u*(1,1);
    B-A=u*(3,0);
    C=2/3[B,rotation(A,B,-90)];
    D-C=A-B;
    draw polygone(A,B,C,D);
    draw codeperp(A,B,C,5);
    draw codeperp(B,C,D,5);
    draw codeperp(C,D,A,5);
    draw codeperp(D,A,B,5);
    marque_s:=marque_s/3;
    draw Codelongueur(A,B,C,D,2);
    draw Codelongueur(A,D,C,B,5);
    marque_s:=marque_s*3;
    draw appelation(A,B,-3mm,btex $L$ etex);
    label.lft(btex $\ell$ etex,iso(A,D));
  \end{mpost}
  \fi
}

\def\MPFigureTriangle{%
    \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,5u,5u);
    pair A,B,C;
    A=u*(1,1);
    B-A=u*(3,0);
    C=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    draw polygone(A,B,C);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,5u,5u);
    pair A,B,C;
    A=u*(1,1);
    B-A=u*(3,0);
    C=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    draw polygone(A,B,C);
  \end{mpost}
  \fi
}

\def\MPFigureCercle{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,5u,5u);
    pair A,B,C;
    A=u*(2.5,2.5);
    path cc;
    cc=cercles(A,1.25u);
    B=pointarc(cc,195);
    C=symetrie(B,A);
    draw cc withcolor gris;
    draw segment(B,C);
    marque_p:="croix";
    pointe(A);
    draw appelation(B,C,3mm,btex diam\`etre etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,5u,5u);
    pair A,B,C;
    A=u*(2.5,2.5);
    path cc;
    cc=cercles(A,1.25u);
    B=pointarc(cc,195);
    C=symetrie(B,A);
    draw cc withcolor gris;
    draw segment(B,C);
    marque_p:="croix";
    pointe(A);
    draw appelation(B,C,3mm,\btex diam\`etre etex);
  \end{mpost}
  \fi
}

\def\MPFigureDisque{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    Figure(-5u,-5u,5u,5u);
    pair A,B,C;
    A=u*(2.5,2.5);
    path cc;
    cc=cercles(A,1.25u);
    B=pointarc(cc,195);
    C=symetrie(B,A);
    draw cc withcolor gris;
    draw segment(A,C);
    marque_p:="croix";
    pointe(A);
    draw appelation(A,C,3mm,btex rayon $r$ etex);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,5u,5u);
    pair A,B,C;
    A=u*(2.5,2.5);
    path cc;
    cc=cercles(A,1.25u);
    B=pointarc(cc,195);
    C=symetrie(B,A);
    draw cc withcolor gris;
    draw segment(A,C);
    marque_p:="croix";
    pointe(A);
    draw appelation(A,C,3mm,\btex rayon $r$ etex);
  \end{mpost}
  \fi
}

\def\MPFigureTriangleAire{%
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
u:=\useKV[ClesFormule]{Echelle};
    drawoptions( dashed dashpattern(on1cm));
    pair A,B,C,H,I,J;
    A=u*(0.5,1);
    B-A=u*(1.4,0);
    C=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    H=projection(C,A,B);
    I=projection(A,B,C);
    J=projection(B,C,A);
    draw polygone(A,B,C) withcolor gris;
    drawoptions();
    draw segment(C,H);
    draw segment(A,B);
    draw codeperp(C,H,B,5);
    drawoptions();
    A:=A+u*(2.5,0);
    B:=A+u*(1.4,0);
    C:=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    I:=projection(A,B,C);
    J:=projection(B,C,A);
    draw polygone(A,B,C) withcolor gris;
    drawoptions();
    draw segment(A,I);
    draw segment(C,B);
    draw codeperp(A,I,B,5);
    drawoptions();
    A:=A-u*(1.25,1);
    B:=A+u*(1.4,0);
    C:=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    J:=projection(B,C,A);
    draw polygone(A,B,C) withcolor gris;
    drawoptions();
    draw segment(B,J);
    draw segment(C,A);
    draw codeperp(B,J,C,5);
    drawoptions();
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={u:=\useKV[ClesFormule]{Echelle};}]
    Figure(-5u,-5u,5u,5u);
    pair A,B,C,H,I,J;
    A=u*(0.5,1);
    B-A=u*(1.4,0);
    C=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    H=projection(C,A,B);
    I=projection(A,B,C);
    J=projection(B,C,A);
    draw polygone(A,B,C) withcolor gris;
    drawoptions();
    draw segment(C,H);
    draw segment(A,B);
    draw codeperp(C,H,B,5);
    drawoptions();
    A:=A+u*(2.5,0);
    B:=A+u*(1.4,0);
    C:=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    I:=projection(A,B,C);
    J:=projection(B,C,A);
    draw polygone(A,B,C) withcolor gris;
    drawoptions();
    draw segment(A,I);
    draw segment(C,B);
    draw codeperp(A,I,B,5);
    drawoptions();
    A:=A-u*(1.25,1);
    B:=A+u*(1.4,0);
    C:=demidroite(A,rotation(B,A,60)) intersectionpoint demidroite(B,rotation(A,B,-45));
    J:=projection(B,C,A);
    draw polygone(A,B,C) withcolor gris;
    drawoptions();
    draw segment(B,J);
    draw segment(C,A);
    draw codeperp(B,J,C,5);
    drawoptions();
  \end{mpost}
  \fi
}%

\newcommand\Formule[1][]{%
  \useKVdefault[ClesFormule]%
  \setKV[ClesFormule]{#1}%
  \setlength{\RoundedBoxWidth}{\useKV[ClesFormule]{Largeur}}%
  \xdef\ColorFill{\useKV[ClesFormule]{Couleur}}%
  \ifboolKV[ClesFormule]{Perimetre}{%
    \begin{tikzpicture}[remember picture, overlay]
      \node[draw,fill=\ColorFill,dashed,rounded corners,rotate={\useKV[ClesFormule]{Angle}}] (test) at \useKV[ClesFormule]{Ancre} {\begin{minipage}{\RoundedBoxWidth}%
          \IfStrEqCase{\useKV[ClesFormule]{Surface}}{%
            {carre}{\begin{center}
                \MPFigureCarre\par
                P\'erim\`etre d'un carr\'e :\par$4\times c$
              \end{center}}%
            {polygone}{%
              \begin{center}
                \MPFigurePolygone\par
                P\'erim\`etre d'un polygone : \par$\text{Somme des c\^ot\'es}$
              \end{center}
            }%
            {rectangle}{%
              \begin{center}
                \MPFigureRectangle\par
                P\'erim\`etre d'un rectangle : \par$2\times(L+\ell)$
              \end{center}
              }%
              {losange}{%
                \begin{center}
                \MPFigureLosange\par
                P\'erim\`etre d'un losange : \par$4\times c$
              \end{center}
              }%
            {triangle}{%
              \begin{center}
                \MPFigureTriangle\par
                P\'erim\`etre d'un triangle : \par Somme des c\^ot\'es
              \end{center}
            }%
            {cercle}{%
              \begin{center}
                \MPFigureCercle\par
                P\'erim\`etre d'un cercle : \par$\pi\times\text{diam\`etre}$
              \end{center}
            }%
            {parallelogramme}{%
              \begin{center}
                \MPFigureParallelogramme\par
                P\'erim\`etre d'un parall\'elogramme : \par Somme des c\^ot\'es
              \end{center}
            }}
        \end{minipage}};
    \end{tikzpicture}
  }{\ifboolKV[ClesFormule]{Aire}{%
      \begin{tikzpicture}[remember picture, overlay]
        \node[draw,fill=\ColorFill,dashed,rounded corners=2,rotate={\useKV[ClesFormule]{Angle}}] (test) at \useKV[ClesFormule]{Ancre} {\begin{minipage}{\RoundedBoxWidth}%
            \IfStrEqCase{\useKV[ClesFormule]{Surface}}{%
              {carre}{\begin{center}
                  \MPFigureCarre\par
                  Aire d'un carr\'e :\par$c\times c$
              \end{center}}%
            {rectangle}{%
              \begin{center}
                  \MPFigureRectangle\par
                  Aire d'un rectangle :\par$L\times\ell$
              \end{center}
              }%
              {losange}{%
                \begin{center}
                  \MPFigureLosangeAire\par
                  Aire d'un losange :\par$\dfrac{\text{grande diagonale}\times\text{petite diagonale}}{2}$
              \end{center}
              }%
            {triangle}{%
              \begin{center}
                \MPFigureTriangleAire\par\vspace{1em}\par
                Aire d'un triangle : $\displaystyle\frac{\text{c\^ot\'e}\times\text{hauteur relative \`a ce c\^ot\'e}}{2}$
              \end{center}
            }%
            {disque}{%
              \begin{center}
                \MPFigureDisque\par
                Aire d'un disque :\par$\pi\times r\times r$
              \end{center}
            }%
            {parallelogramme}{%
              \begin{center}
                \MPFigureParallelogrammeAire\par
                Aire d'un parall\'elogramme : $\text{c\^ot\'e}\times\text{hauteur relative \`a ce c\^ot\'e}$
                \end{center}
            }
            {sphere}{%
              \begin{center}
                \MPFigureSphere\par
                Aire d'une sph\`ere : $4\times\pi\times r^2$
              \end{center}
            }}
        \end{minipage}};
    \end{tikzpicture}
    }{%Volume
      \begin{tikzpicture}[remember picture, overlay]
        \node[draw,fill=\ColorFill,dashed,rounded corners=2,rotate={\useKV[ClesFormule]{Angle}}] (test) at \useKV[ClesFormule]{Ancre} {\begin{minipage}{\RoundedBoxWidth}%
            \IfStrEqCase{\useKV[ClesFormule]{Solide}}{%
              {boule}{\begin{center}
                \MPFigureSphere\par
                Volume d'une boule : $\dfrac{4\times\pi\times r^3}{3}$
              \end{center}}%
            {cube}{%
              \begin{center}
                \MPFigureCube\par
                Volume d'une cube : $a^3\quad(a\times a\times a)$
              \end{center}
            }%
              {pave}{%
                \begin{center}
                  \MPFigurePave\par
                  Volume d'un pav\'e droit : $\ell\times h\times p$
              \end{center}
              }
              {prisme}{%
                \begin{center}
                  \MPFigurePrisme\par
                  Volume d'un prisme droit : $\text{Aire de la base}\times\mbox{hauteur}$
                \end{center}
              }
              {cylindre}{%
                \begin{center}
                  \MPFigureCylindre\par
                  Volume d'un cylindre de r\'evolution : $\pi\times r^2\times h$
                \end{center}
              }
              {pyramide}{%
                \begin{center}
                  \MPFigurePyramide\par
                  Volume d'une pyramide : $\dfrac{\text{Aire de la base}\times\text{hauteur}}{3}$
                \end{center}
              }
              {cone}{%
                \begin{center}
                  \MPFigureCone\par
                  Volume d'un c\^one de r\'evolution : $\displaystyle\dfrac{\pi\times r^2\times h}{3}$
                \end{center}
              }
              }
          \end{minipage}};
      \end{tikzpicture}
    }
  }
}

%%%
% Proba
%%%
\setKVdefault[ClesProba]{Echelle=false,Arbre=false,Branche=2,Angle=60,Rayon=0.25,LongueurEchelle=5,Affichage=0,Grille=1,Incline}

\def\Updatetoksproba#1/#2\nil{\addtotok\toklistepointproba{"#1","\footnotesize #2",}}
\def\Updatetoksprobapdf#1/#2\nil{\addtotok\toklistepointproba{"#1","\noexpand\footnotesize #2",}}
\def\Updatetoksprobaechelle#1/#2/#3\nil{\addtotok\toklistepointproba{#1,#2,"#3",}}

\newtoks\toklistepointproba

% Pour construire l'arbre de probabilit\'e
\def\buildarbreproba{%
  \toklistepointproba{}%
  \ifluatex
  \foreachitem\compteur\in\ListeProba{\expandafter\Updatetoksproba\compteur\nil}%
  \else
  \foreachitem\compteur\in\ListeProba{\expandafter\Updatetoksprobapdf\compteur\nil}%
  \fi
  \MPArbreProba{\useKV[ClesProba]{Branche}}{\useKV[ClesProba]{Angle}}{\the\toklistepointproba}{\useKV[ClesProba]{Rayon}}%
}%

% Pour construire l'\'echelle de probabilit\'e
\def\buildechelleproba{%
  \toklistepointproba{}%
  \foreachitem\compteur\in\ListeProba{\expandafter\Updatetoksprobaechelle\compteur\nil}%
  \MPEchelleProbaUn{\useKV[ClesProba]{LongueurEchelle}}{\the\toklistepointproba}{\useKV[ClesProba]{Affichage}}{\useKV[ClesProba]{Grille}}%
}

\def\MPEchelleProbaUn#1#2#3#4{%
  % #1:longueur du segment repr\'esentant l'\'echelle
  % #2:Liste des \'ev\`enements/proba
  % #3: pour l'affichage des labels (0 : rien, 1: fleches, 2 : fleches+ev\`enements, 3: fleches+proba, 4 : tout)
  % #4 : dimension de "la grille" associ\'ee
  \ifluatex
  \begin{mplibcode}
    pair A,B,C[],D[];%les noeuds de l'arbre
    %Figure(-10u,-10u,10u,10u);
    A=u*(1,1);
    B-A=u*(#1,0);
    draw segment(A,B);
    draw marquesegment(A,B);
    marque_s:=marque_s/2;
    if #4>1:
      for k=0 upto (#4-1):
        D[k]=(k/#4)[A,B];
      endfor;
      if (#4 mod 2)=0:
        for k=0 step 2 until (#4-1):
          draw marquesegment(D[k],D[k+1]);
        endfor;
      else:
        for k=1 step 2 until (#4-1):
          draw marquesegment(D[k],D[k+1]);
        endfor;
      fi;
    fi;
    marque_s:=marque_s*2;
    labeloffset:=labeloffset*3;
    label.bot(btex 0 etex,A);
    label.bot(btex 1 etex,B);
    labeloffset:=labeloffset/3;
    n:=1;%compter les informations
    k:=1;% compter les informations noeud pour les placer
    vardef toto(text t)=
      for p_=t:
        if (n mod 3)=1:
          num:=p_;
        fi;
        if (n mod 3)=2:
        deno:=p_;
        fi;
        if (n mod 3=0):
          C[k]=(num/deno)[A,B];
          if (#3>0):
          drawarrow (C[k]-u*(0,0.5))--(C[k]-u*(0,0.15));
          fi;
          if (#3=2) or (#3=4):
            dotlabel.top(TEX(p_),C[k]);
          fi;
          if (#3=1) or (#3=3):
            dotlabel.top("",C[k]);
          fi;
          if (#3>2):
            label.bot(TEX("$\frac{"&decimal(num)&"}{"&decimal(deno)&"}$"),C[k]-u*(0,0.5));
          fi;
          k:=k+1;
        fi;
      n:=n+1;
      endfor;
    enddef;
    toto(#2);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={input PfCGeometrie;}]
    pair A,B,C[],D[];%les noeuds de l'arbre
    Figure(-10u,-10u,10u,10u);
    A=u*(1,1);
    B-A=u*(#1,0);
    draw segment(A,B);
    draw marquesegment(A,B);
    marque_s:=marque_s/2;
    if #4>1:
      for k=0 upto (#4-1):
        D[k]=(k/#4)[A,B];
      endfor;
      if (#4 mod 2)=0:
        for k=0 step 2 until (#4-1):
          draw marquesegment(D[k],D[k+1]);
        endfor;
      else:
        for k=1 step 2 until (#4-1):
          draw marquesegment(D[k],D[k+1]);
        endfor;
      fi;
    fi;
    marque_s:=marque_s*2;
    labeloffset:=labeloffset*3;
    label.bot(btex 0 etex,A);
    label.bot(btex 1 etex,B);
    labeloffset:=labeloffset/3;
    n:=1;%compter les informations
    k:=1;% compter les informations noeud pour les placer
    vardef toto(text t)=
      for p_=t:
        if (n mod 3)=1:
          num:=p_;
        fi;
        if (n mod 3)=2:
        deno:=p_;
        fi;
        if (n mod 3=0):
          C[k]=(num/deno)[A,B];
          if (#3>0):
          drawarrow (C[k]-u*(0,0.5))--(C[k]-u*(0,0.15));
          fi;
          if (#3=2) or (#3=4):
            dotlabel.top(LATEX(p_),C[k]);
          fi;
          if (#3=1) or (#3=3):
            dotlabel.top("",C[k]);
          fi;
          if (#3>2):
            label.bot(LATEX("$\noexpand\frac{"&decimal(num)&"}{"&decimal(deno)&"}$"),C[k]-u*(0,0.5));%Le \noexpand est n\'ecessaire pour \'eviter un probl\`eme \`a la compilation, dû \`a l'expansion du \frac par gmp.
          fi;
          k:=k+1;
        fi;
      n:=n+1;
      endfor;
    enddef;
    toto(#2);
  \end{mpost}
  \fi
}

\def\MPArbreProba#1#2#3#4{%
  % #1:longueur d'une branche
  % #2:angle entre deux branches de m\^eme origine
  % #3:Liste des \'ev\`enements/proba
  \ifluatex
  \begin{mplibcode}
    boolean Incline;
    Incline=\useKV[ClesProba]{Incline};
    pair A[],B[];%les noeuds de l'arbre
    A0=u*(1,1);
    B0-A0=u*(#1,0);
    A1=rotation(B0,A0,#2/2);
    A2=rotation(B0,A0,-#2/2);
    B1-A1=B0-A0;
    A3=rotation(B1,A1,#2/3);
    A4=rotation(B1,A1,-#2/3);
    B2-A2=B0-A0;
    A5=rotation(B2,A2,#2/3);
    A6=rotation(B2,A2,-#2/3);
    draw segment(A4,A1);
    draw segment(A5,A2);
    draw chemin(A3,A1,A0,A2,A6);
    for k=1 upto 6:
    fill cercles(A[k],#4*cm) withcolor white;
    endfor;
    n:=1;%compter les informations
    k:=1;% compter les informations noeud pour les placer
    l:=1;% compter les informations "num\'eriques"
    vardef toto(text t)=
    for p_=t:
    if (n mod 2)=1:
    if p_<>"":
    label(TEX(p_),A[k]);
    fi;
    k:=k+1;
    else:
    if (l mod 2)=1:
    if p_<>"":
    if Incline:
    draw appelation(A[(l-1) div 2],A[l],4mm,TEX(p_));
    else:
    label.ulft(TEX(p_),iso(A[(l-1) div 2],A[l]));
    fi;
    fi;
    else:
    if p_<>"":
    if Incline:
    draw appelation(A[(l-1) div 2],A[l],-4mm,TEX(p_));
    else:
    label.llft(TEX(p_),iso(A[(l-1) div 2],A[l]));
    fi;
    fi;
    fi;
    l:=l+1;
    fi;
    n:=n+1;
    endfor;
    enddef;
    toto(#3);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={%input PfCGeometrie;
      boolean Incline; Incline=\useKV[ClesProba]{Incline};}]
    pair A[],B[];%les noeuds de l'arbre
    %Figure(-10u,-10u,10u,10u);
    A0=u*(1,1);
    B0-A0=u*(#1,0);
    A1=rotation(B0,A0,#2/2);
    A2=rotation(B0,A0,-#2/2);
    B1-A1=B0-A0;
    A3=rotation(B1,A1,#2/3);
    A4=rotation(B1,A1,-#2/3);
    B2-A2=B0-A0;
    A5=rotation(B2,A2,#2/3);
    A6=rotation(B2,A2,-#2/3);
    draw segment(A4,A1);
    draw segment(A5,A2);
    draw chemin(A3,A1,A0,A2,A6);
    for k=1 upto 6:
    fill cercles(A[k],#4*cm) withcolor white;
    endfor;
    n:=1;%compter les informations
    k:=1;% compter les informations noeud pour les placer
    l:=1;% compter les informations "num\'eriques"
    vardef toto(text t)=
    for p_=t:
    if (n mod 2)=1:
    if p_<>"":
    label(LATEX(p_),A[k]);
    fi;
    k:=k+1;
    else:
    if (l mod 2)=1:
    if p_<>"":
    if Incline:
    draw appelation(A[(l-1) div 2],A[l],4mm,LATEX(p_));
    else:
    label.ulft(LATEX(p_),iso(A[(l-1) div 2],A[l]));
    fi;
    fi;
    else:
    if p_<>"":
    if Incline:
    draw appelation(A[(l-1) div 2],A[l],-4mm,LATEX(p_));
    else:
    label.llft(LATEX(p_),iso(A[(l-1) div 2],A[l]));
    fi;
    fi;
    fi;
    l:=l+1;
    fi;
    n:=n+1;
    endfor;
    enddef;
    toto(#3);
  \end{mpost}
  \fi
}

\newcommand\Proba[2][]{%
  \useKVdefault[ClesProba]%
  \setKV[ClesProba]{#1}%
  % On liste les diff\'erents \'el\'ements sous la forme Ev\`enement/proba
  \setsepchar[*]{,*/}\ignoreemptyitems%
  \readlist*\ListeProba{#2}%
  \ifboolKV[ClesProba]{Echelle}{%
    \buildechelleproba%
  }{\ifboolKV[ClesProba]{Arbre}{%
      \buildarbreproba%
    }{}%
  }%
  \setsepchar{,}%
}%

%%%
% Reperage
%%%
\setKVdefault[ClesReperage]{Unitex=1,Pasx=1,Unitey=1,Pasy=1,Unitez=1,Pasz=1,DemiDroite=false,Droite=false,Plan=false,Trace=false,ListeSegment={},Espace=false,Sphere=false,AnglePhi=30,CouleurLa=white,CouleurLon=Tomato,AffichageNom=false,AffichageGrad=false,AffichageAbs=0,AffichageCoord=false,LectureCoord=false,ValeurUnitex=1,ValeurUnitey=1,ValeurOrigine=0,NomOrigine=O,EchelleEspace=50,CouleurCoord=black,Thermometre=false,Mercure=false,CouleurMercure=black,Celsius,Kelvin=false,Farenheit=false,ValeurMin=-4000,ValeurMax=4000,Etages=4,Code=false}
\defKV[ClesReperage]{Traces=\setKV[ClesReperage]{Code}}
% ValeurOrigine permet de faire des morceaux de demi-droite gradu\'ee en passant par droite :)

\def\Updatetoksdroite#1/#2\nil{\addtotok\toklistepointdroite{#1,"#2",}}
\def\Updatetoksdroite#1/#2\nil{\addtotok\toklistepointdroite{#1,"#2",}}
\def\Updatetoksdemidroite#1/#2\nil{\addtotok\toklistenompointdemidroite{"#2",}}
\def\Updatetoksrepere#1/#2/#3\nil{\addtotok\toklistepointrepere{#1,#2,"#3",}}
\def\Updatetoksespace#1/#2/#3/#4\nil{\addtotok\toklistepointespace{#1,#2,#3,"#4",}}

\newtoks\toklistepointrepere%
\newtoks\toklistepointdroite%
\newtoks\toklistepointdemidroite%
\newtoks\toklistenompointdemidroite%
\newtoks\toklistepointespace%

% Pour construire le rep\`ere de l'espace
\def\buildespace{%
  \toklistepointespace{}%
  \ifboolKV[ClesReperage]{Sphere}{%
    \foreachitem\compteur\in\ListePointEspace{\expandafter\Updatetoksrepere\compteur\nil}%
    \[\MPEspaceSphere{\the\toklistepointrepere}{\useKV[ClesReperage]{EchelleEspace}}\]
  }{%
    \foreachitem\compteur\in\ListePointEspace{\expandafter\Updatetoksespace\compteur\nil}%
    \ifboolKV[ClesReperage]{AffichageNom}{%
      \ifboolKV[ClesReperage]{AffichageCoord}{%
        \[\MPEspacePave{\useKV[ClesReperage]{Unitex}}{\useKV[ClesReperage]{Pasx}}{\useKV[ClesReperage]{Unitey}}{\useKV[ClesReperage]{Pasy}}{\useKV[ClesReperage]{Unitez}}{\useKV[ClesReperage]{Pasz}}{\the\toklistepointespace}{3}{\useKV[ClesReperage]{EchelleEspace}}\]%
      }{%
        \[\MPEspacePave{\useKV[ClesReperage]{Unitex}}{\useKV[ClesReperage]{Pasx}}{\useKV[ClesReperage]{Unitey}}{\useKV[ClesReperage]{Pasy}}{\useKV[ClesReperage]{Unitez}}{\useKV[ClesReperage]{Pasz}}{\the\toklistepointespace}{2}{\useKV[ClesReperage]{EchelleEspace}}\]%
      }%
    }{%
      \ifboolKV[ClesReperage]{AffichageCoord}{%
        \[\MPEspacePave{\useKV[ClesReperage]{Unitex}}{\useKV[ClesReperage]{Pasx}}{\useKV[ClesReperage]{Unitey}}{\useKV[ClesReperage]{Pasy}}{\useKV[ClesReperage]{Unitez}}{\useKV[ClesReperage]{Pasz}}{\the\toklistepointespace}{1}{\useKV[ClesReperage]{EchelleEspace}}\]%
      }{%
        \[\MPEspacePave{\useKV[ClesReperage]{Unitex}}{\useKV[ClesReperage]{Pasx}}{\useKV[ClesReperage]{Unitey}}{\useKV[ClesReperage]{Pasy}}{\useKV[ClesReperage]{Unitez}}{\useKV[ClesReperage]{Pasz}}{\the\toklistepointespace}{0}{\useKV[ClesReperage]{EchelleEspace}}\]%
      }%
    }%
  }%
}%

\def\MPEspaceSphere#1#2{%
  \ifluatex
  \begin{mplibcode}
    typetrace:="3D";
    typerepre:="persp";
    anglephi:=\useKV[ClesReperage]{AnglePhi};
    Initialisation(1500,anglephi,10,#2);
    color O,A,B,C,D,Z,M[];
    O=(0,0,0);
    A=(cosd(anglephi+90),sind(anglephi+90),0);
    B=(cosd(anglephi+180),sind(anglephi+180),0);
    C=(1,0,0);
    D=(0,1,0);
    Z=(0,0,1);
    trace cercles(O,A,O,A,Z) withcolor 0.7white;
    path Equateur;
    Equateur=cercles(O,C,O,C,D);
    trace (subpath((0.25+anglephi/360)*length Equateur,(0.75+anglephi/360)*length Equateur) of Equateur) dashed evenly withcolor 0.7white;
    trace (subpath((0.75+anglephi/360)*length Equateur,(1.25+anglephi/360)*length Equateur) of Equateur) withcolor 0.7white;
    path greenwich;
    greenwich=cercles(O,C,O,C,Z);
    trace subpath(3*length greenwich/4,5*length greenwich/4) of greenwich  withcolor 0.7white;
    clip currentpicture to cercles(O,A,O,A,Z);
    trace chemin(C,O,Z) dashed evenly withcolor 0.85white;
    trace chemin(O,2[Z,O])  dashed evenly withcolor 0.85white;

    vardef toto(text t)=
    n:=1;
    for p_=t:
    if (n mod 3)=1:
    k:=p_;
    fi;
    if (n mod 3)=2:
    l:=p_;
    fi;
    if (n mod 3)=0:
      M[n]=(cosd(k)*cosd(l),sind(k)*cosd(l),sind(l));
      path Codageun,Codagedeux;
      if k>0:
        Codageun=cercles(O,1[O,C],O,1[O,C],D) cutafter chemin(O,(cosd(k),sind(k),0));
      elseif k<0:
        Codageun=cercles(O,1[O,C],O,1[O,C],D) cutbefore chemin(O,(cosd(k),sind(k),0));
      fi;
      if l>0:
        Codagedeux=cercles(O,(cosd(k),sind(k),0),O,(cosd(k),sind(k),0),Z) cutafter chemin(O,M[n]);
      elseif l<0:
        Codagedeux=cercles(O,(cosd(k),sind(k),0),O,(cosd(k),sind(k),0),Z) cutbefore chemin(O,M[n]);
      fi;
    %%%% if l>0:
    %%%fill Projette(O)--Projette((cosd(k),sind(k),0))--Codagedeux--cycle withcolor \useKV[ClesReperage]{CouleurLa};
    %%%fill Projette(O)--Projette(C)--Codageun--cycle withcolor \useKV[ClesReperage]{CouleurLon};
    %%%else:
    %%%fill Projette(O)--Codagedeux--Projette((cosd(k),sind(k),0))--cycle withcolor \useKV[ClesReperage]{CouleurLa};
    %%%fill Projette(O)--Codageun--Projette(C)--cycle withcolor \useKV[ClesReperage]{CouleurLon};
    %%%fi;
      if unknown Codageun: else: trace Codageun; fi;
      if unknown Codagedeux: else: trace Codagedeux; fi;
      if \useKV[ClesReperage]{AffichageCoord}:
        picture CodageUn,CodageDeux;
        CodageUn=image(
          if k>0:
            label.bot(TEX("\scriptsize\ang{"&decimal(k)&"} E"),(0,0));
          else:
            label.bot(TEX("\scriptsize\ang{"&decimal(abs(k))&"} O"),(0,0));
          fi;
        );
        CodageDeux=image(
        if k>0:
          label.rt(TEX("\scriptsize\ang{"&decimal(l)&"} N"),(0,0));
        else:
          label.lft(TEX("\scriptsize\ang{"&decimal(abs(l))&"} S"),(0,0));
        fi;
        );
        fill (polygone(llcorner CodageUn,lrcorner CodageUn,urcorner CodageUn,ulcorner CodageUn) shifted(point(0.5*length Codageun) of Codageun)) withcolor blanc;
        trace CodageUn shifted (point(0.5*length Codageun) of Codageun);
        fill (polygone(llcorner CodageDeux,lrcorner CodageDeux,urcorner CodageDeux,ulcorner CodageDeux) shifted(point(0.5*length Codagedeux) of Codagedeux)) withcolor blanc;
        trace CodageDeux shifted (point(0.5*length Codagedeux) of Codagedeux);
      fi;
    trace chemin(O,(cosd(k),sind(k),0)) dashed withdots scaled 0.5;
    trace chemin(O,M[n]) dashed withdots scaled 0.5;
    trace chemin(O,C) dashed withdots scaled 0.5;
    if \useKV[ClesReperage]{AffichageNom}:
    if l>0:dotlabel.top(p_,Projette(M[n]));
    else:
    dotlabel.bot(p_,Projette(M[n]));
    fi;
    fi;
    fi;
    n:=n+1;
    endfor;
    enddef;
    toto(#1);
    label.llft(btex \tiny \ang{0} etex,Projette(C));
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={boolean AffichageCoord; AffichageCoord=\useKV[ClesReperage]{AffichageCoord}; boolean AffichageNom; AffichageNom=\useKV[ClesReperage]{AffichageNom};anglephi:=\useKV[ClesReperage]{AnglePhi};}]
    typetrace:="3D";
    typerepre:="persp";
    Initialisation(1500,anglephi,10,#2);
    color O,A,B,C,D,Z,M[];
    O=(0,0,0);
    A=(cosd(anglephi+90),sind(anglephi+90),0);
    B=(cosd(anglephi+180),sind(anglephi+180),0);
    C=(1,0,0);
    D=(0,1,0);
    Z=(0,0,1);
    trace cercles(O,A,O,A,Z) withcolor 0.7white;
    path Equateur;
    Equateur=cercles(O,C,O,C,D);
    trace (subpath((0.25+anglephi/360)*length Equateur,(0.75+anglephi/360)*length Equateur) of Equateur) dashed evenly withcolor 0.7white;
    trace (subpath((0.75+anglephi/360)*length Equateur,(1.25+anglephi/360)*length Equateur) of Equateur) withcolor 0.7white;
    path greenwich;
    greenwich=cercles(O,C,O,C,Z);
    trace subpath(3*length greenwich/4,5*length greenwich/4) of greenwich  withcolor 0.7white;
    clip currentpicture to cercles(O,A,O,A,Z);
    trace chemin(C,O,Z) dashed evenly withcolor 0.85white;
    trace chemin(O,2[Z,O])  dashed evenly withcolor 0.85white;

    vardef toto(text t)=
    n:=1;
    for p_=t:
     if (n mod 3)=1:
     k:=p_;
    fi;
    if (n mod 3)=2:
    l:=p_;
    fi;
    if (n mod 3)=0:
    M[n]=(cosd(k)*cosd(l),sind(k)*cosd(l),sind(l));
    path Codageun,Codagedeux;
    if k>0:
    Codageun=cercles(O,1[O,C],O,1[O,C],D) cutafter chemin(O,(cosd(k),sind(k),0));
    elseif k<0:
    Codageun=cercles(O,1[O,C],O,1[O,C],D) cutbefore chemin(O,(cosd(k),sind(k),0));
    fi;
    if l>0:
    Codagedeux=cercles(O,(cosd(k),sind(k),0),O,(cosd(k),sind(k),0),Z) cutafter chemin(O,M[n]);
    elseif k<0:
    Codagedeux=cercles(O,(cosd(k),sind(k),0),O,(cosd(k),sind(k),0),Z) cutbefore chemin(O,M[n]);
    fi;
    %if l>0:
    %fill Projette(O)--Projette((cosd(k),sind(k),0))--Codagedeux--cycle withcolor \useKV[ClesReperage]{CouleurLa};
    %fill Projette(O)--Projette(C)--Codageun--cycle withcolor \useKV[ClesReperage]{CouleurLon};
    %else:
    %fill Projette(O)--Codagedeux--Projette((cosd(k),sind(k),0))--cycle withcolor \useKV[ClesReperage]{CouleurLa};
    %fill Projette(O)--Codageun--Projette(C)--cycle withcolor \useKV[ClesReperage]{CouleurLon};
    %fi;
    if unknown Codageun: else: trace Codageun; fi;
    if unknown Codagedeux: else: trace Codagedeux; fi;
    if AffichageCoord:
    picture CodageUn,CodageDeux;
    CodageUn=image(
    if k>0:
    label.bot(LATEX("\noexpand\scriptsize\noexpand\ang{"&decimal(k)&"} E"),(0,0));
    else:
    label.bot(LATEX("\noexpand\scriptsize\noexpand\ang{"&decimal(abs(k))&"} O"),(0,0));
    fi;
    );
    CodageDeux=image(
    if k>0:
    label.rt(LATEX("\noexpand\scriptsize\noexpand\ang{"&decimal(l)&"} N"),(0,0));
    else:
    label.lft(LATEX("\noexpand\scriptsize\noexpand\ang{"&decimal(abs(l))&"} S"),(0,0));
    fi;
    );
    fill (polygone(llcorner CodageUn,lrcorner CodageUn,urcorner CodageUn,ulcorner CodageUn) shifted(point(0.5*length Codageun) of Codageun)) withcolor blanc;
    trace CodageUn shifted (point(0.5*length Codageun) of Codageun);
    fill (polygone(llcorner CodageDeux,lrcorner CodageDeux,urcorner CodageDeux,ulcorner CodageDeux) shifted(point(0.5*length Codagedeux) of Codagedeux)) withcolor blanc;
    trace CodageDeux shifted (point(0.5*length Codagedeux) of Codagedeux);
    fi;
    trace chemin(O,(cosd(k),sind(k),0)) dashed withdots scaled 0.5;
    trace chemin(O,M[n]) dashed withdots scaled 0.5;
    trace chemin(O,C) dashed withdots scaled 0.5;
    if AffichageNom:
    if l>0:dotlabel.top(p_,Projette(M[n]));
    else:
    dotlabel.bot(p_,Projette(M[n]));
    fi;
    fi;
    fi;
    n:=n+1;
    endfor;
    enddef;
    toto(#1);
    label.llft(LATEX("\noexpand\tiny\noexpand\ang{0}"),Projette(C));
  \end{mpost}
  \fi
}

\def\MPEspacePave#1#2#3#4#5#6#7#8#9{%
  \ifluatex
  \begin{mplibcode}
    typetrace:="3D";
    typerepre:="persp";
    Figure(-20u,-20u,20u,20u);
    Initialisation(1500,30,20,abs(#9));
    %marque_r:=marque_r/2;
    marque_p:="plein";
    color A,B,C,D,E,F,G,H,M[],N[];
    draw Pave(A,B,C,D,E,F,G,H)(#1,#3,#5);
    if #9>0:
    drawarrow Projette(A)--Projette(1.5[D,A]);
    drawarrow Projette(C)--Projette(1.5[D,C]);
    drawarrow Projette(E)--Projette(1.5[D,E]);
    label.top(btex $x$ etex,Projette(1.5[D,A]));
    label.top(btex $y$ etex,Projette(1.5[D,C]));
    label.top(btex $z$ etex,Projette(1.5[D,E]));
    label.ulft(btex 1 etex,Projette((1/#2)[D,A]));
    label.bot(btex 1 etex,Projette((1/#4)[D,C]));
    label.lft(btex 1 etex,Projette((1/#6)[D,E]));
    for k=1 upto (#2):
    pointe((k/#2)[D,A]);
    endfor;
    for k=1 upto (#4):
    pointe((k/#4)[D,C]);
    endfor;
    for k=1 upto (#6):
    pointe((k/#6)[D,E]);
    endfor;
    else:
    drawarrow Projette(D)--Projette(1.5[A,D]) dashed evenly;
    drawarrow Projette(B)--Projette(1.5[A,B]);
    drawarrow Projette(F)--Projette(1.5[A,F]);
    label.lrt(btex $x$ etex,Projette(1.5[A,D]));
    label.top(btex $y$ etex,Projette(1.5[A,B]));
    label.top(btex $z$ etex,Projette(1.5[A,F]));
    label.ulft(btex 1 etex,Projette((1/#2)[A,D]));
    label.bot(btex 1 etex,Projette((1/#4)[A,B]));
    label.lft(btex 1 etex,Projette((1/#6)[A,F]));
    for k=1 upto (#2):
    pointe((k/#2)[A,D]);
    endfor;
    for k=1 upto (#4):
    pointe((k/#4)[A,B]);
    endfor;
    for k=1 upto (#6):
    pointe((k/#6)[A,F]);
    endfor;
    fi;
    vardef tata(text t)=
    n:=1;%pour compter combien de points
    k:=0;%pour garder l'abscisse
    l:=0;%pour garder l'ordonn\'ee
    m:=0;%pour garder l'altitude
    if #8>0:
    for p_=t:
    if (n mod 4)=1:
    k:=p_;
    fi;
    if (n mod 4)=2:
    l:=p_;
    fi;
    if (n mod 4)=3:
    m:=p_;
    fi;
    if (n mod 4)=0:
    M[n]=(k/#2)[D,A]+(l/#4)*(C-D)+(m/#6)*(E-D);
    N[n]=(k/#2)[D,A]+(l/#4)*(C-D);
    if (#8>1):
    label.top(TEX(p_),Projette(M[n]));
    pointe(M[n]);
    fi;
    if (#8=1) or (#8=3) :
    drawoptions(dashed evenly withcolor gris);
    draw segment(M[n],(0,0,bluepart(M[n])));
    draw segment(M[n],N[n]);
    draw segment(N[n],(redpart(M[n]),0,0));
    draw segment(N[n],(0,greenpart(M[n]),0));
    drawoptions();
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;
    vardef toto(text t)=
    n:=1;%pour compter combien de points
    k:=0;%pour garder l'abscisse
    l:=0;%pour garder l'ordonn\'ee
    m:=0;%pour garder l'altitude
    if #8>0:
    for p_=t:
    if (n mod 4)=1:
    k:=p_;
    fi;
    if (n mod 4)=2:
    l:=p_;
    fi;
    if (n mod 4)=3:
    m:=p_;
    fi;
    if (n mod 4)=0:
    % message("je suis ici : "&p_);
    M[n]=(k/#2)[A,D]+(l/#4)*(B-A)+(m/#6)*(F-A);
    N[n]=(k/#2)[A,D]+(l/#4)*(B-A);
    if (#8>1):
    label.top(TEX(p_),Projette(M[n]));
    pointe(M[n]);
    fi;
    if (#8=1) or (#8=3) :
    drawoptions(dashed evenly withcolor gris);
    draw segment(M[n],A+(0,0,bluepart(M[n])));
    draw segment(M[n],N[n]);
    draw segment(N[n],A+(l/#4)*(B-A));
    draw segment(N[n],A+(k/#2)*(D-A));
    drawoptions();
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;
    if #9>0:
    tata(#7);
    else:
    toto(#7);
    fi;
    draw Pave(A,B,C,D,E,F,G,H)(#1,#3,#5);
    if \useKV[ClesReperage]{Code}:
    \useKV[ClesReperage]{Traces}
    fi;
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={input PfCGeometrie;}]
    typetrace:="3D";
    typerepre:="persp";
    Figure(-20u,-20u,20u,20u);
    Initialisation(1500,30,20,abs(#9));
    %marque_r:=marque_r/2;
    marque_p:="plein";
    color A,B,C,D,E,F,G,H,M[],N[];
    draw Pave(A,B,C,D,E,F,G,H)(#1,#3,#5);
    if #9>0:
    drawarrow Projette(A)--Projette(1.5[D,A]);
    drawarrow Projette(C)--Projette(1.5[D,C]);
    drawarrow Projette(E)--Projette(1.5[D,E]);
    label.ulft(btex 1 etex,Projette((1/#2)[D,A]));
    label.bot(btex 1 etex,Projette((1/#4)[D,C]));
    label.lft(btex 1 etex,Projette((1/#6)[D,E]));
    for k=1 upto (#2):
    pointe((k/#2)[D,A]);
    endfor;
    for k=1 upto (#4):
    pointe((k/#4)[D,C]);
    endfor;
    for k=1 upto (#6):
    pointe((k/#6)[D,E]);
    endfor;
    else:
    drawarrow Projette(D)--Projette(1.5[A,D]) dashed evenly;
    drawarrow Projette(B)--Projette(1.5[A,B]);
    drawarrow Projette(F)--Projette(1.5[A,F]);
    label.ulft(btex 1 etex,Projette((1/#2)[A,D]));
    label.bot(btex 1 etex,Projette((1/#4)[A,B]));
    label.lft(btex 1 etex,Projette((1/#6)[A,F]));
    for k=1 upto (#2):
    pointe((k/#2)[A,D]);
    endfor;
    for k=1 upto (#4):
    pointe((k/#4)[A,B]);
    endfor;
    for k=1 upto (#6):
    pointe((k/#6)[A,F]);
    endfor;
    fi;
    vardef tata(text t)=
    n:=1;%pour compter combien de points
    k:=0;%pour garder l'abscisse
    l:=0;%pour garder l'ordonn\'ee
    m:=0;%pour garder l'altitude
    if #8>0:
    for p_=t:
    if (n mod 4)=1:
    k:=p_;
    fi;
    if (n mod 4)=2:
    l:=p_;
    fi;
    if (n mod 4)=3:
    m:=p_;
    fi;
    if (n mod 4)=0:
    M[n]=(k/#2)[D,A]+(l/#4)*(C-D)+(m/#6)*(E-D);
    N[n]=(k/#2)[D,A]+(l/#4)*(C-D);
    if (#8>1):
    label.top(LATEX(p_),Projette(M[n]));
    pointe(M[n]);
    fi;
    if (#8=1) or (#8=3) :
    drawoptions(dashed evenly withcolor gris);
    draw segment(M[n],(0,0,bluepart(M[n])));
    draw segment(M[n],N[n]);
    draw segment(N[n],(redpart(M[n]),0,0));
    draw segment(N[n],(0,greenpart(M[n]),0));
    drawoptions();
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;
    vardef toto(text t)=
    n:=1;%pour compter combien de points
    k:=0;%pour garder l'abscisse
    l:=0;%pour garder l'ordonn\'ee
    m:=0;%pour garder l'altitude
    if #8>0:
    for p_=t:
    if (n mod 4)=1:
    k:=p_;
    fi;
    if (n mod 4)=2:
    l:=p_;
    fi;
    if (n mod 4)=3:
    m:=p_;
    fi;
    if (n mod 4)=0:
    % message("je suis ici : "&p_);
    M[n]=(k/#2)[A,D]+(l/#4)*(B-A)+(m/#6)*(F-A);
    N[n]=(k/#2)[A,D]+(l/#4)*(B-A);
    if (#8>1):
    label.top(LATEX(p_),Projette(M[n]));
    pointe(M[n]);
    fi;
    if (#8=1) or (#8=3) :
    drawoptions(dashed evenly withcolor gris);
    draw segment(M[n],A+(0,0,bluepart(M[n])));
    draw segment(M[n],N[n]);
    draw segment(N[n],A+(l/#4)*(B-A));
    draw segment(N[n],A+(k/#2)*(D-A));
    drawoptions();
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;
    if #9>0:
    tata(#7);
    else:
    toto(#7);
    fi;
    draw Pave(A,B,C,D,E,F,G,H)(#1,#3,#5);
  \end{mpost}
  \fi
}%

% Pour construire le rep\`ere du plan
\def\buildreperenew{%
  \toklistepointrepere{}%
  \foreachitem\compteur\in\ListePointRepere{\expandafter\Updatetoksrepere\compteur\nil}%
  \ifboolKV[ClesReperage]{Trace}{%
    \[\MPPlanTrace{\useKV[ClesReperage]{Unitex}}{\useKV[ClesReperage]{Pasx}}{\useKV[ClesReperage]{Unitey}}{\useKV[ClesReperage]{Pasy}}{\the\toklistepointrepere}{2}{\useKV[ClesReperage]{ValeurUnitex}}{\useKV[ClesReperage]{ValeurUnitey}}{\useKV[ClesReperage]{ListeSegment}}\]%
  }{%
    \xdef\AfficheNom{0}\ifboolKV[ClesReperage]{AffichageNom}{\ifboolKV[ClesReperage]{LectureCoord}{\xdef\AfficheNom{3}}{\xdef\AfficheNom{2}}}{\ifboolKV[ClesReperage]{LectureCoord}{\xdef\AfficheNom{1}}{}}%
    \xdef\AfficheGrad{0}\ifboolKV[ClesReperage]{AffichageGrad}{\xdef\AfficheGrad{1}}{}%
    \xdef\AfficheCoord{\useKV[ClesReperage]{AffichageAbs}}%
    \MPPlannew{(\useKV[ClesReperage]{Unitex},\useKV[ClesReperage]{Pasx})}{(\useKV[ClesReperage]{Unitey},\useKV[ClesReperage]{Pasy})}{\the\toklistepointrepere}{\AfficheNom}{\AfficheCoord}{\AfficheGrad}{(\useKV[ClesReperage]{ValeurUnitex},\useKV[ClesReperage]{ValeurUnitey})}%
  }%
}

\def\MPPlannew#1#2#3#4#5#6#7{%
  %#1 : Unitex, pasx
  %#2 : unitey, pasy
  %#3 : liste de points
  %#4 : Affichage nom + lecture graphique
  %#5 : Affichage des (abscisses/ordonn\'ees)
  %#6 : Graduation compl\`ete ?
  %#7 : (unitex,unitey)
  \ifluatex
  \begin{mplibcode}
    maxx:=-4000;
    minx=4000;
    unitex:=(xpart(#1))*cm;
    pasx=ypart(#1);
    unitpx:=unitex/pasx;
    maxy:=-4000;
    miny:=4000;
    unitey:=(xpart(#2))*cm;
    pasy:=ypart(#2);
    unitpy:=unitey/pasy;
    n:=1;
    vardef toto(text t)=
    for p_=t:
    if (n mod 3)=1:
    if p_>maxx:
        maxx:=p_;
      fi;
      if p_<minx:
        minx:=p_;
      fi;
    fi;
    if (n mod 3)=2:
      if p_>maxy:
        maxy:=p_;
      fi;
      if p_<miny:
        miny:=p_;
      fi;
      fi;
      n:=n+1;
    endfor;
    maxx:=maxx+1;
    minx:=minx-1;
    if maxx<(ypart(#1)+1):
    maxx:=ypart(#1)+1;
    fi;
    if minx>(-ypart(#1)-1):
    minx:=-ypart(#1)-1;
    fi;
    maxy:=maxy+1;
    miny:=miny-1;
    if maxy<(ypart(#2)+1):
    maxy:=ypart(#2)+1;
    fi;
    if miny>(-ypart(#2)-1):
    miny:=-ypart(#2)-1;
    fi;
    enddef;
    toto(#3);
    Figure((minx-1)*unitpx,(miny-1)*unitpy,(maxx+1)*unitpx,(maxy+1)*unitpy);
    pair A,B,C,D,E;
    A=(0,0);
    B=(minx*unitpx,0);
    C=(maxx*unitpx,0);
    D=(0,miny*unitpy);
    E=(0,maxy*unitpy);
    for k=0 upto (maxx-minx):
    draw ((xpart(B),ypart(D)-0.75*unitpy)--(xpart(B),ypart(E)+0.75*unitpy)) shifted (k*unitpx,0) withcolor gris;
    endfor;
    for k=0 upto (maxy-miny):
    draw ((xpart(B)-0.75*unitpx,ypart(D))--(xpart(C)+0.75*unitpx,ypart(D))) shifted (0,k*unitpy) withcolor gris;
    endfor;
    drawarrow (B+(-0.75*unitpx,0))--(C+(0.75*unitpx,0));
    drawarrow (D+(0,-0.75*unitpy))--(E+(0,0.75*unitpy));
    % graduation compl\`ete ou pas ?
    label.llft(btex \footnotesize 0 etex,A);
    if #6>0:
    for k=minx upto maxx:
    if (xpart((k*unitex,0))>xpart(B+(-0.75*unitpx,0))) and (xpart((k*unitex,0))<xpart(C+(0.75*unitpx,0))):
    if k<>0:
    dotlabel.lrt(TEX("\footnotesize\num{"&decimal(k)&"}"),(k*unitex,0));
    fi;
    fi;
    endfor;
    for k=miny upto maxy:
    if (ypart((0,k*unitey))>ypart(D+(0,-0.75*unitpy))) and (ypart((0,k*unitey))<ypart(E+(0,0.75*unitpy))):
    if k<>0:
    dotlabel.ulft(TEX("\footnotesize\num{"&decimal(k)&"}"),(0,k*unitey));
    fi;
    fi;
    endfor;
    else:
    dotlabel.lrt(TEX("\footnotesize\num{"&decimal(xpart(#7))&"}"),(unitex,0));
    dotlabel.ulft(TEX("\footnotesize\num{"&decimal(ypart(#7))&"}"),(0,unitey));
    fi;
    % apparition du nom des points ou pas
    m_c:=m_c*3;
    marque_p:="croix";
    vardef tata(text t)=%on place les points
    if #4>0:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if #4>1:
    if p_<>"":
    if (k>0) and (l>0):
    label.urt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l>0):
    label.urt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l=0):
    label.urt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l>0):
    label.ulft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l<0):
    label.llft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l<0):
    label.llft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l=0):
    label.llft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l<0):
    label.lrt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    pointe((k*unitpx,l*unitpy));
    fi;
    fi;
    if (#4=1) or (#4=3):
    draw (0,l*unitpy)--(k*unitpx,l*unitpy)--(k*unitpx,0) dashed evenly;
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    if #5=2:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if p_<>"":
        if (k mod pasx)<>0:
        label.lrt(TEX("\footnotesize$\frac{\num{"&decimal(k)&"}}{\num{"&decimal(pasx)&"}}$"),(k*unitpx,0));
        else:
        label.lrt(TEX("\footnotesize\num{\fpeval{"&decimal(k)&"/"&decimal(pasx)&"}}"),(k*unitpx,0));
        fi;
        if (l mod pasy)<>0:
        label.ulft(TEX("\footnotesize$\frac{\num{"&decimal(l)&"}}{\num{"&decimal(pasy)&"}}$"),(0,l*unitpy));
        else:
        label.ulft(TEX("\footnotesize\num{\fpeval{"&decimal(l)&"/"&decimal(pasy)&"}}"),(0,l*unitpy));
        fi;
      pointe((k*unitpx,0),(0,l*unitpy));
      fi;
    fi;
    n:=n+1;
    endfor;
    elseif #5=1:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if p_<>"":
    label.lrt(TEX("\footnotesize\num{\fpeval{"&decimal(k)&"/"&decimal(pasx)&"}}"),(k*unitpx,0));
    label.ulft(TEX("\footnotesize\num{\fpeval{"&decimal(l)&"/"&decimal(pasy)&"}}"),(0,l*unitpy));
    pointe((k*unitpx,0),(0,l*unitpy));
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;
    tata(#3);
  \end{mplibcode}
  \else
  \begin{mpost}
    maxx:=-4000;
    minx=4000;
    unitex:=(xpart(#1))*cm;
    pasx=ypart(#1);
    unitpx:=unitex/pasx;
    maxy:=-4000;
    miny:=4000;
    unitey:=(xpart(#2))*cm;
    pasy:=ypart(#2);
    unitpy:=unitey/pasy;
    n:=1;
    vardef toto(text t)=
    for p_=t:
    if (n mod 3)=1:
    if p_>maxx:
        maxx:=p_;
      fi;
      if p_<minx:
        minx:=p_;
      fi;
    fi;
    if (n mod 3)=2:
      if p_>maxy:
        maxy:=p_;
      fi;
      if p_<miny:
        miny:=p_;
      fi;
      fi;
      n:=n+1;
    endfor;
    maxx:=maxx+1;
    minx:=minx-1;
    if maxx<(ypart(#1)+1):
    maxx:=ypart(#1)+1;
    fi;
    if minx>(-ypart(#1)-1):
    minx:=-ypart(#1)-1;
    fi;
    maxy:=maxy+1;
    miny:=miny-1;
    if maxy<(ypart(#2)+1):
    maxy:=ypart(#2)+1;
    fi;
    if miny>(-ypart(#2)-1):
    miny:=-ypart(#2)-1;
    fi;
    enddef;
    toto(#3);
    Figure((minx-1)*unitpx,(miny-1)*unitpy,(maxx+1)*unitpx,(maxy+1)*unitpy);
    pair A,B,C,D,E;
    A=(0,0);
    B=(minx*unitpx,0);
    C=(maxx*unitpx,0);
    D=(0,miny*unitpy);
    E=(0,maxy*unitpy);
    for k=0 upto (maxx-minx):
    draw ((xpart(B),ypart(D)-0.75*unitpy)--(xpart(B),ypart(E)+0.75*unitpy)) shifted (k*unitpx,0) withcolor gris;
    endfor;
    for k=0 upto (maxy-miny):
    draw ((xpart(B)-0.75*unitpx,ypart(D))--(xpart(C)+0.75*unitpx,ypart(D))) shifted (0,k*unitpy) withcolor gris;
    endfor;
    drawarrow (B+(-0.75*unitpx,0))--(C+(0.75*unitpx,0));
    drawarrow (D+(0,-0.75*unitpy))--(E+(0,0.75*unitpy));
    % graduation compl\`ete ou pas ?
    label.llft(btex \noexpand\footnotesize 0 etex,A);
    if #6>0:
    for k=minx upto maxx:
    if (xpart((k*unitex,0))>xpart(B+(-0.75*unitpx,0))) and (xpart((k*unitex,0))<xpart(C+(0.75*unitpx,0))):
    if k<>0:
    dotlabel.lrt(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(k)&"}"),(k*unitex,0));
    fi;
    fi;
    endfor;
    for k=miny upto maxy:
    if (ypart((0,k*unitey))>ypart(D+(0,-0.75*unitpy))) and (ypart((0,k*unitey))<ypart(E+(0,0.75*unitpy))):
    if k<>0:
    dotlabel.ulft(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(k)&"}"),(0,k*unitey));
    fi;
    fi;
    endfor;
    else:
    dotlabel.lrt(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(xpart(#7))&"}"),(unitex,0));
    dotlabel.ulft(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(ypart(#7))&"}"),(0,unitey));
    fi;
    % apparition du nom des points ou pas
    m_c:=m_c*3;
    marque_p:="croix";
    vardef tata(text t)=%on place les points
    if #4>0:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if #4>1:
    if p_<>"":
    if (k>0) and (l>0):
    label.urt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l>0):
    label.urt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l=0):
    label.urt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l>0):
    label.ulft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l<0):
    label.llft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l<0):
    label.llft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l=0):
    label.llft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l<0):
    label.lrt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    pointe((k*unitpx,l*unitpy));
    fi;
    fi;
    if (#4=1) or (#4=3):
    draw (0,l*unitpy)--(k*unitpx,l*unitpy)--(k*unitpx,0) dashed evenly;
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    if #5=2:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if p_<>"":
        if (k mod pasx)<>0:
        label.lrt(LATEX("\noexpand\footnotesize$\noexpand\frac{\noexpand\num{"&decimal(k)&"}}{\noexpand\num{"&decimal(pasx)&"}}$"),(k*unitpx,0));
        else:
        label.lrt(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(k)&"/"&decimal(pasx)&"}}"),(k*unitpx,0));
        fi;
        if (l mod pasy)<>0:
        label.ulft(LATEX("\noexpand\footnotesize$\noexpand\frac{\noexpand\num{"&decimal(l)&"}}{\noexpand\num{"&decimal(pasy)&"}}$"),(0,l*unitpy));
        else:
        label.ulft(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(l)&"/"&decimal(pasy)&"}}"),(0,l*unitpy));
        fi;
      pointe((k*unitpx,0),(0,l*unitpy));
      fi;
    fi;
    n:=n+1;
    endfor;
    elseif #5=1:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if p_<>"":
    label.lrt(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(k)&"/"&decimal(pasx)&"}}"),(k*unitpx,0));
    label.ulft(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(l)&"/"&decimal(pasy)&"}}"),(0,l*unitpy));
    pointe((k*unitpx,0),(0,l*unitpy));
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;
    tata(#3);
  \end{mpost}
  \fi
}

\def\MPPlanTrace#1#2#3#4#5#6#7#8#9{%
  \ifluatex
  \begin{mplibcode}
    maxx:=-4000;
  minx=4000;
  unitex:=#1*cm;
  pasx=#2;
  unitpx:=unitex/pasx;
  maxy:=-4000;
  miny:=4000;
  unitey:=#3*cm;
  pasy:=#4;
  unitpy:=unitey/pasy;
  n:=1;
  vardef toto(text t)=
    for p_=t:
    if (n mod 3)=1:
      if p_>maxx:
        maxx:=p_;
      fi;
      if p_<minx:
        minx:=p_;
      fi;
    fi;
    if (n mod 3)=2:
      if p_>maxy:
        maxy:=p_;
      fi;
      if p_<miny:
        miny:=p_;
      fi;
      fi;
      n:=n+1;
    endfor;
    maxx:=maxx+1;
    minx:=minx-1;
    if maxx<(#2+1):
    maxx:=#2+1;
    fi;
    if minx>(-#2-1):
    minx:=-#2-1;
    fi;
    maxy:=maxy+1;
    miny:=miny-1;
    if maxy<(#4+1):
    maxy:=#2+1;
    fi;
    if miny>(-#4-1):
    miny:=-#4-1;
    fi;
    enddef;
    toto(#5);
    Figure((minx-1)*unitpx,(miny-1)*unitpy,(maxx+1)*unitpx,(maxy+1)*unitpy);
    pair A,B,C,D,E;
    A=(0,0);
    B=(minx*unitpx,0);
    C=(maxx*unitpx,0);
    D=(0,miny*unitpy);
    E=(0,maxy*unitpy);
    for k=0 upto (maxx-minx):
    draw ((xpart(B),ypart(D)-0.75*unitpy)--(xpart(B),ypart(E)+0.75*unitpy)) shifted (k*unitpx,0) withcolor gris;
    endfor;
    for k=0 upto (maxy-miny):
    draw ((xpart(B)-0.75*unitpx,ypart(D))--(xpart(C)+0.75*unitpx,ypart(D))) shifted (0,k*unitpy) withcolor gris;
    endfor;
    drawarrow (B+(-0.75*unitpx,0))--(C+(0.75*unitpx,0));
    drawarrow (D+(0,-0.75*unitpy))--(E+(0,0.75*unitpy));
    dotlabel.bot(TEX("\footnotesize\num{"&decimal(#7)&"}"),(unitex,0));
    dotlabel.lft(TEX("\footnotesize\num{"&decimal(#8)&"}"),(0,unitey));
    label.llft(btex 0 etex,A);
    % apparition du nom des points ou pas
    m_c:=m_c*3;
    marque_p:="croix";
        vardef tata(text t)=%on place les points
    if #6>0:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if #6>1:
    if (k>0) and (l>0):
    label.urt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l>0):
    label.urt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l=0):
    label.urt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l>0):
    label.ulft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l<0):
    label.llft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l<0):
    label.llft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l=0):
    label.llft(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l<0):
    label.lrt(TEX(p_),(k*unitpx,l*unitpy));
    fi;
    pointe((k*unitpx,l*unitpy));
    fi;
    if (#6=1) or (#6=3):
    draw (0,l*unitpy)--(k*unitpx,l*unitpy)--(k*unitpx,0) dashed evenly;
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;    
    vardef Tracage(text t)(text ls)=%on trace les segments
    pair A[];
    n:=0;%pour parcourir la liste
    m:=0;%pour lister les points par leur nombre
    for p_=t:
    n:=n+1;
    if (n mod 3)=1:
    k:=p_;
    fi;
    if (n mod 3)=2:
    l:=p_;
    fi;
    if (n mod 3)=0:
    m:=m+1;
    A[m]=(k*unitpx,l*unitpy);
    fi;
    endfor;
    for p_=ls:
    draw segment(A[p_ div 10],A[p_ mod 10]);
    endfor;
    enddef;
    tata(#5);
    Tracage(#5)(#9);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={input PfCGeometrie;}]
  maxx:=-4000;
  minx=4000;
  unitex:=#1*cm;
  pasx=#2;
  unitpx:=unitex/pasx;
  maxy:=-4000;
  miny:=4000;
  unitey:=#3*cm;
  pasy:=#4;
  unitpy:=unitey/pasy;
  n:=1;
  vardef toto(text t)=
    for p_=t:
    if (n mod 3)=1:
      if p_>maxx:
        maxx:=p_;
      fi;
      if p_<minx:
        minx:=p_;
      fi;
    fi;
    if (n mod 3)=2:
      if p_>maxy:
        maxy:=p_;
      fi;
      if p_<miny:
        miny:=p_;
      fi;
      fi;
      n:=n+1;
    endfor;
    maxx:=maxx+1;
    minx:=minx-1;
    if maxx<(#2+1):
    maxx:=#2+1;
    fi;
    if minx>(-#2-1):
    minx:=-#2-1;
    fi;
    maxy:=maxy+1;
    miny:=miny-1;
    if maxy<(#4+1):
    maxy:=#2+1;
    fi;
    if miny>(-#4-1):
    miny:=-#4-1;
    fi;
    enddef;
    toto(#5);
    Figure((minx-1)*unitpx,(miny-1)*unitpy,(maxx+1)*unitpx,(maxy+1)*unitpy);
    pair A,B,C,D,E;
    A=(0,0);
    B=(minx*unitpx,0);
    C=(maxx*unitpx,0);
    D=(0,miny*unitpy);
    E=(0,maxy*unitpy);
    for k=0 upto (maxx-minx):
    draw ((xpart(B),ypart(D)-0.75*unitpy)--(xpart(B),ypart(E)+0.75*unitpy)) shifted (k*unitpx,0) withcolor gris;
    endfor;
    for k=0 upto (maxy-miny):
    draw ((xpart(B)-0.75*unitpx,ypart(D))--(xpart(C)+0.75*unitpx,ypart(D))) shifted (0,k*unitpy) withcolor gris;
    endfor;
    drawarrow (B+(-0.75*unitpx,0))--(C+(0.75*unitpx,0));
    drawarrow (D+(0,-0.75*unitpy))--(E+(0,0.75*unitpy));
    dotlabel.bot(LATEX("\noexpand\footnotesize\num{"&decimal(#7)&"}"),(unitex,0));
    dotlabel.lft(LATEX("\noexpand\footnotesize\num{"&decimal(#8)&"}"),(0,unitey));
    label.llft(btex 0 etex,A);
    % apparition du nom des points ou pas
    m_c:=m_c*3;
    marque_p:="croix";
        vardef tata(text t)=%on place les points
    if #6>0:
    n:=1;
    k:=0;%pour retenir la coordonn\'ee en x
    l:=0;%pour retenir la coordonn\'ee en y
    for p_=t:
        if (n mod 3)=1:
    if numeric p_:
    k:=p_;
    fi;
    fi;
    if (n mod 3)=2:
    if numeric p_:
    l:=p_;
    fi;
    fi;
    if (n mod 3)=0:
    if #6>1:
    if (k>0) and (l>0):
    label.urt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l>0):
    label.urt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l=0):
    label.urt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l>0):
    label.ulft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k=0) and (l<0):
    label.llft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l<0):
    label.llft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k<0) and (l=0):
    label.llft(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    if (k>0) and (l<0):
    label.lrt(LATEX(p_),(k*unitpx,l*unitpy));
    fi;
    pointe((k*unitpx,l*unitpy));
    fi;
    if (#6=1) or (#6=3):
    draw (0,l*unitpy)--(k*unitpx,l*unitpy)--(k*unitpx,0) dashed evenly;
    fi;
    fi;
    n:=n+1;
    endfor;
    fi;
    enddef;    
    vardef Tracage(text t)(text ls)=%on trace les segments
    pair A[];
    n:=0;%pour parcourir la liste
    m:=0;%pour lister les points par leur nombre
    for p_=t:
    n:=n+1;
    if (n mod 3)=1:
    k:=p_;
    fi;
    if (n mod 3)=2:
    l:=p_;
    fi;
    if (n mod 3)=0:
    m:=m+1;
    A[m]=(k*unitpx,l*unitpy);
    fi;
    endfor;
    for p_=ls:
    draw segment(A[p_ div 10],A[p_ mod 10]);
    endfor;
    enddef;
    tata(#5);
    Tracage(#5)(#9);
  \end{mpost}
  \fi
}

\def\MPNewDEMIGraduee#1#2{%
  % #1 : liste des points \`a placer en pas. pour g\'erer le cas des rep\'erages fractionnaires
  % #2 : liste des noms des points
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    maxx:=0;
    unitex:=\useKV[ClesReperage]{Unitex}*cm;
    pasx:=\useKV[ClesReperage]{Pasx};
    unitp:=unitex/pasx;%unit\'e de d\'eplacement
    ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex};
    ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine};
    AffichageGrad:=\AffichageGrad;
    AffichageCoord:=\useKV[ClesReperage]{AffichageAbs};
    AffichageNom:=\AffichageNom;
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination de l'abscisse maximale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+1;
    if maxx<(pasx+1):
    maxx:=pasx+1;
    fi;
    % -----
    pair A,B;
    A=(0,0);
    B=unitp*(maxx,0);
    % On trace la demi-droite
    drawarrow A--(B+(0.75*unitp,0));
    % marquage secondaire
    marque_s:=marque_s/3;
    for k=0 step 2 until (maxx):
    draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
    endfor;
    drawoptions();
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-1):
    draw marquesegment((k/maxx)[A,B],((k+pasx)/maxx)[A,B]);
    endfor;
    %% marquage des points
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    dotlabel.bot(TEX("\footnotesize\num{"&decimal(ValeurUnitex)&"}"),unitex*(1,0));
    label.bot(TEX("\footnotesize\num{"&decimal(ValeurOrigine)&"}"),A);
    if AffichageGrad>0:
    for k=2 upto maxx:
    dotlabel.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(k)&"}}"),unitex*(k,0));
    endfor;
    fi;
    %%
    vardef tata(text t)=
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    label.top(TEX(p_),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    endfor;
    fi;
    if AffichageCoord=3:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    drawarrow (unitp*(valeur[n],-1))--(unitp*(valeur[n],-0.3));
    label.bot(btex \pointilles[2em] etex,(unitp*(valeur[n],-1)));
    fi;
    endfor;
    elseif AffichageCoord=2:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.bot(TEX("\footnotesize$\frac{\num{\fpeval{"&decimal(ValeurOrigine*pasx)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(valeur[n])&"}}}{\num{"&decimal(pasx)&"}}$"),unitp*(valeur[n],0));
    else:
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    fi;
    pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    elseif AffichageCoord=1:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    fi;
    enddef;
    %----
    tata(#2);
    clip currentpicture to polygone(u*(-1,-1),((maxx+0.75)*unitp,-u),((maxx+0.75)*unitp,u),u*(-1,1));
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={unitex:=\useKV[ClesReperage]{Unitex}*cm; pasx:=\useKV[ClesReperage]{Pasx}; unitp:=unitex/pasx; ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex}; ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine}; AffichageGrad:=\AffichageGrad; AffichageCoord:=\useKV[ClesReperage]{AffichageAbs}; AffichageNom:=\AffichageNom;}]
    maxx:=0;
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination de l'abscisse maximale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+1;
    if maxx<(pasx+1):
    maxx:=pasx+1;
    fi;
    % -----
    pair A,B;
    A=(0,0);
    B=unitp*(maxx,0);
    % On trace la demi-droite
    drawarrow A--(B+(0.75*unitp,0));
    % marquage secondaire
    marque_s:=marque_s/3;
    for k=0 step 2 until (maxx):
    draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
    endfor;
    drawoptions();
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-1):
    draw marquesegment((k/maxx)[A,B],((k+pasx)/maxx)[A,B]);
    endfor;
    %% marquage des points
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    dotlabel.bot(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(ValeurUnitex)&"}"),unitex*(1,0));
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(ValeurOrigine)&"}"),A);
    if AffichageGrad>0:
    for k=2 upto maxx:
    dotlabel.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(k)&"}}"),unitex*(k,0));
    endfor;
    fi;
    %%
    vardef tata(text t)=
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    label.top(LATEX(p_),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    endfor;
    fi;
    if AffichageCoord=3:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    drawarrow (unitp*(valeur[n],-1))--(unitp*(valeur[n],-0.3));
    label.bot(btex \noexpand\hbox to2em{\noexpand\pointilles[2em]} etex,(unitp*(valeur[n],-1)));
    %pointe(unitp*(valeur[n]-ValeurOrigine,0));
    fi;
    endfor;
    elseif AffichageCoord=2:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\frac{\noexpand\num{\noexpand\fpeval{"&decimal(ValeurOrigine*pasx)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(valeur[n])&"}}}{\noexpand\num{"&decimal(pasx)&"}}$"),unitp*(valeur[n],0));
    else:
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    fi;
    pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    elseif AffichageCoord=1:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    fi;
    enddef;
    %----
    tata(#2);
    clip currentpicture to polygone(u*(-1,-1),((maxx+0.75)*unitp,-u),((maxx+0.75)*unitp,u),u*(-1,1));
  \end{mpost}
  \fi
}

\def\MPNewDROITEGraduee#1#2{%
  % #1 : liste des points \`a placer en pas. pour g\'erer le cas des rep\'erages fractionnaires
  % #2 : liste des noms des points
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    maxx:=0;
    minx:=4000;
    unitex:=\useKV[ClesReperage]{Unitex}*cm;
    pasx:=\useKV[ClesReperage]{Pasx};
    unitp:=unitex/pasx;%unit\'e de d\'eplacement
    ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex};
    ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine};
    AffichageGrad:=\AffichageGrad;
    AffichageCoord:=\useKV[ClesReperage]{AffichageAbs};
    AffichageNom:=\AffichageNom;
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination des abscisses maximale et minimale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    if valeur[k]<minx:
    minx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+(pasx div 2);
    minx:=minx-(pasx div 2);
    if maxx<(pasx+1):
    maxx:=2*pasx-1;
    fi;
    if minx>(-pasx-1):
    minx:=-2*pasx-1;
    fi;
    if minx<\useKV[ClesReperage]{ValeurMin}:
    minx:=\useKV[ClesReperage]{ValeurMin};
    fi;
    if maxx>\useKV[ClesReperage]{ValeurMax}:
    maxx:=\useKV[ClesReperage]{ValeurMax};
    fi;
    % -----
    pair A,B,C;
    A=(0,0);
    B=unitp*(maxx,0);
    C=unitp*(minx,0);
    % On trace la demi-droite
    drawarrow (C+unitp*(-0.75,0))--(B+unitp*(0.75,0));
    % marquage secondaire
    marque_s:=marque_s/3;
    labeloffset:=labeloffset*2;
    if ((maxx-minx) mod 2)=0:
      for k=(minx+1) step 2 until (maxx-1):
      draw marquedemidroite(C,B);
      draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
      endfor;
      else:
      for k=(minx) step 2 until (maxx-1):
        draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
     endfor;
     fi;
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-pasx):
    draw marquesegment((k/maxx)[A,B],((k+pasx)/maxx)[A,B]);
    endfor;
    for k=0 step -pasx until (minx+pasx):
    draw marquesegment((k/maxx)[A,B],((k-pasx)/maxx)[A,B]);
    endfor;
    % marquage des points
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    label.bot(TEX("\footnotesize\num{"&decimal(ValeurUnitex)&"}"),unitex*(1,0));
    label.bot(TEX("\footnotesize\num{"&decimal(ValeurOrigine)&"}"),A);
    if AffichageGrad>0:
    for k=((minx+(minx mod pasx)) div pasx) upto (maxx div pasx):
    if (k<0) or (k>1):
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}"),unitex*(k,0));%%%
    fi;
    endfor;
    fi;
    vardef tata(text t)=%on place les points
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    if substring(1,2) of p_="*":
    label.top(TEX(substring(2,length p_) of p_),unitp*(valeur[n],0));
    else:
    label.top(TEX(p_),unitp*(valeur[n],0));
    fi;
    if p_<>"":
    pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    fi;
    % On ajoute une paramétrisation possible à chaque point.
    if AffichageCoord>0:
    n:=0;
    for p_=t:
    n:=n+1;
    if substring(1,2) of p_="*":
    ACoord:=scantokens(substring(0,1) of p_);
    if ACoord=3:
    drawarrow (unitp*(valeur[n],-1))--(unitp*(valeur[n],-0.3));
    label.bot(btex \hbox to2em{\dotfill} etex,(unitp*(valeur[n],-1)));
    pointe(unitp*(valeur[n]-ValeurOrigine,0));
    elseif ACoord=2:
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.bot(TEX("\footnotesize$\frac{\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"}}}{\num{"&decimal(pasx)&"}}$"),unitp*(valeur[n],0));
    else:
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    fi;
    pointe(unitp*(valeur[n],0));
    elseif ACoord=1:
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    fi;
    else:
    if AffichageCoord=3:
    if p_<>"":
    drawarrow (unitp*(valeur[n],-1))--(unitp*(valeur[n],-0.3));
    label.bot(btex \hbox to2em{\dotfill} etex,(unitp*(valeur[n],-1)));
    pointe(unitp*(valeur[n],0));
    fi;
    elseif AffichageCoord=2:
    if p_<>"":
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.bot(TEX("\footnotesize$\frac{\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"}}}{\num{"&decimal(pasx)&"}}$"),unitp*(valeur[n],0));
    else:
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    fi;
    pointe(unitp*(valeur[n],0));
    fi;
    elseif AffichageCoord=1:
    if p_<>"":
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    fi;
    fi;
    fi;
    endfor;
    fi;
    enddef;
    %%%
    tata(#2);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={unitex:=\useKV[ClesReperage]{Unitex}*cm; pasx:=\useKV[ClesReperage]{Pasx}; unitp:=unitex/pasx; ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex}; ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine}; AffichageGrad:=\AffichageGrad; AffichageCoord:=\useKV[ClesReperage]{AffichageAbs}; AffichageNom:=\AffichageNom; ValeurMin=\useKV[ClesReperage]{ValeurMin}; ValeurMax=\useKV[ClesReperage]{ValeurMax};}]
    maxx:=0;
    minx:=4000;
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination des abscisses maximale et minimale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    if valeur[k]<minx:
    minx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+(pasx div 2);
    minx:=minx-(pasx div 2);
    if maxx<(pasx+1):
    maxx:=2*pasx-1;
    fi;
    if minx>(-pasx-1):
    minx:=-2*pasx-1;
    fi;
    if minx<ValeurMin:
    minx:=ValeurMin;
    fi;
    if maxx>ValeurMax:
    maxx:=ValeurMax;
    fi;
    % -----
    pair A,B,C;
    A=(0,0);
    B=unitp*(maxx,0);
    C=unitp*(minx,0);
    % On trace la demi-droite
    drawarrow (C+unitp*(-0.75,0))--(B+unitp*(0.75,0));
    % marquage secondaire
    marque_s:=marque_s/3;
    labeloffset:=labeloffset*2;
    if ((maxx-minx) mod 2)=0:
      for k=(minx+1) step 2 until (maxx-1):
      draw marquedemidroite(C,B);
      draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
      endfor;
      else:
      for k=(minx) step 2 until (maxx-1):
        draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
     endfor;
     fi;
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-pasx):
    draw marquesegment((k/maxx)[A,B],((k+pasx)/maxx)[A,B]);
    endfor;
    for k=0 step -pasx until (minx+pasx):
    draw marquesegment((k/maxx)[A,B],((k-pasx)/maxx)[A,B]);
    endfor;
    % marquage des points
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(ValeurUnitex)&"}"),unitex*(1,0));
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{"&decimal(ValeurOrigine)&"}"),A);
    if AffichageGrad>0:
    for k=((minx+(minx mod pasx)) div pasx) upto (maxx div pasx):
    if (k<0) or (k>1):
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}"),unitex*(k,0));%%%
    fi;
    endfor;
    fi;
    vardef tata(text t)=%on place les points
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    if substring(1,2) of p_="*":
    label.top(LATEX(substring(2,length p_) of p_),unitp*(valeur[n],0));
    else:
    label.top(LATEX(p_),unitp*(valeur[n],0));
    fi;
    if p_<>"":
    pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    fi;
    if AffichageCoord>0:
    n:=0;
    for p_=t:
    n:=n+1;
    if substring(1,2) of p_="*":
    ACoord:=scantokens(substring(0,1) of p_);
    if ACoord=3:
    drawarrow (unitp*(valeur[n],-1))--(unitp*(valeur[n],-0.3));
    label.bot(btex \noexpand\hbox to2em{\noexpand\dotfill} etex,(unitp*(valeur[n],-1)));
    pointe(unitp*(valeur[n]-ValeurOrigine,0));
    elseif ACoord=2:
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\frac{\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"}}}{\noexpand\num{"&decimal(pasx)&"}}$"),unitp*(valeur[n],0));
    else:
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    fi;
    pointe(unitp*(valeur[n],0));
    elseif ACoord=1:
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    fi;
    else:
    if AffichageCoord=3:
    if p_<>"":
    drawarrow (unitp*(valeur[n],-1))--(unitp*(valeur[n],-0.3));
    label.bot(btex \noexpand\hbox to2em{\noexpand\dotfill} etex,(unitp*(valeur[n],-1)));
    pointe(unitp*(valeur[n],0));
    fi;
    elseif AffichageCoord=2:
    if p_<>"":
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.bot(LATEX("\noexpand\footnotesize$\noexpand\frac{\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"}}}{\noexpand\num{"&decimal(pasx)&"}}$"),unitp*(valeur[n],0));
    else:
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    fi;
    pointe(unitp*(valeur[n],0));
    fi;
    elseif AffichageCoord=1:
    if p_<>"":
    label.bot(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(valeur[n],0));
    pointe(unitp*(valeur[n],0));
    fi;
    fi;
    fi;
    endfor;
    fi;    
    enddef;
    %%%
    tata(#2);
  \end{mpost}
  \fi
}%

\def\MPThermo#1#2{%
  % #1 : liste des points \`a placer en pas. pour g\'erer le cas des rep\'erages fractionnaires
  % #2 : liste des noms des points
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    maxx:=0;
    minx:=4000;
    unitex:=\useKV[ClesReperage]{Unitex}*cm;
    pasx:=\useKV[ClesReperage]{Pasx};
    unitp:=unitex/pasx;%unit\'e de d\'eplacement
    ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex};
    ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine};
    AffichageGrad:=\AffichageGrad;
    AffichageCoord:=\useKV[ClesReperage]{AffichageAbs};
    AffichageNom:=\AffichageNom;
    boolean Kelvin,Farenheit;
    Kelvin=\useKV[ClesReperage]{Kelvin};
    Farenheit=\useKV[ClesReperage]{Farenheit};
    color ColMercure;
    ColMercure:=\useKV[ClesReperage]{CouleurMercure};
    boolean Mercure;
    Mercure=\useKV[ClesReperage]{Mercure};
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination des abscisses maximale et minimale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    if valeur[k]<minx:
    minx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+(pasx div 2);
    minx:=minx-(pasx div 2);
    if maxx<(pasx+1):
    maxx:=2*pasx-1;
    fi;
    if minx>(-pasx-1):
    minx:=-2*pasx-1;
    fi;
    if Kelvin:
    minx:=0;
    fi;
    % -----
    pair A,B,C;
    A=(0,0);
    B=unitp*(0,maxx);
    C=unitp*(0,minx);
    % On trace la demi-droite
    draw ((C+unitp*(0,-0.75))--(B+unitp*(0,0.75)));
    % marquage secondaire
    marque_s:=marque_s/3;
    if pasx<11:
    labeloffset:=labeloffset*2;
    if ((maxx-minx) mod 2)=0:
      for k=(minx+1) step 2 until (maxx-1):
      draw marquedemidroite(C,B);
      draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
      endfor;
      else:
      for k=(minx) step 2 until (maxx-1):
        draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
     endfor;
     fi;
     fi;
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-pasx):
    draw marquesegment((k/maxx)[A,B],((k+pasx)/maxx)[A,B]);
    endfor;
    for k=0 step -pasx until (minx+pasx):
    draw marquesegment((k/maxx)[A,B],((k-pasx)/maxx)[A,B]);
    endfor;
    % marquage des points
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    if Kelvin:
    label.lft(TEX("\footnotesize\Temp[K]{"&decimal(ValeurUnitex)&"}"),unitex*(0,1));
    label.lft(TEX("\footnotesize\Temp[K]{"&decimal(ValeurOrigine)&"}"),A);
    elseif Farenheit:
    label.lft(TEX("\footnotesize\Temp[F]{"&decimal(ValeurUnitex)&"}"),unitex*(0,1));
    label.lft(TEX("\footnotesize\Temp[F]{"&decimal(ValeurOrigine)&"}"),A);
    else:
    label.lft(TEX("\footnotesize\Temp{"&decimal(ValeurUnitex)&"}"),unitex*(0,1));
    label.lft(TEX("\footnotesize\Temp{"&decimal(ValeurOrigine)&"}"),A);
    fi;
    if AffichageGrad>0:
    for k=((minx+(minx mod pasx)) div pasx) upto (maxx div pasx):
    if (k<0) or (k>1):
    if Kelvin:
    label.lft(TEX("\footnotesize\Temp[K]{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}"),unitex*(0,k));%%%
    elseif Farenheit:
    label.lft(TEX("\footnotesize\Temp[F]{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}"),unitex*(0,k));%%%
    else:
    label.lft(TEX("\footnotesize\Temp{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}"),unitex*(0,k));%%%
    fi;
    fi;
    endfor;
    fi;

    vardef Thermo(expr nbt)=
    pair Tc[];
    Tc[0]=(5mm,unitp*(minx-1));
    path cc[];
    cc1=cercles(Tc[0],2.5mm);
    Tc1=pointarc(cc1,75);
    Tc4=pointarc(cc1,105);
    Tc2=(xpart(Tc1),ypart(B+unitp*(0,0.75)));
    Tc3=(xpart(Tc4),ypart(B+unitp*(0,0.75)));
    Tc5=(xpart(Tc1),ypart(unitp*(0,valeur[1])));
    Tc6=(xpart(Tc4),ypart(unitp*(0,valeur[1])));
    path temp;
    temp=Tc1--Tc5--Tc6--Tc4--arccercle(Tc4,Tc1,Tc0)--cycle;
    if nbt>0:
    fill temp withcolor ColMercure;
    trace Tc5--Tc6;
    fi;
    trace arccercle(Tc4,Tc1,Tc0);
    trace Tc1--Tc2--arccercle(Tc2,Tc3,iso(Tc2,Tc3))--Tc4;
    enddef;

    if Mercure:Thermo(1) else : Thermo(0) fi;
    
    vardef tata(text t)=%on place les points
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    label.rt(TEX(p_),unitp*(0,valeur[n]));
    if p_<>"":
    pointe(unitp*(0,valeur[n]));
    fi;
    endfor;
    fi;
    if AffichageCoord=3:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    drawarrow (unitp*(-1,valeur[n]))--(unitp*(-0.3,valeur[n]));
    label.rt(btex \hbox to2em{\dotfill} etex,(unitp*(-1,valeur[n])));
    pointe(unitp*(0,valeur[n]-ValeurOrigine));
    fi;
    endfor;
    elseif AffichageCoord=2:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.rt(TEX("\footnotesize$\frac{\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"}}}{\num{"&decimal(pasx)&"}}$"),unitp*(0,valeur[n]));
    else:
    label.rt(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(0,valeur[n]));
    fi;
    pointe(unitp*(0,valeur[n]-ValeurOrigine));
    fi;
    endfor;
    elseif AffichageCoord=1:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    if Kelvin:
    label.rt(TEX("\footnotesize\Temp[K]{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),(5mm,unitp*valeur[n]));
    elseif Farenheit:
    label.rt(TEX("\footnotesize\Temp[F]{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),(5mm,unitp*valeur[n]));
    else:
    label.rt(TEX("\footnotesize\Temp{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),(5mm,unitp*valeur[n]));
    fi;
    pointe(unitp*(0,valeur[n]));
    draw (unitp*(0,valeur[n]))--(7.5mm,unitp*valeur[n]) dashed evenly;
    fi;
    endfor;
    fi;
    enddef;
    %%%
    tata(#2);
  \end{mplibcode}
  \else
  \begin{mpost}[mpsettings={unitex:=\useKV[ClesReperage]{Unitex}*cm;
    pasx:=\useKV[ClesReperage]{Pasx};
    unitp:=unitex/pasx;%unit\'e de d\'eplacement
    ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex};
    ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine};
    AffichageGrad:=\AffichageGrad;
    AffichageCoord:=\useKV[ClesReperage]{AffichageAbs};
    AffichageNom:=\AffichageNom;
    boolean Kelvin,Farenheit;
    Kelvin=\useKV[ClesReperage]{Kelvin};
    Farenheit=\useKV[ClesReperage]{Farenheit};
    color ColMercure;
    ColMercure:=\useKV[ClesReperage]{CouleurMercure};
    boolean Mercure;
    Mercure=\useKV[ClesReperage]{Mercure};}]
    maxx:=0;
    minx:=4000;
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination des abscisses maximale et minimale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    if valeur[k]<minx:
    minx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+(pasx div 2);
    minx:=minx-(pasx div 2);
    if maxx<(pasx+1):
    maxx:=2*pasx-1;
    fi;
    if minx>(-pasx-1):
    minx:=-2*pasx-1;
    fi;
    if Kelvin:
    minx:=0;
    fi;
    % -----
    pair A,B,C;
    A=(0,0);
    B=unitp*(0,maxx);
    C=unitp*(0,minx);
    % On trace la demi-droite
    draw (C+unitp*(0,-0.75))--(B+unitp*(0,0.75));
    % marquage secondaire
    marque_s:=marque_s/3;
    if pasx<11:
    labeloffset:=labeloffset*2;
    if ((maxx-minx) mod 2)=0:
      for k=(minx+1) step 2 until (maxx-1):
      draw marquedemidroite(C,B);
      draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
      endfor;
      else:
      for k=(minx) step 2 until (maxx-1):
        draw marquesegment((k/maxx)[A,B],((k+1)/maxx)[A,B]);
     endfor;
    fi;
    fi;
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-pasx):
    draw marquesegment((k/maxx)[A,B],((k+pasx)/maxx)[A,B]);
    endfor;
    for k=0 step -pasx until (minx+pasx):
    draw marquesegment((k/maxx)[A,B],((k-pasx)/maxx)[A,B]);
    endfor;
    % marquage des points
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    if Kelvin:
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{"&decimal(ValeurUnitex)&"}{\kelvin}"),unitex*(0,1));
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{"&decimal(ValeurOrigine)&"}{\kelvin}"),A);
    elseif Farenheit:
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{"&decimal(ValeurUnitex)&"}{\farenheit}"),unitex*(0,1));
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{"&decimal(ValeurOrigine)&"}{\farenheit}"),A);
    else:
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{"&decimal(ValeurUnitex)&"}{\celsius}"),unitex*(0,1));
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{"&decimal(ValeurOrigine)&"}{\celsius}"),A);
    fi;
    if AffichageGrad>0:
    for k=((minx+(minx mod pasx)) div pasx) upto (maxx div pasx):
    if (k<0) or (k>1):
    if Kelvin:
    label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}{\kelvin}"),unitex*(0,k));%%%
    elseif Farenheit:
label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}{\farenheit}"),unitex*(0,k));%%%
    else:
label.lft(LATEX("\noexpand\footnotesize\noexpand\SI{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}{\celsius}"),unitex*(0,k));%%%
    fi;
    fi;
    endfor;
    fi;

    vardef Thermo(expr nbt)=
    pair Tc[];
    Tc[0]=(5mm,unitp*(minx-1));
    path cc[];
    cc1=cercles(Tc[0],2.5mm);
    Tc1=pointarc(cc1,75);
    Tc4=pointarc(cc1,105);
    Tc2=(xpart(Tc1),ypart(B+unitp*(0,0.75)));
    Tc3=(xpart(Tc4),ypart(B+unitp*(0,0.75)));
    Tc5=(xpart(Tc1),ypart(unitp*(0,valeur[1])));
    Tc6=(xpart(Tc4),ypart(unitp*(0,valeur[1])));
    path temp;
    temp=Tc1--Tc5--Tc6--Tc4--arccercle(Tc4,Tc1,Tc0)--cycle;
    if nbt>0:
    fill temp withcolor ColMercure;
    trace Tc5--Tc6;
    fi;
    trace arccercle(Tc4,Tc1,Tc0);
    trace Tc1--Tc2--arccercle(Tc2,Tc3,iso(Tc2,Tc3))--Tc4;
    enddef;

    if Mercure:Thermo(1) else : Thermo(0) fi;
    
    vardef tata(text t)=%on place les points
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    label.rt(LATEX(p_),unitp*(0,valeur[n]));
    if p_<>"":
    pointe(unitp*(0,valeur[n]));
    fi;
    endfor;
    fi;
    if AffichageCoord=3:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    drawarrow (unitp*(-1,valeur[n]))--(unitp*(-0.3,valeur[n]));
    label.rt(\btex \hbox to2em{\dotfill} etex,(unitp*(-1,valeur[n])));
    pointe(unitp*(0,valeur[n]-ValeurOrigine));
    fi;
    endfor;
    elseif AffichageCoord=2:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    if ((ValeurUnitex*valeur[n]) mod pasx)<>0:
    label.rt(LATEX("\noexpand\footnotesize$\noexpand\frac{\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"}}}{\num{"&decimal(pasx)&"}}$"),unitp*(0,valeur[n]));
    else:
    label.rt(LATEX("\noexpand\footnotesize\noexpand\num{\noexpand\fpeval{"&decimal(ValeurUnitex)&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}"),unitp*(0,valeur[n]));
    fi;
    pointe(unitp*(0,valeur[n]-ValeurOrigine));
    fi;
    endfor;
    elseif AffichageCoord=1:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    if Kelvin:
    label.rt(LATEX("\noexpand\footnotesize\noexpand\SI{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}{\kelvin}"),(5mm,unitp*valeur[n]));
    elseif Farenheit:
    label.rt(LATEX("\noexpand\footnotesize\noexpand\SI{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}{\farenheit}"),(5mm,unitp*valeur[n]));
    else:
    label.rt(LATEX("\noexpand\footnotesize\noexpand\SI{\noexpand\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-(ValeurOrigine))&"*"&decimal(valeur[n])&"/"&decimal(pasx)&"}}{\celsius}"),(5mm,unitp*valeur[n]));
    fi;
    pointe(unitp*(0,valeur[n]));
    draw (unitp*(0,valeur[n]))--(7.5mm,unitp*valeur[n]) dashed evenly;
    fi;
    endfor;
    fi;
    enddef;
    %%%
    tata(#2);
  \end{mpost}
  \fi
}

\def\MPNewDROITEGradueeMulti#1#2{%
  % #1 : liste des points \`a placer en pas. pour g\'erer le cas des rep\'erages fractionnaires
  % #2 : liste des noms des points
  \ifluatex
  \mplibforcehmode
  \begin{mplibcode}
    maxx:=0;
    minx:=4000;
    unitex:=\useKV[ClesReperage]{Unitex}*cm;
    pasx:=\useKV[ClesReperage]{Pasx};
    unitp:=unitex/pasx;%unit\'e de d\'eplacement
    ValeurUnitex:=\useKV[ClesReperage]{ValeurUnitex};
    ValeurOrigine:=\useKV[ClesReperage]{ValeurOrigine};
    AffichageGrad:=\AffichageGrad;
    AffichageCoord:=\useKV[ClesReperage]{AffichageAbs};
    AffichageNom:=\AffichageNom;
    numeric valeur[];
    vardef titi(text t)=
    n:=0;
    for p_=t:
    n:=n+1;
    valeur[n]=p_;
    endfor;
    enddef;
    titi(#1);
    % Détermination des abscisses maximale et minimale
    for k=1 upto n:
    if valeur[k]>maxx:
    maxx:=valeur[k];
    fi;
    if valeur[k]<minx:
    minx:=valeur[k];
    fi;
    endfor;
    maxx:=maxx+(pasx div 2);
    minx:=minx-(pasx div 2);
    if maxx<(pasx+1):
    maxx:=2*pasx-1;
    fi;
    if minx>(-pasx-1):
    minx:=-2*pasx-1;
    fi;
    if minx<\useKV[ClesReperage]{ValeurMin}:
    minx:=\useKV[ClesReperage]{ValeurMin};
    fi;
    if maxx>\useKV[ClesReperage]{ValeurMax}:
    maxx:=\useKV[ClesReperage]{ValeurMax};
    fi;
%    % -----
    pair A[],B[],C[];
    for l=0 upto (\useKV[ClesReperage]{Etages}-1):
    A[l]=(0,-l*cm);
    B[l]=unitp*(maxx,0)+(0,-l*cm);
    C[l]=unitp*(minx,0)+(0,-l*cm);
    % On trace la demi-droite
    drawarrow (C[l]+unitp*(-0.75,0))--(B[l]+unitp*(0.75,0));
    % marquage secondaire
    marque_s:=marque_s/3;
    if ((maxx-minx) mod 2)=0:
      for k=(minx+1) step 2 until (maxx-1):
      draw marquedemidroite(C[l],B[l]);
      draw marquesegment((k/maxx)[A[l],B[l]],((k+1)/maxx)[A[l],B[l]]);
      endfor;
      else:
      for k=(minx) step 2 until (maxx-1):
        draw marquesegment((k/maxx)[A[l],B[l]],((k+1)/maxx)[A[l],B[l]]);
     endfor;
     fi;
    % marquage primaire
    marque_s:=marque_s*3;
    for k=0 step pasx until (maxx-pasx):
    draw marquesegment((k/maxx)[A[l],B[l]],((k+pasx)/maxx)[A[l],B[l]]);
    endfor;
    for k=0 step -pasx until (minx+pasx):
    draw marquesegment((k/maxx)[A[l],B[l]],((k-pasx)/maxx)[A[l],B[l]]);
    endfor;
    endfor;
    % On trace les zoom
    for k=0 upto (\useKV[ClesReperage]{Etages}-2):
    lp:=floor(1+uniformdeviate(8));
    draw (lp/10)[A[k],B[k]]--A[k+1] dashed evenly scaled 0.5 withcolor 0.5white;
    draw ((lp+1)/10)[A[k],B[k]]--B[k+1] dashed evenly scaled 0.5 withcolor 0.5white;
    endfor;
    % Labelisation
    m_c:=m_c*3;
    marque_p:="croix";
    labeloffset:=labeloffset*2;
    label.top(TEX("\footnotesize\num{"&decimal(ValeurUnitex)&"}"),unitex*(1,0));
    label.top(TEX("\footnotesize\num{"&decimal(ValeurOrigine)&"}"),A[0]);
    if AffichageGrad>0:
    for k=((minx+(minx mod pasx)) div pasx) upto (maxx div pasx):
    if (k<0) or (k>1):
    label.bot(TEX("\footnotesize\num{\fpeval{"&decimal(ValeurOrigine)&"+"&decimal(ValeurUnitex-ValeurOrigine)&"*"&decimal(k)&"}}"),unitex*(k,0));%%%
    fi;
    endfor;
    fi;
    labeloffset:=labeloffset/2;
    vardef tata(text t)=%on place les points
    if AffichageNom>0:
    n:=0;
    for p_=t:
    n:=n+1;
    label.top(TEX(p_),unitp*(valeur[n],0)+(0,(-\useKV[ClesReperage]{Etages}+1)*cm));
    pointe(unitp*(valeur[n],0));
    endfor;
    fi;
    if AffichageCoord=3:
    n:=0;
    for p_=t:
    n:=n+1;
    if p_<>"":
    drawarrow (unitp*(valeur[n],-1)+(0,(-\useKV[ClesReperage]{Etages}+1)*cm))--(unitp*(valeur[n],-0.3)+(0,(-\useKV[ClesReperage]{Etages}+1)*cm));
    label.bot(btex \hbox to4em{\dotfill} etex,(unitp*(valeur[n],-1))+(0,(-\useKV[ClesReperage]{Etages}+0.5)*cm));
    %pointe(unitp*(valeur[n],0));
    fi;
    endfor;
    fi;
    enddef;
    %%%
    tata(#2);
  \end{mplibcode}
  \fi
}

% Pour construire les droite/demi-droite gradu\'ee
\def\builddemidroitenew{%
  \toklistepointdroite{}%
  \toklistenompointdemidroite{}%
  \xdef\AffichageNom{0}\ifboolKV[ClesReperage]{AffichageNom}{\xdef\AffichageNom{1}}{}
  \xdef\AffichageCoord{\useKV[ClesReperage]{AffichageAbs}}
  \xdef\AffichageGrad{0}\ifboolKV[ClesReperage]{AffichageGrad}{\xdef\AffichageGrad{1}}{}
  \ifboolKV[ClesReperage]{Thermometre}{%
    \foreachitem\compteur\in\ListePointDroite{\expandafter\Updatetoksdemidroite\compteur\nil}%
    \xdef\Listedesvaleursaplacersurlademidroite{}%
    \foreachitem\compteur\in\ListePointDroite{\xdef\Listedesvaleursaplacersurlademidroite{\Listedesvaleursaplacersurlademidroite,\ListePointDroite[\compteurcnt,1]}}%
    % \Listedesvaleursaplacersurlademidroite%
    \MPThermo{\Listedesvaleursaplacersurlademidroite}{\the\toklistenompointdemidroite}%
  }{%
    \ifboolKV[ClesReperage]{DemiDroite}{%
      \xdef\Listedesvaleursaplacersurlademidroite{}%
      \foreachitem\compteur\in\ListePointDroite{\expandafter\Updatetoksdemidroite\compteur\nil}%
      \foreachitem\compteur\in\ListePointDroite{\xdef\Listedesvaleursaplacersurlademidroite{\Listedesvaleursaplacersurlademidroite,\ListePointDroite[\compteurcnt,1]}}%
      %\Listedesvaleursaplacersurlademidroite%
      \MPNewDEMIGraduee{\Listedesvaleursaplacersurlademidroite}{\the\toklistenompointdemidroite}%
    }{%
      \foreachitem\compteur\in\ListePointDroite{\expandafter\Updatetoksdemidroite\compteur\nil}%
      \xdef\Listedesvaleursaplacersurlademidroite{}%
      \foreachitem\compteur\in\ListePointDroite{\xdef\Listedesvaleursaplacersurlademidroite{\Listedesvaleursaplacersurlademidroite,\ListePointDroite[\compteurcnt,1]}}%
      %\Listedesvaleursaplacersurlademidroite%
      \MPNewDROITEGraduee{\Listedesvaleursaplacersurlademidroite}{\the\toklistenompointdemidroite}%
    }%
  }%
}%

\NewDocumentCommand\Reperage{o m}{%
  \useKVdefault[ClesReperage]%
  \setKV[ClesReperage]{#1}%
  \ifboolKV[ClesReperage]{Espace}{%
    \setKV[ClesReperage]{Unitex=2,Unitey=2.5,Unitez=1.5}%
    \ifboolKV[ClesReperage]{Sphere}{\setKV[ClesReperage]{EchelleEspace=75}}{}%
    \setKV[ClesReperage]{#1}%
    \setsepchar[*]{,*/}\ignoreemptyitems%
    \readlist*\ListePointEspace{#2}%
    \buildespace%
  }{\ifboolKV[ClesReperage]{Plan}{%
      \setsepchar[*]{,*/}\ignoreemptyitems%
      \readlist*\ListePointRepere{#2}%
      \buildreperenew%
    }{%
      \setsepchar[*]{,*/}\ignoreemptyitems%
      \readlist*\ListePointDroite{#2}%
      \builddemidroitenew%
    }%
  }%
}%

\NewDocumentCommand\ReperageMulti{o m}{%
  \useKVdefault[ClesReperage]%
  \setKV[ClesReperage]{#1}%
  \setsepchar[*]{,*/}\ignoreemptyitems%
  \readlist*\ListePointDroite{#2}%
  \toklistepointdroite{}%
  \toklistenompointdemidroite{}%
  \xdef\AffichageNom{0}\ifboolKV[ClesReperage]{AffichageNom}{\xdef\AffichageNom{1}}{}
  \xdef\AffichageCoord{\useKV[ClesReperage]{AffichageAbs}}
  \xdef\AffichageGrad{0}\ifboolKV[ClesReperage]{AffichageGrad}{\xdef\AffichageGrad{1}}{}
  \foreachitem\compteur\in\ListePointDroite{\expandafter\Updatetoksdemidroite\compteur\nil}%
  \xdef\Listedesvaleursaplacersurlademidroite{}%
  \foreachitem\compteur\in\ListePointDroite{\xdef\Listedesvaleursaplacersurlademidroite{\Listedesvaleursaplacersurlademidroite,\ListePointDroite[\compteurcnt,1]}}%
  \MPNewDROITEGradueeMulti{\Listedesvaleursaplacersurlademidroite}{\the\toklistenompointdemidroite}%
  \setsepchar{,}%
}%

%%%
% Puissances
%%%
\newcommand\Puissances[2]{%
  \ensuremath{%
    \xintifboolexpr{#2==0}{1}{\xintifboolexpr{#2>0}{\xdef\TotalP{\fpeval{#2-1}}#1\multido{\i=1+1}{\TotalP}{\times#1}}{\xdef\TotalP{\fpeval{-#2-1}}\frac{1}{#1\multido{\i=1+1}{\TotalP}{\times#1}}}}%
  }%
}

%%%
% Ecritures d'unit\'es
%%%
\setKVdefault[Unites]{m=false,km=false,hm=false,ha=false,dam=false,a=false,dm=false,cm=true,mm=false,um=false,nm=false,g=true,t=false,q=false,kg=false,hg=false,dag=false,dg=false,cg=false,mg=false,ug=false,ng=false,mmin=false,kmh=true,kms=false,ms=false,mh=false,kgm=false,gcm=true,L=true,kL=false,hL=false,daL=false,dL=false,cL=false,mL=false,l=true,kl=false,hl=false,dal=false,dl=false,cl=false,ml=false,Go=true,Mo=false,ko=false,To=false,o=false,kWh=true,C=true,K=false,F=false}

%D'apres https://tex.stackexchange.com/questions/38905/time-of-the-day-or-time-period-using-the-package-siunitx
\ExplSyntaxOn
\NewDocumentCommand \Temps { o > { \SplitArgument { 5 } { ; } } m }
{%
  \group_begin:%
  \IfNoValueF{#1}
  { \keys_set:nn { siunitx } {#1} }
  \siunitx_hms_output:nnn #2
  \group_end:
}
\cs_new_protected:Npn \siunitx_hms_output:nnn #1#2#3#4#5#6
{%
  \IfNoValueF {#1}%
  {%
    \tl_if_blank:nF {#1}%
    {%
      \SI{#1}{\annee\xintifboolexpr{#1>1}{s}{}}%
      \IfNoValueF {#2}{~}%
    }%
  }%
  \IfNoValueF {#2}%
  {%
    \tl_if_blank:nF {#2}%
    {%
      \SI{#2}{\mois}%
      \IfNoValueF{#3}{~}%
    }%
  }%
  \IfNoValueF {#3}%
  {%
    \tl_if_blank:nF {#3}%
    {%
      \SI{#3}{\jour}%
      \IfNoValueF{#4}{~}%
    }%
  }%
  \IfNoValueF {#4}%
  {%
    \tl_if_blank:nF {#4}%
    {%
      \SI{#4}{\hour}%
      \IfNoValueF{#5}{~}%
    }%
  }%
  \IfNoValueF {#5}%
  {%
    \tl_if_blank:nF {#5}%
    {%
      \SI[minimum-integer-digits=2]{#5}{\minute}%
      \IfNoValueF{#6}{~}%
    }%
  }%
  \IfNoValueF {#6}%
  {%
    \tl_if_blank:nF {#6} {\SI{#6}{\second}}}%
}%
\ExplSyntaxOff

\newcommand\Temp[2][]{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{F}{%
    \SI{#2}{\fahrenheit}%
  }{%
    \ifboolKV[Unites]{K}{%
      \SI{#2}{\kelvin}%
    }{%
      \SI{#2}{\celsius}%
    }%
  }%
}%

\newcommand\Conso[2][]{%
  \SI{#2}{\kWh}%
}

\newcommand\Prix[2][2]{%
  \SI[round-mode=places,round-precision=#1]{#2}{\EuRo}%
}

\newcommand\Octet[2][]{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{o}{%
    \SI{#2}{\octet}%
  }{%
    \ifboolKV[Unites]{ko}{%
      \SI{#2}{\kilo\octet}%
    }{\ifboolKV[Unites]{Mo}{%
        \SI{#2}{\mega\octet}%
      }{\ifboolKV[Unites]{To}{%
          \SI{#2}{\tera\octet}%
        }{%
          \SI{#2}{\giga\octet}%
        }%
      }%
    }%
  }%
}%

\NewDocumentCommand\Lg{o m}{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{nm}{%
    \SI{#2}{\nm}%
  }{\ifboolKV[Unites]{um}{%
      \SI{#2}{\um}%
    }{\ifboolKV[Unites]{km}{%
        \SI{#2}{\km}%
      }{\ifboolKV[Unites]{hm}{%
          \SI{#2}{\hecto\metre}%
        }{\ifboolKV[Unites]{dam}{%
            \SI{#2}{\deca\metre}%
          }{\ifboolKV[Unites]{dm}{%
              \SI{#2}{\dm}%
            }{\ifboolKV[Unites]{m}{%
                \SI{#2}{\m}%
              }{\ifboolKV[Unites]{mm}{%
                  \SI{#2}{\mm}%
                }{\SI{#2}{\cm}%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\NewDocumentCommand\Masse{o m}{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{ng}{%
    \SI{#2}{\ng}%
  }{\ifboolKV[Unites]{ug}{%
      \SI{#2}{\ug}%
    }{\ifboolKV[Unites]{t}{%
        \SI{#2}{\tonne}%
      }{\ifboolKV[Unites]{q}{%
          \SI{#2}{\quintal}%
        }{%
          \ifboolKV[Unites]{kg}{%
            \SI{#2}{\kg}%
          }{\ifboolKV[Unites]{hg}{%
              \SI{#2}{\hecto\gram}%
            }{\ifboolKV[Unites]{dag}{%
                \SI{#2}{\deca\gram}%
              }{\ifboolKV[Unites]{dg}{%
                  \SI{#2}{\deci\gram}%
                }{\ifboolKV[Unites]{cg}{%
                    \SI{#2}{\centi\gram}%
                  }{\ifboolKV[Unites]{mg}{%
                      \SI{#2}{\milli\gram}%
                    }{\SI{#2}{\gram}%
                    }%
                  }%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\NewDocumentCommand\Capa{o m}{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{kL}{%
    \SI{#2}{\kilo\liter}%
  }{\ifboolKV[Unites]{hL}{%
      \SI{#2}{\hecto\liter}%
    }{\ifboolKV[Unites]{daL}{%
        \SI{#2}{\deca\liter}%
      }{\ifboolKV[Unites]{dL}{%
          \SI{#2}{\deci\liter}%
        }{\ifboolKV[Unites]{cL}{%
            \SI{#2}{\centi\liter}%
          }{\ifboolKV[Unites]{mL}{%
              \SI{#2}{\milli\liter}%
            }{\SI{#2}{\liter}%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\newcommand\Aire[2][]{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{km}{%
    \SI{#2}{\square\km}%
  }{\ifboolKV[Unites]{hm}{%
      \SI{#2}{\square\hecto\metre}%
    }{\ifboolKV[Unites]{ha}{%
        \SI{#2}{\hectare}%
      }{\ifboolKV[Unites]{dam}{%
          \SI{#2}{\square\deca\metre}%
        }{\ifboolKV[Unites]{a}{%
            \SI{#2}{\are}%
          }{\ifboolKV[Unites]{dm}{%
              \SI{#2}{\square\dm}%
            }{\ifboolKV[Unites]{m}{%
                \SI{#2}{\square\metre}%
              }{\ifboolKV[Unites]{mm}{%
                  \SI{#2}{\square\mm}%
                }{\SI{#2}{\square\cm}%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\newcommand\Vol[2][]{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{km}{%
    \SI{#2}{\cubic\km}%
  }{\ifboolKV[Unites]{hm}{%
      \SI{#2}{\cubic\hecto\metre}%
    }{\ifboolKV[Unites]{dam}{%
        \SI{#2}{\cubic\deca\metre}%
      }{\ifboolKV[Unites]{dm}{%
          \SI{#2}{\cubic\dm}%
        }{\ifboolKV[Unites]{m}{%
            \SI{#2}{\cubic\metre}%
          }{\ifboolKV[Unites]{mm}{%
              \SI{#2}{\cubic\mm}%
            }{\SI{#2}{\cubic\cm}%
            }%
          }%
        }%
      }%
    }%
  }%
}%

\newcommand\Vitesse[2][]{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{mmin}{%
    \SI[per-mode=symbol]{#2}{\meter\per\minute}%
  }{%
    \ifboolKV[Unites]{mh}{%
      \SI[per-mode=symbol]{#2}{\meter\per\hour}%
    }{%
      \ifboolKV[Unites]{ms}{%
        \SI[per-mode=symbol]{#2}{\meter\per\second}%
      }{%
        \ifboolKV[Unites]{kms}{%
          \SI[per-mode=symbol]{#2}{\kilo\meter\per\second}%
        }{%
          \SI[per-mode=symbol]{#2}{\kilo\meter\per\hour}%
        }%
      }%
    }%
  }%
}%

\newcommand\MasseVol[2][]{%
  \useKVdefault[Unites]%
  \setKV[Unites]{#1}%
  \ifboolKV[Unites]{kgm}{%
    \SI[per-mode=symbol]{#2}{\kilo\gram\per\cubic\metre}%
  }{%
    \SI[per-mode=symbol]{#2}{\gram\per\cubic\centi\metre}%
  }%
}%

%%%
% Tableaux d'unit\'es
%%%
\setKVdefault[ClesTableaux]{Virgule=true,Incline=false,Entiers=false,Decimaux=false,Milliards=false,Millions=false,Micro=false,Nano=false,Partie=false,CouleurG=gray!15,CouleurM=gray!15,Couleurm=gray!15,Couleuru=gray!15,Couleurd=gray!15,Classes=false,Nombres=false,Puissances=false,NbLignes=2,Metre=false,Are=false,Capacite=false,Carre=false,Cube=false,Litre=false,Gramme=false,Fleches=false,FlechesB=false,FlechesH=false,Colonnes=false,Prefixes=false,Escalier=false,Taille=5,Largeur=4.75em,Nom=PfCTableau,CodeAfter={},PuissancesSeules=false,Colonne=-1}

\newcommand\PfCTBstrut{\rule[-1.2ex]{0pt}{3.8ex}}% Top and Bottom strut
\newcommand\PfCTstrut{\rule{0pt}{3.8ex}}% Top strut
\newcommand\PfCBstrut{\rule[-1.2ex]{0pt}{0ex}}% Bottom strut

\newlength\PfCTableauPuissances%

\newcommand\Tableau[2][]{%
  \useKVdefault[ClesTableaux]%
  \setKV[ClesTableaux]{#1}%
  \ifboolKV[ClesTableaux]{Escalier}{%
    \ifboolKV[ClesTableaux]{Metre}{%
      \xdef\PfCTableauUnite{\meter}%
      \xdef\PfCCoefConversion{10}%
    }{}%
    \ifboolKV[ClesTableaux]{Carre}{%
      \xdef\PfCTableauUnite{\square\meter}%
      \xdef\PfCCoefConversion{100}%
    }{}%
    \ifboolKV[ClesTableaux]{Cube}{%
      \xdef\PfCTableauUnite{\cubic\meter}%
      \xdef\PfCCoefConversion{1000}%
    }{}%
    \ifboolKV[ClesTableaux]{Gramme}{%
      \xdef\PfCTableauUnite{\gram}%
      \xdef\PfCCoefConversion{10}%
    }{}%
    \PfCTableauIncline%
  }{%
  %
  %%% Cl\'e Prefixes
  %
  \ifboolKV[ClesTableaux]{Prefixes}{%
    \xdef\DecalageLigne{0}%
    \setlength{\tabcolsep}{0.01\tabcolsep}%
    \begin{center}%
      %
      %%% Definition du tableau
      %
      \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonne{16}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonne{13}}{\xdef\PfCDerniereColonne{10}}}%
      \ifboolKV[ClesTableaux]{Nano}{\xdef\PfCDerniereColonne{\fpeval{\PfCDerniereColonne+6}}}{\ifboolKV[ClesTableaux]{Micro}{\xdef\PfCDerniereColonne{\fpeval{\PfCDerniereColonne+3}}}{}}
      \begin{NiceTabular}{*{\ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }}{m{3.25em}}>{\columncolor{gray!15}}{c}*{%
            \ifboolKV[ClesTableaux]{Micro}{6}{%
              \ifboolKV[ClesTableaux]{Nano}{9}{3}%
            }}%
          {m{3.25em}}}%
        %
      	%%% Prise en compte de la cl\'e Partie
      	%
        \ifboolKV[ClesTableaux]{Partie}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \Block[]{1-%
            \ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }}{\bfseries Partie enti\`ere}\ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&%
          }{%
            \ifboolKV[ClesTableaux]{Millions}{%
              &&&%
            }{%
            }}%
          &&&&&
          &\Block[fill=gray!15]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[]{1-%
            \ifboolKV[ClesTableaux]{Micro}{6}{%
              \ifboolKV[ClesTableaux]{Nano}{9}{3}%
            }}{\bfseries Partie d\'ecimale}
          &&%
          \ifboolKV[ClesTableaux]{Micro}{&&&}{%
            \ifboolKV[ClesTableaux]{Nano}{&&&&&&}{}%
          }%
          \\
        }{}%
        %
      	%%% Prise en compte de la cl\'e Classes
      	%
        \ifboolKV[ClesTableaux]{Classes}{%
          %\hline
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}\ifboolKV[ClesTableaux]{Milliards}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurG}}]{1-3}{Classe des milliards}&&&\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}
          \ifboolKV[ClesTableaux]{Millions}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}
          \Block[draw,fill={\useKV[ClesTableaux]{Couleurm}}]{1-3}{Classe des milliers}&&%
          &\Block[draw,fill={\useKV[ClesTableaux]{Couleuru}}]{1-3}{Classe des unités}&&
          &\Block[draw,fill=gray!15]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[draw]{1-%
            \ifboolKV[ClesTableaux]{Micro}{6}{%
              \ifboolKV[ClesTableaux]{Nano}{9}{3}%
            }}{}
          &&%
          \ifboolKV[ClesTableaux]{Micro}{&&&}{%
            \ifboolKV[ClesTableaux]{Nano}{&&&&&&}{}%
          }%
          \\
        }{}%
      	%
      	%%% Valeurs par d\'efaut
      	%
        \hline%
        \ifboolKV[ClesTableaux]{Milliards}{%
        \Block[borders={left,right}]{}{}&\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont giga}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont m\'ega}%
        &\Block[borders={right}]{}{}%
        }{%
        \ifboolKV[ClesTableaux]{Millions}{%
        \Block[borders={left,right}]{}{}&\Block[borders={right}]{}{}%
        &\Block[]{}{\fontsize{8}{8}\selectfont m\'ega}%
        &%
        }{%
        }}%
        \Block[borders={left,right}]{}{}&\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont kilo}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont hecto}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont d\'eca}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont unit\'es}%
        &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont deci}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont centi}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont milli}%
      	\ifboolKV[ClesTableaux]{Micro}{&\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont micro}\\}{%
      	\ifboolKV[ClesTableaux]{Nano}{&\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont micro}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{8}{8}\selectfont nano}\\}{\\}%
      	}%
        %
      	%%% Prise en compte de la cl\'e Nombres
      	%
        \ifboolKV[ClesTableaux]{Nombres}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont\num{100000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont\num{10000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont\num{1000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{100000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000000}}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont \num{1000000}}%
            &%
          }{}
          \ifboolKV[ClesTableaux]{Millions}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont \num{100000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000000}}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont \num{1000000}}%
            &%
          }{}
          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont \num{100000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{1000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{100}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{1}}%
          &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,1} ou $\dfrac{\strut1}{\strut10}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,01} ou $\dfrac{\strut1}{\strut100}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,001} ou $\dfrac{\strut1}{\strut\num{1000}}$}%
          \ifboolKV[ClesTableaux]{Micro}{%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,0001} ou $\dfrac{\strut1}{\strut\num{10000}}$}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,00001} ou $\dfrac{\strut1}{\strut\num{100000}}$}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,000001} ou $\dfrac{\strut1}{\strut\num{1000000}}$}%
          }{%
            \ifboolKV[ClesTableaux]{Nano}{%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,0001} ou $\dfrac{\strut1}{\strut\num{10000}}$}%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,00001} ou $\dfrac{\strut1}{\strut\num{100000}}$}%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,000001} ou $\dfrac{\strut1}{\strut\num{1000000}}$}%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,0000001} ou $\dfrac{\strut1}{\strut\num{10000000}}$}%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,00000001} ou $\dfrac{\strut1}{\strut\num{100000000}}$}%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,000000001} ou $\dfrac{\strut1}{\strut\num{1000000000}}$}%
            }{}%
          }{}\\%
        }{}%
      	%%% Prise en compte de la cl\'e Puissances
        \ifboolKV[ClesTableaux]{Puissances}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
          \Block[borders={left,right}]{}{}&%
          \Block[borders={right}]{}{}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^{9}$}%
          &\Block[borders={right}]{}{}%
          &\Block[borders={right}]{}{}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^{6}$}%
          &\Block[borders={right}]{}{}%
        }{%
        \ifboolKV[ClesTableaux]{Millions}{%
          \Block[borders={left,right}]{}{}&%
          \Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^{6}$}%
        &%
        }{%
        }}%
        \Block[borders={left,right}]{}{}&\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^3$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^2$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^1$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{1}$}%
        &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-1}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-2}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-3}$}%
        \ifboolKV[ClesTableaux]{Micro}{&%
          \Block[borders={right}]{}{}&%
          \Block[borders={right}]{}{}&
          \Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-6}$}}{%
      	\ifboolKV[ClesTableaux]{Nano}{&%
          \Block[borders={right}]{}{}&%
        \Block[borders={right}]{}{}&%
        \Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-6}$}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-9}$}}{}%
      	}%
        \\%
        }{}%
        %
      	%%% Lignes vierges
      	%
        \hline%
        \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&%
          }{%
            \ifboolKV[ClesTableaux]{Millions}{%
              &&&%
            }{%
            }}%
          &&&&&&,&&&%
          \ifboolKV[ClesTableaux]{Micro}{&&&}{%
            \ifboolKV[ClesTableaux]{Nano}{&&&&&&}{}%
          }%
          \\}%
        \CodeAfter%
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{\fpeval{\PfCDerniereColonne+1}}}\do{%
          \tikz\draw (\fpeval{\DecalageLigne+2}-|##1)--(\fpeval{\DecalageLigne+2+\useKV[ClesTableaux]{NbLignes}}-|##1);%
        }%
        %% On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonneEntiere{13}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonneEntiere{10}}{\xdef\PfCDerniereColonneEntiere{7}}}%
        \xdef\PfCPremiereColonneDecimale{\fpeval{\PfCDerniereColonneEntiere+2}}%
        \setsepchar[*]{,*.}%
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{%
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {\TabLongueurNombre}{1}}\do{%
            \tikz\node at (\fpeval{\DecalageLigne+##2+1.5}-|\fpeval{\PfCDerniereColonneEntiere-0.5-\TabLongueurNombre+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};%
          }%
          \StrLen{\ListeNombreAPlacer[##2,2]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{\DecalageLigne+##2+1.5}-|\fpeval{\PfCPremiereColonneDecimale-1.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,2]}{##1}{##1}};%
          }%
        }%
        \fi%
      \end{NiceTabular}%
    \end{center}%
    \setlength{\tabcolsep}{100\tabcolsep}%
  }{}%
  %
  %%% Puissances seules
  %
  \ifboolKV[ClesTableaux]{PuissancesSeules}{%
    \setlength{\PfCTableauPuissances}{3em}%
    \xdef\DecalageLigne{0}%
    \setlength{\tabcolsep}{0.01\tabcolsep}%
    \begin{center}%
      % 
      %%% Definition du tableau
      % 
      \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonne{16}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonne{13}}{\xdef\PfCDerniereColonne{10}}}%
      \begin{NiceTabular}{*{\ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }}{m{\PfCTableauPuissances}}>{\columncolor{gray!15}}{c}*{3}{m{\PfCTableauPuissances}}}%
        \CodeBefore
        \xintifboolexpr{\useKV[ClesTableaux]{Colonne}>0}{%
          \tikz\fill[gray!15] (1-|\fpeval{\useKV[ClesTableaux]{Colonne}}) rectangle (last-|\fpeval{\useKV[ClesTableaux]{Colonne}+1});
        }{}
        \Body
        \hline
      	% 
      	%%% Prise en compte de la cl\'e Partie
%      	% 
%        \ifboolKV[ClesTableaux]{Partie}{%
%          \Block[]{1-%
%            \ifboolKV[ClesTableaux]{Milliards}{12}{%
%              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
%            }}{\bfseries Partie enti\`ere}\ifboolKV[ClesTableaux]{Milliards}{%
%            &&&&&&%
%          }{%
%            \ifboolKV[ClesTableaux]{Millions}{%
%              &&&%
%            }{%
%            }}%
%          &&&&&%
%          &\Block[fill=gray!15]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}\xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%%
%          &\Block[]{1-3}{\bfseries Partie d\'ecimale}%
%          &&\\
%        }{}%
%        %
%      	%%% Prise en compte de la cl\'e Classes
%      	%
%        \ifboolKV[ClesTableaux]{Classes}{%
%          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}\ifboolKV[ClesTableaux]{Milliards}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurG}}]{1-3}{Classe des milliards}&&&\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}%
%          \ifboolKV[ClesTableaux]{Millions}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}%
%          \Block[draw,fill={\useKV[ClesTableaux]{Couleurm}}]{1-3}{Classe des milliers}&&%
%          &\Block[draw,fill={\useKV[ClesTableaux]{Couleuru}}]{1-3}{Classe des unités}&&
%          &\Block[draw,fill=gray!15]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
%          &\Block[draw]{1-3}{}&&%
%          \\
%        }{}%
        % 
        %%% Valeurs ci-dessous par d\'efaut
        %
        %Affichage ou pas des noms ?
%        \hline
%        \ifboolKV[ClesTableaux]{Milliards}{%
%          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont centaines de milliards}%
%          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de milliards}%
%          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont unit\'es de milliards}%
%          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont centaines de millions}%
%          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de millions}%
%          &\Block[]{}{\fontsize{5}{5}\selectfont unit\'es de millions}%
%          &
%        }{}%
%        \ifboolKV[ClesTableaux]{Millions}{%
%          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont centaines de millions}%
%          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de millions}%
%          &\Block[]{}{\fontsize{5}{5}\selectfont unit\'es de millions}%
%          &
%        }{}%
%        \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont centaines de milliers}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de milliers}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont unit\'es de milliers}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont centaines}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont unit\'es}%
%        &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dixi\`emes}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont centi\`emes}%
%        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont milli\`emes}\\
%        %
      	%%% Prise en compte de la cl\'e Nombres
      	%
        \ifboolKV[ClesTableaux]{Nombres}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont\num{100000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont\num{10000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont\num{1000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{100000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000000}}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont \num{1000000}}%
            &%
          }{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont \num{100000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000000}}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont \num{1000000}}%
            &%
          }{}%
          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont \num{100000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{1000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{100}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{1}}%
          &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,1} ou $\dfrac{\strut1}{\strut10}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,01} ou $\dfrac{\strut1}{\strut100}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,001} ou $\dfrac{\strut1}{\strut\num{1000}}$}%
          \\
        }{}%
        %%% Prise en compte de la cl\'e Puissances
        \ifboolKV[ClesTableaux]{Milliards}{%
          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont $10^{11}$}&%
          \Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^{10}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^{9}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^{8}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^{7}$}%
          &\Block[borders={}]{}{\fontsize{5}{5}\selectfont $10^{6}$}%
          &%
        }{%
          \ifboolKV[ClesTableaux]{Millions}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont $10^{8}$}&%
            \Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^{7}$}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont $10^{6}$}%
            &%
          }{%
          }}%
        \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont $10^{5}$}
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^{4}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $10^3$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\num{d2}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\num{d1}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\num{10}^0$}%
        &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\num{10}^{-1}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\num{10}^{-2}$}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\num{10}^{-3}$}%
        \\%
        %%% Lignes vierges
        \hline%
        \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&}{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            &&&}{}%
          &&&&&&\ifboolKV[ClesTableaux]{Virgule}{,}{\phantom{,}}&&&\\}%
        \CodeAfter%
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{\fpeval{\PfCDerniereColonne+1}}}\do{%
          \tikz\draw (\fpeval{\DecalageLigne+2}-|##1)--(\fpeval{\DecalageLigne+2+\useKV[ClesTableaux]{NbLignes}}-|##1);%
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar[*]{,*/}%
        \readlist*\ListeNombreAPlacer{#2}%
        \setsepchar{,}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{##2+1.5}-|\fpeval{\ListeNombreAPlacer[##2,2]-0.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};
          }%
        }
        \fi%
      \end{NiceTabular}%
    \end{center}%
    \setlength{\tabcolsep}{100\tabcolsep}%
  }{}%
  %
  %%% Cl\'e Entiers
  %
  \ifboolKV[ClesTableaux]{Entiers}{%
    \xdef\DecalageLigne{0}%
    \xdef\TailleFonte{\useKV[ClesTableaux]{Taille}}%
    \setlength{\tabcolsep}{0.01\tabcolsep}%
    \begin{center}%
      % 
      %%% Definition du tableau
      % 
      \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonne{13}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonne{10}}{\xdef\PfCDerniereColonne{7}}}%
      \begin{NiceTabular}{*{%
            \ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }%
          }{m{\useKV[ClesTableaux]{Largeur}}}}%
        \ifboolKV[ClesTableaux]{Classes}{%
          \hline
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}\ifboolKV[ClesTableaux]{Milliards}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurG}}]{1-3}{Classe des milliards}&&&\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&%
          }{}
          \ifboolKV[ClesTableaux]{Millions}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}
          \Block[draw,fill={\useKV[ClesTableaux]{Couleurm}}]{1-3}{Classe des milliers}&&%
          &\Block[draw,fill={\useKV[ClesTableaux]{Couleuru}}]{1-3}{Classe des unités}&&\\}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            \Block[]{}{}&\Block[]{}{}&\Block[]{}{}&\Block[]{}{}&\Block[]{}{}&\Block[]{}{}&}{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            \Block[]{}{}&\Block[]{}{}&\Block[]{}{}&}{}%
          \Block[]{}{}
          &\Block[]{}{}
          &\Block[]{}{}
          &\Block[]{}{}
          &\Block[]{}{}
          &\Block[]{}{}\\
        }%ok
        \hline
        \ifboolKV[ClesTableaux]{Milliards}{%
          \Block[draw]{}{\fontsize{\TailleFonte}{\TailleFonte}\selectfont centaines de milliards}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont dizaines de milliards}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont unit\'es de milliards}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont centaines de millions}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont dizaines de millions}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont unit\'es de millions}%
          &
        }{}
        \ifboolKV[ClesTableaux]{Millions}{%
          \Block[draw]{}{\fontsize{5}{5}\selectfont centaines de millions}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont dizaines de millions}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont unit\'es de millions}%
          &
        }{}
        \Block[draw]{}{\fontsize{5}{5}\selectfont centaines de milliers}%
        &\Block[draw]{}{\fontsize{5}{5}\selectfont dizaines de milliers}%
        &\Block[draw]{}{\fontsize{5}{5}\selectfont unit\'es de milliers}%
        &\Block[draw]{}{\fontsize{5}{5}\selectfont centaines}%
        &\Block[draw]{}{\fontsize{5}{5}\selectfont dizaines}%
        &\Block[draw]{}{\fontsize{5}{5}\selectfont unit\'es}\\%
        \ifboolKV[ClesTableaux]{Nombres}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            \Block[draw]{}{\fontsize{5}{5}\selectfont\num{100000000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{10000000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{1000000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{100000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{10000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{1000000}}%
            &%
          }{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            \Block[draw]{}{\fontsize{5}{5}\selectfont\num{100000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{10000000}}%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{1000000}}%
            &%
          }{}%
          \Block[draw]{}{\fontsize{5}{5}\selectfont\num{100000}}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{10000}}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{1000}}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{100}}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{10}}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont\num{1}}%
          \\
        }{}%
        % 
        %%% Prise en compte de la cl\'e Puissances
        % 
        \ifboolKV[ClesTableaux]{Puissances}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times10^{9}$}%
            &%
            &%
            &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times10^{6}$}%
            &%
          }{%
            \ifboolKV[ClesTableaux]{Millions}{%
              &%
              &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times10^{6}$}%
              &%
            }{%
            }}%
          &%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times10^3$}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times\num{10}^2$}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times\num{10}^1$}%
          &\Block[draw]{}{\fontsize{5}{5}\selectfont $\times\num{1}$}%
          \\%
        }{}%
        % 
        %%% Lignes vierges
        % 
        \hline%
        \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&}{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            &&&}{}%
          &&&&&\\}%
        \ifboolKV[ClesTableaux]{Milliards}{%
          \Block[]{}{\tikz[remember picture,overlay]{\coordinate (L1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (K1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (J1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (I1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (H1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (G1);}}&}{}%
        \ifboolKV[ClesTableaux]{Millions}{%
          \Block[]{}{\tikz[remember picture,overlay]{\coordinate (I1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (H1);}}&\Block[]{}{\tikz[remember picture,overlay]{\coordinate (G1);}}&}{}%
        \Block[]{}{\tikz[remember picture,overlay]{\coordinate (F1);}}
        &\Block[]{}{\tikz[remember picture,overlay]{\coordinate (E1);}}
        &\Block[]{}{\tikz[remember picture,overlay]{\coordinate (D1);}}
        &\Block[]{}{\tikz[remember picture,overlay]{\coordinate (C1);}}
        &\Block[]{}{\tikz[remember picture,overlay]{\coordinate (B1);}}
        &\Block[]{}{\tikz[remember picture,overlay]{\coordinate (A1);}}\\
        \CodeAfter%
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{\PfCDerniereColonne}}\do{%
          \tikz\draw (\fpeval{\DecalageLigne+1}-|##1)--(\fpeval{\DecalageLigne+1+\useKV[ClesTableaux]{NbLignes}+1}-|##1);%
        }%
        %% On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar{,}%
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{%
          \StrLen{\ListeNombreAPlacer[##2]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {\TabLongueurNombre}{1}}\do{%
            \tikz\node at (\fpeval{\DecalageLigne+##2+1.5}-|\fpeval{\PfCDerniereColonne-0.5-\TabLongueurNombre+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2]}{##1}{##1}};%
          }%
        }%
        \fi%
        % On trace les éventuelles fleches
        \ifboolKV[ClesTableaux]{Fleches}{\setKV[ClesTableaux]{FlechesH,FlechesB}}{}%%
        \ifboolKV[ClesTableaux]{Classes}{}{%
          \ifboolKV[ClesTableaux]{FlechesB}{%
            \ifboolKV[ClesTableaux]{Milliards}{%
              \xintFor* ##1 in {\xintSeq{1}{11}}\do{%
                \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{1.5+##1}) to node[below, midway]{\small$\div\num{10}$}(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{0.5+##1});%
              }%
            }{%
              \ifboolKV[ClesTableaux]{Millions}{%
                \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
                  \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{1.5+##1}) to node[below, midway]{\small$\div\num{10}$}(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{0.5+##1});%
                }%
              }{%
                \xintFor* ##1 in {\xintSeq{1}{5}}\do{%
                  \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{1.5+##1}) to node[below, midway]{\small$\div\num{10}$}(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{0.5+##1});%
                }%
              }%
            }%
          }{}%
          \ifboolKV[ClesTableaux]{FlechesH}{%
            \ifboolKV[ClesTableaux]{Milliards}{%
              \xintFor* ##1 in {\xintSeq{1}{11}}\do{%
                \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{0.5+##1}) to node[above, midway]{\small$\times\num{10}$}(1.5-|\fpeval{1.5+##1});%
              }%
            }{%
              \ifboolKV[ClesTableaux]{Millions}{%
                \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
                  \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{0.5+##1}) to node[above, midway]{\small$\times\num{10}$}(1.5-|\fpeval{1.5+##1});%
                }%
              }{%
                \xintFor* ##1 in {\xintSeq{1}{5}}\do{%
                  \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{0.5+##1}) to node[above, midway]{\small$\times\num{10}$}(1.5-|\fpeval{1.5+##1});%
                }%
              }%
            }%
          }{}%
        }%
        \useKV[ClesTableaux]{CodeAfter}%
      \end{NiceTabular}%
    \end{center}%
    \setlength{\tabcolsep}{100\tabcolsep}%
  }{}%
  % 
  %%% Cl\'e Decimaux
  % 
  \ifboolKV[ClesTableaux]{Decimaux}{%
    \xdef\DecalageLigne{0}%
    \setlength{\tabcolsep}{0.01\tabcolsep}%
    \begin{center}%
      % 
      %%% Definition du tableau
      % 
      \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonne{16}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonne{13}}{\xdef\PfCDerniereColonne{10}}}%
      \begin{NiceTabular}{*{\ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }}{m{4.75em}}>{\columncolor{gray!15}}{c}*{3}{m{4.75em}}}%
      	% 
      	%%% Prise en compte de la cl\'e Partie
      	% 
        \ifboolKV[ClesTableaux]{Partie}{%
          \Block[]{1-%
            \ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }}{\bfseries Partie enti\`ere}\ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&%
          }{%
            \ifboolKV[ClesTableaux]{Millions}{%
              &&&%
            }{%
            }}%
          &&&&&%
          &\Block[fill=gray!15]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}\xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%%
          &\Block[]{1-3}{\bfseries Partie d\'ecimale}%
          &&\\
        }{}%
        %
      	%%% Prise en compte de la cl\'e Classes
      	%
        \ifboolKV[ClesTableaux]{Classes}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}\ifboolKV[ClesTableaux]{Milliards}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurG}}]{1-3}{Classe des milliards}&&&\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}%
          \ifboolKV[ClesTableaux]{Millions}{\Block[draw,fill={\useKV[ClesTableaux]{CouleurM}}]{1-3}{Classe des millions}&&&}{}%
          \Block[draw,fill={\useKV[ClesTableaux]{Couleurm}}]{1-3}{Classe des milliers}&&%
          &\Block[draw,fill={\useKV[ClesTableaux]{Couleuru}}]{1-3}{Classe des unités}&&
          &\Block[draw,fill=gray!15]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[draw]{1-3}{}&&%
          \\
        }{}%
        % 
        %%% Valeurs ci-dessous par d\'efaut
        % 
        \hline
        \ifboolKV[ClesTableaux]{Milliards}{%
          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont centaines de milliards}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de milliards}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont unit\'es de milliards}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont centaines de millions}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de millions}%
          &\Block[]{}{\fontsize{5}{5}\selectfont unit\'es de millions}%
          &
        }{}%
        \ifboolKV[ClesTableaux]{Millions}{%
          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont centaines de millions}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de millions}%
          &\Block[]{}{\fontsize{5}{5}\selectfont unit\'es de millions}%
          &
        }{}%
        \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont centaines de milliers}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines de milliers}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont unit\'es de milliers}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont centaines}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dizaines}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont unit\'es}%
        &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont dixi\`emes}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont centi\`emes}%
        &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont milli\`emes}\\
        %
      	%%% Prise en compte de la cl\'e Nombres
      	%
        \ifboolKV[ClesTableaux]{Nombres}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont\num{100000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont\num{10000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont\num{1000000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{100000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000000}}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont \num{1000000}}%
            &%
          }{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont \num{100000000}}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000000}}%
            &\Block[borders={}]{}{\fontsize{5}{5}\selectfont \num{1000000}}%
            &%
          }{}%
          \Block[borders={left,right}]{}{\fontsize{5}{5}\selectfont \num{100000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{1000}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{100}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{10}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{1}}%
          &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,1} ou $\dfrac{\strut1}{\strut10}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,01} ou $\dfrac{\strut1}{\strut100}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont \num{0,001} ou $\dfrac{\strut1}{\strut\num{1000}}$}%
          \\
        }{}%
        %
        %%% Prise en compte de la cl\'e Puissances
        %
        \ifboolKV[ClesTableaux]{Puissances}{%
          \xdef\DecalageLigne{\fpeval{\DecalageLigne+1}}%
          \ifboolKV[ClesTableaux]{Milliards}{%
            \Block[borders={left,right}]{}{}&%
            \Block[borders={right}]{}{}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^{9}$}%
            &\Block[borders={right}]{}{}%
            &\Block[borders={right}]{}{}%
            &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^{6}$}%
            &\Block[borders={right}]{}{}%
          }{%
            \ifboolKV[ClesTableaux]{Millions}{%
              \Block[borders={left,right}]{}{}&%
              \Block[borders={right}]{}{}%
              &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^{6}$}%
              &%
            }{%
            }}%
          \Block[borders={left,right}]{}{}&\Block[borders={right}]{}{}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times10^3$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^2$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^1$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{1}$}%
          &\Block[borders={right}]{}{\ifboolKV[ClesTableaux]{Virgule}{,}{}}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-1}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-2}$}%
          &\Block[borders={right}]{}{\fontsize{5}{5}\selectfont $\times\num{10}^{-3}$}%
          \\%
        }{}%
        %
        %%% Lignes vierges
        %
        \hline%
        \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&}{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            &&&}{}%
          &&&&&&,&&&\\}%
        \CodeAfter%
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{\fpeval{\PfCDerniereColonne+1}}}\do{%
          \tikz\draw (\fpeval{\DecalageLigne+2}-|##1)--(\fpeval{\DecalageLigne+2+\useKV[ClesTableaux]{NbLignes}}-|##1);%
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonneEntiere{13}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonneEntiere{10}}{\xdef\PfCDerniereColonneEntiere{7}}}%
        \xdef\PfCPremiereColonneDecimale{\fpeval{\PfCDerniereColonneEntiere+2}}%
        \setsepchar[*]{,*.}%
        \ignoreemptyitems%
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{%
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {\TabLongueurNombre}{1}}\do{%
            \tikz\node at (\fpeval{\DecalageLigne+##2+1.5}-|\fpeval{\PfCDerniereColonneEntiere-0.5-\TabLongueurNombre+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};%
          }%
          \StrLen{\ListeNombreAPlacer[##2,2]}[\TabLongueurNombre]%
          \xintifboolexpr{\ListeNombreAPlacer[##2,2]==0}{}{%
            \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
              \tikz\node at (\fpeval{\DecalageLigne+##2+1.5}-|\fpeval{\PfCPremiereColonneDecimale-1.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,2]}{##1}{##1}};%
            }%
          }%
        }%
        \fi%
      \end{NiceTabular}%
    \end{center}%
    \setlength{\tabcolsep}{100\tabcolsep}%
  }{}%
  % Décimal version inclinée
  \ifboolKV[ClesTableaux]{Incline}{%
    \colorlet{PfCCouleurd}{\useKV[ClesTableaux]{Couleurd}}%
    \xdef\DecalageLigne{0}%
    \setlength{\tabcolsep}{0.01\tabcolsep}%
    \begin{center}%
      %
      %%% Definition du tableau
      %
      \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonne{17}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonne{14}}{\xdef\PfCDerniereColonne{11}}}%
      \begin{NiceTabular}{*{\ifboolKV[ClesTableaux]{Milliards}{12}{%
              \ifboolKV[ClesTableaux]{Millions}{9}{6}%
            }}{wc{1cm}}*{5}{wc{1cm}}}%
        %
        \CodeBefore%
        \ifboolKV[ClesTableaux]{Milliards}{%
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurG}}] (1|-5)--(2|-1)--(3|-1)--(2|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurG}}] (2|-5)--(3|-1)--(4|-1)--(3|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurG}}] (3|-5)--(4|-1)--(5|-1)--(4|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurM}}] (4|-5)--(5|-1)--(6|-1)--(5|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurM}}] (5|-5)--(6|-1)--(7|-1)--(6|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurM}}] (6|-5)--(7|-1)--(8|-1)--(7|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (7|-5)--(8|-1)--(9|-1)--(8|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (8|-5)--(9|-1)--(10|-1)--(9|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (9|-5)--(10|-1)--(11|-1)--(10|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (10|-5)--(11|-1)--(12|-1)--(11|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (11|-5)--(12|-1)--(13|-1)--(12|-5)--cycle;
          \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (12|-5)--(13|-1)--(14|-1)--(13|-5)--cycle;
          \tikz\draw[draw=black,fill=PfCCouleurd!50] (13|-5)--(14|-1)--(15|-1)--(14|-5)--cycle;
          \tikz\draw[draw=black,fill=PfCCouleurd!40] (14|-5)--(15|-1)--(16|-1)--(15|-5)--cycle;
          \tikz\draw[draw=black,fill=PfCCouleurd!30] (15|-5)--(16|-1)--(17|-1)--(16|-5)--cycle;
          \tikz\draw[draw=black,fill=PfCCouleurd!20] (16|-5)--(17|-1)--(18|-1)--(17|-5)--cycle;
        }{\ifboolKV[ClesTableaux]{Millions}{%
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurM}}] (1|-5)--(2|-1)--(3|-1)--(2|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurM}}] (2|-5)--(3|-1)--(4|-1)--(3|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{CouleurM}}] (3|-5)--(4|-1)--(5|-1)--(4|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (4|-5)--(5|-1)--(6|-1)--(5|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (5|-5)--(6|-1)--(7|-1)--(6|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (6|-5)--(7|-1)--(8|-1)--(7|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (7|-5)--(8|-1)--(9|-1)--(8|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (8|-5)--(9|-1)--(10|-1)--(9|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (9|-5)--(10|-1)--(11|-1)--(10|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!50] (10|-5)--(11|-1)--(12|-1)--(11|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!40] (11|-5)--(12|-1)--(13|-1)--(12|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!30] (12|-5)--(13|-1)--(14|-1)--(13|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!20] (13|-5)--(14|-1)--(15|-1)--(14|-5)--cycle;
          }{%
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (1|-5)--(2|-1)--(3|-1)--(2|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (2|-5)--(3|-1)--(4|-1)--(3|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleurm}}] (3|-5)--(4|-1)--(5|-1)--(4|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (4|-5)--(5|-1)--(6|-1)--(5|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (5|-5)--(6|-1)--(7|-1)--(6|-5)--cycle;
            \tikz\draw[draw=black,fill={\useKV[ClesTableaux]{Couleuru}}] (6|-5)--(7|-1)--(8|-1)--(7|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!50] (7|-5)--(8|-1)--(9|-1)--(8|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!40] (8|-5)--(9|-1)--(10|-1)--(9|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!30] (9|-5)--(10|-1)--(11|-1)--(10|-5)--cycle;
            \tikz\draw[draw=black,fill=PfCCouleurd!20] (10|-5)--(11|-1)--(12|-1)--(11|-5)--cycle;
          }%
        }%
        \Body
        %% Pour décaler et laisser la place nécessaire
        \xintFor* ##1 in {\xintSeq{1}{4}}\do{%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&}{}%
          \ifboolKV[ClesTableaux]{Millions}{%
            &&&}{}%
          &&&&&&&&&&\\}%
        %%% Lignes vierges       
        %
        \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          \ifboolKV[ClesTableaux]{Milliards}{%
            &&&&&&}{}%                         
          \ifboolKV[ClesTableaux]{Millions}{%
            &&&}{}%
          &&&&&&&&&&\\}%
        \CodeAfter%%
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{2}{\fpeval{\PfCDerniereColonne-1}}}\do{%
          \tikz\draw[dashed] (\fpeval{\DecalageLigne+5}-|##1)--(\fpeval{\DecalageLigne+5+\useKV[ClesTableaux]{NbLignes}}-|##1);%
        }%
        \tikz\draw (\fpeval{\DecalageLigne+5}-|1)--(\fpeval{\DecalageLigne+5+\useKV[ClesTableaux]{NbLignes}}-|1);%
        \tikz\draw (\fpeval{\DecalageLigne+5}-|\fpeval{\PfCDerniereColonne})--(\fpeval{\DecalageLigne+5+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{\PfCDerniereColonne});%
        %% On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \ifboolKV[ClesTableaux]{Milliards}{\xdef\PfCDerniereColonneEntiere{13}}{\ifboolKV[ClesTableaux]{Millions}{\xdef\PfCDerniereColonneEntiere{10}}{\xdef\PfCDerniereColonneEntiere{7}}}%
        \xdef\PfCPremiereColonneDecimale{\fpeval{\PfCDerniereColonneEntiere+1}}%
        \setsepchar[*]{,*.}%
        \ignoreemptyitems%
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{%
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {\TabLongueurNombre}{1}}\do{%
            \tikz\node at (\fpeval{\DecalageLigne+##2+4.5}-|\fpeval{\PfCDerniereColonneEntiere-0.5-\TabLongueurNombre+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};%
          }%
          \StrLen{\ListeNombreAPlacer[##2,2]}[\TabLongueurNombre]%
          \xintifboolexpr{\ListeNombreAPlacer[##2,2]==0}{}{%
            %On place la virgule
            \tikz\node[xshift=1em] at (\fpeval{\DecalageLigne+##2+4.5}-|\fpeval{\PfCDerniereColonneEntiere-0.5-\TabLongueurNombre+1}) {\PfCTBstrut,};%
            %on écrit la partie décimale
            \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
              \tikz\node at (\fpeval{\DecalageLigne+##2+4.5}-|\fpeval{\PfCPremiereColonneDecimale-1.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,2]}{##1}{##1}};%
            }%
          }%
        }%
        \fi%
        \ifboolKV[ClesTableaux]{Milliards}{%
          \tikz\node[rotate=58] at (2|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\\de milliards\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (3|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\\de milliards\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (4|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Milliards\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (5|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\\de millions\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (6|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\\de millions\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (7|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Millions\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (8|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\\de milliers\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (9|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\\de milliers\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (10|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Milliers\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (11|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (12|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (13|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Unités\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (14|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dixièmes\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (15|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centièmes\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (16|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Millièmes\end{center}\end{minipage}};
          \tikz\node[rotate=58] at (17|-3) {\begin{minipage}{2cm}\begin{center}\scriptsize Dix-millièmes\end{center}\end{minipage}};
        }{\ifboolKV[ClesTableaux]{Millions}{%
            \tikz\node[rotate=58] at (2|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\\de millions\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (3|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\\de millions\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (4|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Millions\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (5|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\\de milliers\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (6|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\\de milliers\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (7|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Milliers\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (8|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (9|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (10|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Unités\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (11|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dixièmes\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (12|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centièmes\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (13|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Millièmes\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (14|-3) {\begin{minipage}{2cm}\begin{center}\scriptsize Dix-millièmes\end{center}\end{minipage}};
          }{%
            \tikz\node[rotate=58] at (2|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\\de milliers\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (3|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\\de milliers\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (4|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Milliers\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (5|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centaines\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (6|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dizaines\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (7|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Unités\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (8|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Dixièmes\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (9|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Centièmes\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (10|-3) {\begin{minipage}{1.5cm}\begin{center}\scriptsize Millièmes\end{center}\end{minipage}};
            \tikz\node[rotate=58] at (11|-3) {\begin{minipage}{2cm}\begin{center}\scriptsize Dix-millièmes\end{center}\end{minipage}};
          }%
        }%
      \end{NiceTabular}%
    \end{center}%
    \setlength{\tabcolsep}{100\tabcolsep}%
  }{}%  
  %
  %%% Prise en compte de la cl\'e Metre
  %
  \ifboolKV[ClesTableaux]{Metre}{%
    \[\renewcommand{\arraystretch}{1.15}%
      \begin{NiceTabular}{*{7}{wc{7.5mm}}}%
        \Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}\\
        \Block[draw]{}{km\PfCTBstrut}&\Block[draw]{1-1}{hm\PfCTBstrut}&\Block[draw]{1-1}{dam\PfCTBstrut}&\Block[draw]{1-1}{m\PfCTBstrut}&\Block[draw]{1-1}{dm\PfCTBstrut}&\Block[draw]{1-1}{cm\PfCTBstrut}&\Block[draw]{1-1}{mm\PfCTBstrut}\\
        \xintFor* ##1 in {\xintSeq {1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          &&&&&&\\
        }%
        \Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}\\
        \CodeAfter
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
          \tikz\draw (3-|##1)--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|##1);
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar[*]{,*/}
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{##2+2.5}-|\fpeval{\ListeNombreAPlacer[##2,2]-0.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};
          }%
        }
        \fi%
        % on trace les flèches
        \ifboolKV[ClesTableaux]{Fleches}{\setKV[ClesTableaux]{FlechesH,FlechesB}}{}%
        \ifboolKV[ClesTableaux]{FlechesH}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{0.5+##1}) to node[above, midway]{\small$\times\num{10}$}(1.5-|\fpeval{1.5+##1});%
          }%
        }{}%
        \ifboolKV[ClesTableaux]{FlechesB}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{3+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{1.5+##1}) to node[below,midway]{\small$\div\num{10}$}(\fpeval{3+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{0.5+##1});%
          }%
        }{}%
        \useKV[ClesTableaux]{CodeAfter}%
      \end{NiceTabular}%
    \]%
  }%
  {}%
  
  %
  %%% Prise en compte de la cl\'e Carre
  %
  \ifboolKV[ClesTableaux]{Carre}{%
    \[\renewcommand{\arraystretch}{1.15}%
      \begin{NiceTabular}{*{7}{wc{3.5mm}wc{3.5mm}}}%
        \Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}\\
        \Block[borders={left,top,right}]{1-2}{km$^2$\PfCTBstrut}&&\Block[borders={top,right}]{1-2}{hm$^2$\PfCTBstrut}&&\Block[borders={top,right}]{1-2}{dam$^2$\PfCTBstrut}&&\Block[borders={top,right}]{1-2}{m$^2$\PfCTBstrut}&&\Block[borders={top,right}]{1-2}{dm$^2$\PfCTBstrut}&&\Block[borders={top,right}]{1-2}{cm$^2$\PfCTBstrut}&&\Block[borders={top,right}]{1-2}{mm$^2$\PfCTBstrut}&\\
        \ifboolKV[ClesTableaux]{Are}{%
          \Block[borders={left,right,bottom}]{1-2}{}&&\Block[draw=gray!50,borders={left,top,bottom}]{}{~}&\Block[borders={top,right,bottom}]{}{\scriptsize ha}&\Block[draw=gray!50,borders={left,top,bottom}]{}{~}&\Block[borders={top,right,bottom}]{}{\scriptsize a}&\Block[borders={left,right,bottom}]{1-2}{}&&\Block[borders={left,right,bottom}]{1-2}{}&&\Block[borders={left,right,bottom}]{1-2}{}&&\Block[borders={left,right,bottom}]{1-2}{}&\\
        }{\hline}%
        \xintFor* ##1 in {\xintSeq {1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          &&&&&&&&&&&&&\\
        }%
        \Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}%
        &&\Block[]{1-2}{}\\
        \CodeAfter
        % on trace les lignes verticales
        \xintifboolexpr{\useKV[ClesTableaux]{Are}}{%
          \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
            \tikz\draw (4-|\fpeval{2*(##1-1)+1})--(\fpeval{4+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{2*(##1-1)+1});
          }%
          \xintFor* ##1 in {\xintSeq{1}{7}}\do{%
            \tikz\draw[gray!50] (4-|\fpeval{2*(##1-1)+2})--(\fpeval{4+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{2*(##1-1)+2});
          }%
        }{%
          \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
            \tikz\draw (3-|\fpeval{2*(##1-1)+1})--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{2*(##1-1)+1});
          }%
          \xintifboolexpr{\useKV[ClesTableaux]{Colonnes}}{%
            \xintFor* ##1 in {\xintSeq{1}{7}}\do{%
              \tikz\draw[gray!50] (3-|\fpeval{2*(##1-1)+2})--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{2*(##1-1)+2});
            }%
          }{}%
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar[*]{,*/}
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{##2+\ifboolKV[ClesTableaux]{Are}{3.5}{2.5}}-|\fpeval{\ListeNombreAPlacer[##2,2]-0.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};
          }%
        }
        \fi%
        % on trace les flèches
        \ifboolKV[ClesTableaux]{Fleches}{\setKV[ClesTableaux]{FlechesH,FlechesB}}{}%
        \ifboolKV[ClesTableaux]{Are}{\xdef\PfCTableauDepart{4}}{\xdef\PfCTableauDepart{3}}%
        \ifboolKV[ClesTableaux]{FlechesH}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{2*##1}) to node[above, midway]{\small$\times\num{100}$}(1.5-|\fpeval{2*(##1+1)});%
          }%
        }{}%
        \ifboolKV[ClesTableaux]{FlechesB}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{\PfCTableauDepart+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{2*(##1+1)}) to node[below,midway]{\small$\div\num{100}$}(\fpeval{\PfCTableauDepart+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{2*##1});%
          }%
        }{}%
        \useKV[ClesTableaux]{CodeAfter}%
      \end{NiceTabular}
    \]%
  }{}%
  %
  %%% Prise en compte de la cl\'e Cube
  %
  \ifboolKV[ClesTableaux]{Cube}{%
    \[\renewcommand{\arraystretch}{1.15}%
%      \setlength{\tabcolsep}{0.625\tabcolsep}%
%      \begin{NiceTabular}{*{7}{wc{3.5mm}wc{3.5mm}wc{3.5mm}}}
      \setlength{\tabcolsep}{0.275\tabcolsep}%
      \begin{NiceTabular}{*{7}{wc{15pt}wc{15pt}wc{15pt}}}
        \Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}\\
        \Block[borders={left,top,right}]{1-3}{km$^3$\PfCTBstrut}&&&\Block[borders={top,right}]{1-3}{hm$^3$\PfCTBstrut}&&&\Block[borders={top,right}]{1-3}{dam$^3$\PfCTBstrut}&&&\Block[borders={top,right}]{1-3}{m$^3$\PfCTBstrut}&&&\Block[borders={top,right}]{1-3}{dm$^3$\PfCTBstrut}&&&\Block[borders={top,right}]{1-3}{cm$^3$\PfCTBstrut}&&&\Block[borders={top,right}]{1-3}{mm$^3$\PfCTBstrut}&&\\
        \ifboolKV[ClesTableaux]{Capacite}{%
          \Block[borders={left,right,bottom}]{1-3}{}&&&\Block[borders={right,bottom}]{1-3}{}&&&\Block[borders={right,bottom}]{1-3}{}&&&\Block[borders={right,bottom}]{1-3}{}&&&\Block[draw=gray!50,borders={top,left,bottom}]{}{\scriptsize hL}&\Block[draw=gray!50,borders={top,bottom}]{}{\scriptsize daL}&\Block[draw=gray!50,borders={top,right,bottom}]{}{\scriptsize L}&\Block[draw=gray!50,borders={top,left,bottom}]{}{\scriptsize dL}&\Block[draw=gray!50,borders={top,bottom}]{}{\scriptsize cL}&\Block[draw=gray!50,borders={top,right,bottom}]{}{\scriptsize mL}&\Block[borders={right,bottom}]{1-3}{}&&\\
        }{\hline}%
        \xintFor* ##1 in {\xintSeq{1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
        &&&&&&&&&&&&&&&&&&&&\\
        }%
        \Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}%
        &&&\Block[]{1-3}{}\\
        \CodeAfter
        % on trace les lignes verticales
        \xintifboolexpr{\useKV[ClesTableaux]{Capacite}}{%
          \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
            \tikz\draw (4-|\fpeval{3*(##1-1)+1})--(\fpeval{4+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{3*(##1-1)+1});
          }%
          \xintFor* ##1 in {\xintSeq{1}{7}}\do{%
            \tikz\draw[gray!50] (4-|\fpeval{3*(##1-1)+2})--(\fpeval{4+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{3*(##1-1)+2});
            \tikz\draw[gray!50] (4-|\fpeval{3*##1})--(\fpeval{4+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{3*##1});
          }%
        }{%
          \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
            \tikz\draw (3-|\fpeval{3*(##1-1)+1})--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{3*(##1-1)+1});
          }%
          \xintifboolexpr{\useKV[ClesTableaux]{Colonnes}}{%
            \xintFor* ##1 in {\xintSeq{1}{7}}\do{%
              \tikz\draw[gray!50] (3-|\fpeval{3*(##1-1)+2})--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{3*(##1-1)+2});
              \tikz\draw[gray!50] (3-|\fpeval{3*##1})--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|\fpeval{3*##1});
            }%
          }{}%
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar[*]{,*/}
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{##2+\ifboolKV[ClesTableaux]{Capacite}{3.5}{2.5}}-|\fpeval{\ListeNombreAPlacer[##2,2]-0.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};
          }%
        }%
        \fi%
        % on trace les flèches
        \ifboolKV[ClesTableaux]{Fleches}{\setKV[ClesTableaux]{FlechesH,FlechesB}}{}%
        \ifboolKV[ClesTableaux]{Capacite}{\xdef\PfCTableauDepart{4}}{\xdef\PfCTableauDepart{3}}%
        \ifboolKV[ClesTableaux]{FlechesH}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{2.5+3*(##1-1)}) to node[above, midway]{\small$\times\num{1000}$}(1.5-|\fpeval{2.5+3*##1});%
          }%
        }{}%
        \ifboolKV[ClesTableaux]{FlechesB}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{\PfCTableauDepart+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{2.5+3*##1}) to node[below,midway]{\small$\div\num{1000}$}(\fpeval{\PfCTableauDepart+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{2.5+3*(##1-1)});%
          }%
        }{}%
        \useKV[ClesTableaux]{CodeAfter}%
      \end{NiceTabular}
    \]%
  }{}%
  %
  %%% Prise en compte de la cl\'e Litre
  %
  \ifboolKV[ClesTableaux]{Litre}{%
    \[\renewcommand{\arraystretch}{1.15}%
      \begin{NiceTabular}{*{6}{wc{7.5mm}}}%
        \Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}\\
        \Block[draw]{}{hL\PfCTBstrut}&\Block[draw]{}{daL\PfCTBstrut}&\Block[draw]{}{L\PfCTBstrut}&\Block[draw]{}{dL\PfCTBstrut}&\Block[draw]{}{cL\PfCTBstrut}&\Block[draw]{}{mL\PfCTBstrut}\\
        \xintFor* ##1 in {\xintSeq {1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          &&&&&\\
        }
        \Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}
        &\Block[]{1-1}{}\\
        \CodeAfter
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{7}}\do{%
          \tikz\draw (3-|##1)--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|##1);
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar[*]{,*/}
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{##2+2.5}-|\fpeval{\ListeNombreAPlacer[##2,2]-0.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};
          }%
        }%
        \fi%
        % on trace les flèches
        \ifboolKV[ClesTableaux]{Fleches}{\setKV[ClesTableaux]{FlechesH,FlechesB}}{}%
        \ifboolKV[ClesTableaux]{FlechesH}{%
          \xintFor* ##1 in {\xintSeq{1}{5}}\do{%
            \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{0.5+##1}) to node[above, midway]{\small$\times\num{10}$}(1.5-|\fpeval{1.5+##1});%
          }%
        }{}%
        \ifboolKV[ClesTableaux]{FlechesB}{%
          \xintFor* ##1 in {\xintSeq{1}{5}}\do{%
            \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{3+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{1.5+##1}) to node[below,midway]{\small$\div\num{10}$}(\fpeval{3+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{0.5+##1});%
          }%
        }{}%
        \useKV[ClesTableaux]{CodeAfter}%
      \end{NiceTabular}%
    \]%
  }{}%
  % 
  %%% Prise en compte de la cl\'e Gramme
  % 
  \ifboolKV[ClesTableaux]{Gramme}{%
    \[\renewcommand{\arraystretch}{1.15}%
      \begin{NiceTabular}{*{7}{wc{7.5mm}}}%
        \Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}\\
        \Block[draw]{}{kg\PfCTBstrut}&\Block[draw]{1-1}{hg\PfCTBstrut}&\Block[draw]{1-1}{dag\PfCTBstrut}&\Block[draw]{1-1}{g\PfCTBstrut}&\Block[draw]{1-1}{dg\PfCTBstrut}&\Block[draw]{1-1}{cg\PfCTBstrut}&\Block[draw]{1-1}{mg\PfCTBstrut}\\
        \xintFor* ##1 in {\xintSeq {1}{\useKV[ClesTableaux]{NbLignes}}}\do{%
          &&&&&&\\
        }%
        \Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}
        &\Block[]{}{}\\
        \CodeAfter
        % on trace les lignes verticales
        \xintFor* ##1 in {\xintSeq{1}{8}}\do{%
          \tikz\draw (3-|##1)--(\fpeval{3+\useKV[ClesTableaux]{NbLignes}}-|##1);
        }%
        % On place le nombre éventuel
        \ifx\bla#2\bla%
        \else%
        \setsepchar[*]{,*/}
        \readlist*\ListeNombreAPlacer{#2}%
        \xintFor* ##2 in{\xintSeq {1}{\ListeNombreAPlacerlen}}\do{
          \StrLen{\ListeNombreAPlacer[##2,1]}[\TabLongueurNombre]%
          \xintFor* ##1 in{\xintSeq {1}{\TabLongueurNombre}}\do{%
            \tikz\node at (\fpeval{##2+2.5}-|\fpeval{\ListeNombreAPlacer[##2,2]-0.5+##1}) {\PfCTBstrut\StrMid{\ListeNombreAPlacer[##2,1]}{##1}{##1}};
          }%
        }
        \fi%
        % on trace les flèches
        \ifboolKV[ClesTableaux]{Fleches}{\setKV[ClesTableaux]{FlechesH,FlechesB}}{}%
        \ifboolKV[ClesTableaux]{FlechesH}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=30,in=150] (1.5-|\fpeval{0.5+##1}) to node[above, midway]{\small$\times\num{10}$}(1.5-|\fpeval{1.5+##1});%
          }%
        }{}%
        \ifboolKV[ClesTableaux]{FlechesB}{%
          \xintFor* ##1 in {\xintSeq{1}{6}}\do{%
            \tikz\draw[gray,->,>=latex,out=-150,in=-30] (\fpeval{3+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{1.5+##1}) to node[below,midway]{\small$\div\num{10}$}(\fpeval{3+\useKV[ClesTableaux]{NbLignes}+0.5}-|\fpeval{0.5+##1});%
          }%
        }{}%
        \useKV[ClesTableaux]{CodeAfter}%
      \end{NiceTabular}%
    \]%
  }{}%
}%
}%

\newcommand\PfCTableauIncline{%
\begin{NiceTabular}{wc{30pt}wc{30pt}wc{30pt}wc{30pt}wc{30pt}wc{30pt}wc{30pt}}
  &&&&&&\\
  \Block[borders={bottom}]{}{\si{\kilo\PfCTableauUnite}}&\\
  &\Block[borders={left}]{}{}&\\
  &\Block[borders={left,bottom}]{}{\si{\hecto\PfCTableauUnite}}&\\
  &&\Block[borders={left}]{}{}&\\
  &&\Block[borders={left,bottom}]{}{\si{\deca\PfCTableauUnite}}&\\
  &&&\Block[borders={left}]{}{}&\\
  &&&\Block[borders={left,bottom}]{}{\si{\PfCTableauUnite}}&\\
  &&&&\Block[borders={left}]{}{}&\\
  &&&&\Block[borders={left,bottom}]{}{\si{\deci\PfCTableauUnite}}&\\
  &&&&&\Block[borders={left}]{}{}&\\
  &&&&&\Block[borders={left,bottom}]{}{\si{\centi\PfCTableauUnite}}&\\
  &&&&&&\Block[borders={left}]{}{}\\
  &&&&&&\Block[borders={left,bottom}]{}{\si{\milli\PfCTableauUnite}}\\
  &&&&&&
  \CodeAfter
  \tikz\draw[out=35,in=90,-stealth,gray] (2-|1.5) to node[midway,right]{\footnotesize$\times\num{\PfCCoefConversion}$}(4-|2.5);
  \tikz\draw[out=35,in=90,-stealth,gray] (4-|2.5) to node[midway,right]{\footnotesize$\times\num{\PfCCoefConversion}$}(6-|3.5);
  \tikz\draw[out=35,in=90,-stealth,gray] (6-|3.5) to node[midway,right]{\footnotesize$\times\num{\PfCCoefConversion}$}(8-|4.5);
  \tikz\draw[out=35,in=90,-stealth,gray] (8-|4.5) to node[midway,right]{\footnotesize$\times\num{\PfCCoefConversion}$}(10-|5.5);
  \tikz\draw[out=35,in=90,-stealth,gray] (10-|5.5) to node[midway,right]{\footnotesize$\times\num{\PfCCoefConversion}$}(12-|6.5);
  \tikz\draw[out=35,in=90,-stealth,gray] (12-|6.5) to node[midway,right]{\footnotesize$\times\num{\PfCCoefConversion}$}(14-|7.5);
  % bas
  \tikz\draw[out=215,in=-90,-stealth,gray,transform canvas={yshift=-2mm}] (15-|7.5) to node[midway,left]{\footnotesize$\div\num{\PfCCoefConversion}$}(13-|6.5);
  \tikz\draw[out=215,in=-90,-stealth,gray,transform canvas={yshift=-2mm}] (13-|6.5) to node[midway,left]{\footnotesize$\div\num{\PfCCoefConversion}$}(11-|5.5);
  \tikz\draw[out=215,in=-90,-stealth,gray,transform canvas={yshift=-2mm}] (11-|5.5) to node[midway,left]{\footnotesize$\div\num{\PfCCoefConversion}$}(9-|4.5);
  \tikz\draw[out=215,in=-90,-stealth,gray,transform canvas={yshift=-2mm}] (9-|4.5) to node[midway,left]{\footnotesize$\div\num{\PfCCoefConversion}$}(7-|3.5);
  \tikz\draw[out=215,in=-90,-stealth,gray,transform canvas={yshift=-2mm}] (7-|3.5) to node[midway,left]{\footnotesize$\div\num{\PfCCoefConversion}$}(5-|2.5);
  \tikz\draw[out=215,in=-90,-stealth,gray,transform canvas={yshift=-2mm}] (5-|2.5) to node[midway,left]{\footnotesize$\div\num{\PfCCoefConversion}$}(3-|1.5);
\end{NiceTabular}%
}%

%%%
% Cards
%%%
\newtcolorbox{Mybox}[3]{%
  enhanced,%
  nobeforeafter,%
  left=0pt,right=0pt,top=0pt,%
  text fill,%
  width=\largeurcarte,%
  height=\hauteurcarte,%
  arc=5pt,%
  overlay unbroken and first={%
    \coordinate[yshift=-0.5\hauteurtitre] (A1) at (frame.north west);%
    \coordinate[yshift=-0.5\hauteurtitre] (B1) at (frame.north east);%   
    \coordinate[yshift=-\hauteurtitre] (A) at (frame.north west);%
    \coordinate[yshift=-\hauteurtitre] (B) at (frame.north east);%
    \coordinate[xshift=1.5pt,yshift=8mm] (S1) at (frame.south west);%
    \coordinate[xshift=-1.5pt,yshift=8mm] (S2) at (frame.south east);%
    \coordinate[xshift=3mm+(\largeurtitre/2)] (A2) at (A1);%
    \coordinate[xshift=-3mm-(\largeurtitre/2)] (B2) at (B1);%
    \node[rounded corners, draw=black, rectangle,minimum height=1cm,text width=\largeurtitre,fill=TrameCouleur] (T1) at (A2){};%
    \node[TexteCouleur] (T1a) at (T1){\Large #1};%
    \node[yshift=-0.65cm] (T1b) at (T1){\tiny r\'eponse pr\'ec\'edente};%
    \node[inner sep=0pt,rounded corners, rectangle, draw=black,minimum height=1cm,text width=\largeurtitre,fill=TrameCouleur] (T2) at (B2){};%
    \node[inner sep=0pt,TexteCouleur] (T2a) at (T2){%
      \begin{minipage}{\largeurtitre}%
        \begin{center}%
          #2%
        \end{center}%
      \end{minipage}%
    };%
    \node[yshift=-0.65cm] (T2b) at (T2){};%
    \ifboolKV[Cards]{Titre}{\node[] at (T2b) {\tiny\useKV[Cards]{NomTitre}};}{}%
    \node[rectangle,xshift=5pt,yshift=4.25mm,minimum width=2em,rounded corners,fill=TrameCouleur,draw=black,anchor=west] (R) at (frame.south west) {\color{black}\Large\bfseries #3};%
    \draw[dashed] (S1) -- (S2);%
  },%
  colback=white,%
  colbacktitle=TrameCouleur,%
}

\newtcolorbox{MyboxJQ}[2]{%
  enhanced,
  nobeforeafter,
  left=0pt,right=0pt,top=0pt,
  text fill,
  width=\largeurcarte,
  height=\hauteurcarte,
  arc=5pt,
  overlay unbroken and first={%
    \coordinate[yshift=-0.5\hauteurtitre] (A1) at (frame.north west);
    \coordinate[yshift=0\hauteurtitre] (S3) at (frame.center);
    \coordinate[yshift=3mm] (C3) at (frame.south);
    \coordinate[xshift=\largeurcarte/2] (A3) at (A1);
    \node[rounded corners, draw=black, rectangle,minimum height=1cm,text width=\largeurcarte-6mm,fill=TrameCouleur] (T1) at (A3){};
    \node[TexteCouleur] (T1a) at (T1){\Large J'ai};
    \node[rounded corners, draw=black, rectangle,minimum height=1cm,text width=\largeurcarte-6mm,fill=TrameCouleur] (T2) at (S3){};
    \node[TexteCouleur] (T2a) at (T2){\Large Qui a ?};
    \node[minimum height=1cm,text width=\largeurcarte-6mm] (PointTexte1) at ($(A3)!0.5!(S3)$) {\begin{minipage}{\largeurcarte-6mm}%
        \begin{center}%
          #1%
        \end{center}%
      \end{minipage}};
    \node[minimum height=1cm,text width=\largeurcarte-6mm] (PointTexte2) at ($(C3)!0.5!(S3)$) {\begin{minipage}{\largeurcarte-6mm}%
        \begin{center}%
          #2%
        \end{center}%
      \end{minipage}};
  },
  colback=white,
}

\usetikzlibrary{backgrounds}

\makeatletter
%https://tex.stackexchange.com/questions/347434/clip-background-image-inside-tcolorbox
\newtcolorbox{MyboxSimpleAv}[1]{%
  enhanced,%
  nobeforeafter,%
  left=0pt,right=0pt,top=\hauteurtitre,bottom=0pt,%
  text fill,%
  width=\largeurcarte,%
  height=\hauteurcarte,%
  arc=5pt,%
  colback=white,%
  underlay={%
    \ifboolKV[Cards]{BackgroundAv}{%
      \begin{tcbclipinterior}
        \node[anchor=center,opacity=1]
        at (interior.center) {%
          \includegraphics[%
          height=\tcb@height,
          width=\tcb@width,
          ]{\useKV[Cards]{ImageAv}}};%
      \end{tcbclipinterior},%
    }{}%
  },%
  overlay unbroken and first={%
    \coordinate[yshift=-0.5\hauteurtitre] (A) at (frame.north);%
    \node[rounded corners, draw=black, rectangle,minimum height=1cm,text width=\largeurcarte-6mm,fill=TrameCouleur] (T1) at (A){\begin{minipage}{\largeurcarte-6mm}%
        \begin{center}%
          #1%
        \end{center}%
      \end{minipage}};%
    \node[yshift=-0.5em-0.5\hauteurtitre] (B) at (A){};%
    \ifboolKV[Cards]{Titre}{\node[fill=white] at (B) {\useKV[Cards]{NomTitre}};}{}%
  }%
}%

\newtcolorbox{MyboxSimpleAr}[1]{%
  enhanced,%
  nobeforeafter,%
  left=0pt,right=0pt,top=\hauteurtitre,bottom=0pt,%
  text fill,%
  width=\largeurcarte,%
  height=\hauteurcarte,%
  arc=5pt,%
  colback=white,%
  underlay={%
    \ifboolKV[Cards]{BackgroundAr}{%
      \begin{tcbclipinterior}
        \node[anchor=center,opacity=1]
        at (interior.center) {%
          \includegraphics[%
          height=\tcb@height,
          width=\tcb@width,
          ]{\useKV[Cards]{ImageAr}}};
      \end{tcbclipinterior}%,%
    }{}%
  },%
  overlay unbroken and first={%
    \coordinate[yshift=-0.5\hauteurtitre] (A) at (frame.north);%
    \node[rounded corners, draw=black, rectangle,minimum height=1cm,text width=\largeurcarte-6mm,fill=TrameCouleur] (T1) at (A){\begin{minipage}{\largeurcarte-6mm}%
        \begin{center}%
          #1%
        \end{center}%
      \end{minipage}};%
  }%
}%
\makeatother

\newtcolorbox{MyboxTrivial}[1][]{%
  enhanced,%
  nobeforeafter,%
  left=0pt,right=0pt,top=0pt,bottom=0pt,%
  text fill,%
  width=\largeurcarte,%
  height=\hauteurcarte,%
  arc=5pt,%
  colback=white,%
  #1
}

\newlength{\largeurcards}%
\newlength{\hauteurcards}%
\newlength{\largeurcarte}%
\newlength{\hauteurcarte}%
\newlength{\hauteurtitre}%
\newlength{\largeurtitre}%

\newlength{\margeh}%
\newlength{\margev}%

\NewEnviron{Trame}{%
  \begin{tikzpicture}[remember picture,overlay]
    % quadrillages horizontal et vertical
    \coordinate[yshift=-\margev] (A) at (current page.north west);%
    \coordinate[yshift=-\margev] (B) at (current page.north east);%
    \coordinate[yshift=-\hauteurcards] (A1) at (A);%
    \coordinate[yshift=-\hauteurcards] (B1) at (B);%
    \coordinate[yshift=-\hauteurcards] (A2) at (A1);%
    \coordinate[yshift=-\hauteurcards] (B2) at (B1);%
    \coordinate[yshift=-\hauteurcards] (A3) at (A2);%
    \coordinate[yshift=-\hauteurcards] (B3) at (B2);%
    \coordinate[yshift=-\hauteurcards] (A4) at (A3);%
    \coordinate[yshift=-\hauteurcards] (B4) at (B3);%
    \coordinate[xshift=\margeh] (C) at (current page.north west);%
    \coordinate[xshift=\margeh] (D) at (current page.south west);%
    \coordinate[xshift=\largeurcards] (C1) at (C);%
    \coordinate[xshift=\largeurcards] (D1) at (D);%
    \coordinate[xshift=\largeurcards] (C2) at (C1);%
    \coordinate[xshift=\largeurcards] (D2) at (D1);%
    \coordinate[xshift=\largeurcards] (C3) at (C2);%
    \coordinate[xshift=\largeurcards] (D3) at (D2);%
    \draw (A) -- (B);%
    \draw (A1) -- (B1);%
    \draw (A2) -- (B2);%
    \draw (A3) -- (B3);%
    \draw (A4) -- (B4);%
    \draw (C)--(D);%
    \draw (C1)--(D1);%
    \draw (C2)--(D2);%
    \draw (C3)--(D3);%
    % point pour placer les cartes
    \coordinate[xshift=\margeh+0.5\largeurcards,yshift=-0.5\hauteurcards] (Carte1) at (A);%
    \coordinate[xshift=\largeurcards,yshift=0mm] (Carte2) at (Carte1);%
    \coordinate[xshift=2\largeurcards,yshift=0mm] (Carte3) at (Carte1);%
    \coordinate[xshift=0mm,yshift=-\hauteurcards] (Carte4) at (Carte1);%
    \coordinate[xshift=0mm,yshift=-\hauteurcards] (Carte5) at (Carte2);%
    \coordinate[xshift=0mm,yshift=-\hauteurcards] (Carte6) at (Carte3);%
    \coordinate[xshift=0mm,yshift=-\hauteurcards] (Carte7) at (Carte4);%
    \coordinate[xshift=0mm,yshift=-\hauteurcards] (Carte8) at (Carte5);%
    \coordinate[xshift=0mm,yshift=-\hauteurcards] (Carte9) at (Carte6);%
    \BODY%
  \end{tikzpicture}%
}%

\setKVdefault[Cards]{Largeur=59,Hauteur=89,HauteurTheme=15,Marge=4,Landscape=false,Couleur=Cornsilk,Theme=Th\'eor\`eme\\de
  Pythagore,ThemeSol=Solution,Trame=false,Titre=false,NomTitre=Jeu 1,Loop,JaiQuia=false,BackgroundAv=false,BackgroundAr=false,ImageAv=4813762.jpg,ImageAr=4813762.jpg,AffichageSolution=true,SolutionSeule=false,%
  % Pour le trivial
  Trivial=false,Symboles={\faInfinity,\faSignal,\faProjectDiagram,\faHiking,\faRuler,\faLockOpen}
}%

\newcommand\Cartes[2][]{%
  \useKVdefault[Cards]%
  \setKV[Cards]{#1}%
  \setsepchar[*]{§*/}%
  \readlist*\ListeCards{#2}%
  \ifboolKV[Cards]{Landscape}{%
    \setlength{\hauteurcarte}{\fpeval{\useKV[Cards]{Largeur}-\useKV[Cards]{Marge}}mm}%
    \setlength{\largeurcarte}{\fpeval{\useKV[Cards]{Hauteur}-\useKV[Cards]{Marge}}mm}%
    \setlength{\largeurcards}{95mm}%
    \setlength{\hauteurcards}{65mm}%
    \setlength{\margeh}{(297mm-3\largeurcards)/2}%
    \setlength{\margev}{(210mm-3\hauteurcards)/2}%
  }{%
    \setlength{\hauteurcarte}{\fpeval{\useKV[Cards]{Hauteur}-\useKV[Cards]{Marge}}mm}%
    \setlength{\largeurcarte}{\fpeval{\useKV[Cards]{Largeur}-\useKV[Cards]{Marge}}mm}%
    \setlength{\largeurcards}{65mm}%
    \setlength{\hauteurcards}{95mm}%
    \setlength{\margeh}{(210mm-3\largeurcards)/2}%
    \setlength{\margev}{(297mm-3\hauteurcards)/2}%
  }%
  \setlength{\hauteurtitre}{\fpeval{\useKV[Cards]{HauteurTheme}}mm}%
  \setlength{\largeurtitre}{\fpeval{(\useKV[Cards]{Largeur}-\useKV[Cards]{Marge}-9)/2}mm}%
  \colorlet{TexteCouleur}{black}%
  \colorlet{TrameCouleur}{\useKV[Cards]{Couleur}}%
  \ifboolKV[Cards]{Trivial}{%
    \xdef\PfCListeSymbolTrivial{\useKV[Cards]{Symboles}}%
    \setsepchar{,}\readlist*\ListeSymbolesTrivial{\PfCListeSymbolTrivial}%
    \setlength{\tabcolsep}{0.25\tabcolsep}
    \ifboolKV[Cards]{Trame}{%
      \clearpage%
      \thispagestyle{empty}%
      \begin{Trame}
        \multido{\i=1+1}{9}{%
          \node[] at (Carte\i) {%
            \begin{MyboxTrivial}%
              \begin{center}
                \begin{NiceTabular}[width=0.9\largeurcarte]{X[1,m]X[9,m]}[hvlines]
                  \xintFor* ##1 in{\xintSeq{1}{6}}\do{%
                    \rule{0pt}{0.12\hauteurcards}\Block{1-1}{\ListeSymbolesTrivial[##1]}&\ListeCards[\i,\fpeval{1+2*(##1-1)}]\\
                  }%
                \end{NiceTabular}
              \end{center}
            \end{MyboxTrivial}%
          };%
        }%
      \end{Trame}%
      \ifboolKV[Cards]{AffichageSolution}{%
        \clearpage%
        \thispagestyle{empty}%
        \begin{Trame}
          \multido{\i=1+1}{3}{%
            \node at (Carte\i) {%
              \begin{MyboxTrivial}%
                \begin{center}
                  \begin{NiceTabular}[width=0.9\largeurcarte]{X[1,m]X[10,m]}[hvlines]
                    \xintFor* ##1 in{\xintSeq{1}{6}}\do{%
                      \rule{0pt}{0.12\hauteurcards}\Block{1-1}{\ListeSymbolesTrivial[##1]}&\ListeCards[\fpeval{4-\i},\fpeval{2*##1}]\\
                    }%
                  \end{NiceTabular}
                \end{center}
              \end{MyboxTrivial}%
            };%
          }%
          \multido{\i=4+1}{3}{%
            \node at (Carte\i) {%
              \begin{MyboxTrivial}%
                \begin{center}
                  \begin{NiceTabular}[width=0.9\largeurcarte]{X[1,m]X[10,m]}[hvlines]
                    \xintFor* ##1 in{\xintSeq{1}{6}}\do{%
                      \rule{0pt}{0.12\hauteurcards}\Block{1-1}{\ListeSymbolesTrivial[##1]}&\ListeCards[\fpeval{10-\i},\fpeval{2*##1}]\\
                    }%
                  \end{NiceTabular}
                \end{center}
              \end{MyboxTrivial}%
            };%
          }%
          \multido{\i=7+1}{3}{%
            \node at (Carte\i) {%
              \begin{MyboxTrivial}
                \begin{center}
                  \begin{NiceTabular}[width=0.9\largeurcarte]{X[1,m]X[10,m]}[hvlines]
                    \xintFor* ##1 in{\xintSeq{1}{6}}\do{%
                      \rule{0pt}{0.12\hauteurcards}\Block{1-1}{\ListeSymbolesTrivial[##1]}&\ListeCards[\fpeval{16-\i},\fpeval{2*##1}]\\
                    }%
                  \end{NiceTabular}
                \end{center}
              \end{MyboxTrivial}%
            };%
          }%
        \end{Trame}%
        \clearpage%
      }{}%
    }{%
      \begin{MyboxTrivial}%
        \begin{center}
          \begin{NiceTabular}[width=0.9\largeurcarte]{X[1,m]X[10,m]}[hvlines]
            \xintFor* ##1 in{\xintSeq{1}{6}}\do{%
              \rule{0pt}{0.12\hauteurcards}\Block{1-1}{\ListeSymbolesTrivial[##1]}&\ListeCards[1,\fpeval{1+2*(##1-1)}]\\
            }%
          \end{NiceTabular}
        \end{center}
      \end{MyboxTrivial}%
      \ifboolKV[Cards]{AffichageSolution}{%
        \begin{MyboxTrivial}%
          \begin{center}
            \begin{NiceTabular}[width=0.9\largeurcarte]{X[1,m]X[10,m]}[hvlines]
              \xintFor* ##1 in{\xintSeq{1}{6}}\do{%
                \rule{0pt}{0.12\hauteurcards}\Block{1-1}{\ListeSymbolesTrivial[##1]}&\ListeCards[1,\fpeval{2*##1}]\\
              }%
            \end{NiceTabular}
          \end{center}
        \end{MyboxTrivial}%
      }{}%
    }%
    \setlength{\tabcolsep}{4\tabcolsep}%
  }{%
    \ifboolKV[Cards]{JaiQuia}{%
      \ifboolKV[Cards]{Trame}{%
        \clearpage%
        \thispagestyle{empty}%
        \begin{Trame}
          \multido{\i=1+1}{9}{%
            \node at (Carte\i) {%
              \begin{MyboxJQ}{\ListeCards[\i,1]}{\ListeCards[\i,2]}%
                %% 
              \end{MyboxJQ}%
            };%
          }%
        \end{Trame}%
        \clearpage%
      }{%
        \begin{MyboxJQ}{\ListeCards[1,1]}{\ListeCards[1,2]}%
          %% 
        \end{MyboxJQ}%
      }%
    }{%
      \ifboolKV[Cards]{Loop}{%
        \ifboolKV[Cards]{Trame}{%
          \clearpage%
          \thispagestyle{empty}%
          \begin{Trame}
            \multido{\i=1+1}{9}{%
              \node at (Carte\i) {%
                \begin{Mybox}{\ListeCards[\i,1]}{\useKV[Cards]{Theme}}{\ListeCards[\i,2]}%
                  \ListeCards[\i,3]%
                \end{Mybox}%
              };%
            }%
          \end{Trame}%
          \clearpage%
        }{%
          \begin{Mybox}{\ListeCards[1,1]}{\useKV[Cards]{Theme}}{\ListeCards[1,2]}%
            \ListeCards[1,3]%
          \end{Mybox}%
        }%
      }{%
        \ifboolKV[Cards]{Trame}{%
          \clearpage%
          \thispagestyle{empty}%
          \begin{Trame}
            \multido{\i=1+1}{9}{%
              \node[] at (Carte\i) {%
                \begin{MyboxSimpleAv}{\useKV[Cards]{Theme}}%
                  \ListeCards[\i,1]%
                \end{MyboxSimpleAv}%
              };%
            }%
          \end{Trame}%
          \ifboolKV[Cards]{AffichageSolution}{%
            \clearpage%
            \thispagestyle{empty}%
            \begin{Trame}
              \multido{\i=1+1}{3}{%
                \node at (Carte\i) {%
                  \begin{MyboxSimpleAr}{\useKV[Cards]{ThemeSol}}%
                    \ListeCards[\fpeval{4-\i},2]%
                  \end{MyboxSimpleAr}%
                };%
              }%
              \multido{\i=4+1}{3}{%
                \node at (Carte\i) {%
                  \begin{MyboxSimpleAr}{\useKV[Cards]{ThemeSol}}%
                    \ListeCards[\fpeval{10-\i},2]%
                  \end{MyboxSimpleAr}%
                };%
              }%
              \multido{\i=7+1}{3}{%
                \node at (Carte\i) {%
                  \begin{MyboxSimpleAr}{\useKV[Cards]{ThemeSol}}%
                    \ListeCards[\fpeval{16-\i},2]%
                  \end{MyboxSimpleAr}%
                };%
              }%
            \end{Trame}%
            \clearpage%
          }{}%
        }{%
          \ifboolKV[Cards]{SolutionSeule}{}{%
            \begin{MyboxSimpleAv}{\useKV[Cards]{Theme}}%
              \ListeCards[1,1]%
            \end{MyboxSimpleAv}%
          }%
          \ifboolKV[Cards]{AffichageSolution}{%
            \begin{MyboxSimpleAr}{\useKV[Cards]{ThemeSol}}%
              \ListeCards[1,2]%
            \end{MyboxSimpleAr}%
          }{}%
        }%
      }%
    }%
  }%
}%

\newcommand\SolutionCarte[2]{%
  \begin{center}
    \bfseries#1
  \end{center}
  
  #2
}%

%%%
% Tableur
%%%
\setKVdefault[Tableur]{Colonnes=4,Largeur=30pt,LargeurUn=30pt,Bandeau=true,Formule={},Cellule=A1,Ligne=0,Colonne=0,PasL=1,PasC=1,Selection=false}%
%Idee de P. Nuns
\defKV[Tableur]{Couleur=\setKV[Tableur]{Selection}}%
%

%Bas\'e sur un code de Christian T\'ell\'ech\'ea.
\newcount\cntlin%
\newcount\cntcol%

\makeatletter%
\newtoks\t@b%
\long\def\ifremain@lines#1\\#2\@nil{%
  \csname @\ifx\@empty#2\@empty second\else first\fi oftwo\endcsname}%
\long\def\subst@eol#1\\#2\@nil{\addtot@b{#1\\}%
  \ifremain@lines#2\\\@nil{\addtot@b&\subst@eol#2\@nil}{\addtot@b{#2\CodeAfter\xintifboolexpr{\useKV[Tableur]{Ligne}==0 || \useKV[Tableur]{Colonne}==0}{}{%
        \tikz\node at (row-\fpeval{\useKV[Tableur]{Ligne}+1+\useKV[Tableur]{PasL}}-|col-\fpeval{\useKV[Tableur]{Colonne}+1+\useKV[Tableur]{PasC}}) {\tiny$\blacksquare$};%
      }%
    \end{NiceTabular}}}}%
\long\def\collectcp@body#1\end{\subst@eol#1\@nil\end}%

\newcommand\addtot@b[1]{\t@b\expandafter{\the\t@b#1}}%
\newcommand\edftot@b[1]{\edef\temp@{#1}\expandafter\addtot@b\expandafter{\temp@}}%

\newlength\PfCLongInter%
\newlength\PfCTableurLargeurUn%
\newlength\PfCTableurLargeur%

\RequirePackage{printlen}

\newenvironment{Tableur}[1][]{%
  \useKVdefault[Tableur]%
  \setKV[Tableur]{#1}%
  \setlength{\PfCTableurLargeurUn}{\fpeval{\useKV[Tableur]{LargeurUn}}pt}%
  \setlength{\PfCTableurLargeur}{\fpeval{\useKV[Tableur]{Largeur}}pt}%
  \ttfamily%
  \newcolumntype{Y}{>{\centering\arraybackslash}m{\PfCTableurLargeurUn}}%
  \newcolumntype{X}{>{\centering\arraybackslash}m{\PfCTableurLargeur}}%
  \setlength{\PfCLongInter}{-40pt+\fpeval{\useKV[Tableur]{LargeurUn}}pt+\fpeval{(\useKV[Tableur]{Colonnes}-2)*\useKV[Tableur]{Largeur}}pt+\fpeval{2*\useKV[Tableur]{Colonnes}-6}\tabcolsep+\fpeval{\useKV[Tableur]{Colonnes}+2}\arrayrulewidth}%  
  \ifboolKV[Tableur]{Bandeau}{%
    \begin{NiceTabular}{p{\PfCTableurLargeur}p{10pt}p{50pt}p{\PfCLongInter}}
      \Block[draw,l]{}{\useKV[Tableur]{Cellule}}&\Block[draw]{}{\scriptsize$\blacktriangledown$}&\Block{}{$f_x$\hfill$\sum$~\scriptsize$\blacktriangledown$\hfill$=$}&\Block[draw]{}{\useKV[Tableur]{Formule}\hfill\scriptsize$\blacktriangledown$}\\
    \end{NiceTabular}%
    \nopagebreak%
    \\%
  }{}%
  \cntlin\z@%
  \t@b{%
    \begin{NiceTabular}{%
        >{%
          \global\cntcol\z@\global\advance\cntlin\@ne%
          \centering\arraybackslash%
          \ifnum\cntlin>\@ne%
          \ifboolKV[Tableur]{Selection}{%
            \xintifboolexpr{\cntlin>\useKV[Tableur]{Ligne} && \cntlin<\fpeval{\useKV[Tableur]{Ligne}+\useKV[Tableur]{PasL}+1}}{\textcolor{white}{\number\numexpr\cntlin-1\relax}}{\number\numexpr\cntlin-1\relax}%
          }{\number\numexpr\cntlin-1\relax}\fi}%
        wc{20pt}Y*{\fpeval{\useKV[Tableur]{Colonnes}-1}}{X}}[hvlines]%
      \CodeBefore
      % on colorie en gris toute la première ligne
      \tikz\draw[fill=gray!15](row-1-|col-1) rectangle (row-2-|last);%
      % on colorie en gris toute la première colonne
      \tikz\draw[fill=gray!15](row-1-|col-1) rectangle (last-|col-2);%
      %
      \xintifboolexpr{\useKV[Tableur]{Ligne}==0 || \useKV[Tableur]{Colonne}==0}{}{%
        \ifboolKV[Tableur]{Selection}{%
          \xdef\PfCTabCouleur{\useKV[Tableur]{Couleur}}%
          % on colorie les cellules sans les tracer
          \tikz\draw[fill=\PfCTabCouleur!50](row-\fpeval{\useKV[Tableur]{Ligne}+1}-|col-\fpeval{\useKV[Tableur]{Colonne}+1}) rectangle (row-\fpeval{\useKV[Tableur]{Ligne}+1+\useKV[Tableur]{PasL}}-|col-\fpeval{\useKV[Tableur]{Colonne}+1+\useKV[Tableur]{PasC}});%
          % on trace la première cellule qui a servi à sélectionner
          \tikz\draw[line width=1.25pt,fill=\PfCTabCouleur!50](row-\fpeval{\useKV[Tableur]{Ligne}+1}-|col-\fpeval{\useKV[Tableur]{Colonne}+1}) rectangle (row-\fpeval{\useKV[Tableur]{Ligne}+1+1}-|col-\fpeval{\useKV[Tableur]{Colonne}+1+1});%
          % on colorie la zone nécessaire sur la première ligne
          \tikz\draw[fill=\PfCTabCouleur](row-1-|col-\fpeval{\useKV[Tableur]{Colonne}+1}) rectangle (row-2-|col-\fpeval{\useKV[Tableur]{Colonne}+1+\useKV[Tableur]{PasC}});%
          % on colorie la zone nécessaire sur la première colonne
          \tikz\draw[fill=\PfCTabCouleur](row-\fpeval{\useKV[Tableur]{Ligne}+1}-|col-1) rectangle (row-\fpeval{\useKV[Tableur]{Ligne}+1+\useKV[Tableur]{PasL}}-|col-2);%
        }{%
          \tikz\draw[line width=1.25pt](row-\fpeval{\useKV[Tableur]{Ligne}+1}-|col-\fpeval{\useKV[Tableur]{Colonne}+1}) rectangle (row-\fpeval{\useKV[Tableur]{Ligne}+1+\useKV[Tableur]{PasL}}-|col-\fpeval{\useKV[Tableur]{Colonne}+1+\useKV[Tableur]{PasC}});%
        }%
      }%
      \Body
    %
  }%
  \loop%
  \ifnum\cntcol<\useKV[Tableur]{Colonnes}%
  \advance\cntcol\@ne%
  \addtot@b{&}%
  % modif by Pascal Nuns
  \ifboolKV[Tableur]{Selection}{%
    \ifnum\cntcol>\fpeval{\useKV[Tableur]{Colonne}-1}%
    \ifnum\cntcol<\fpeval{\useKV[Tableur]{Colonne}+\useKV[Tableur]{PasC}}%
    \edftot@b{{\noexpand\textcolor{white}{\noexpand\bfseries\@Alph{\the\cntcol}}}}%
    \else%
    \edftot@b{\@Alph{\the\cntcol}}%
    \fi%
    \else%
    \edftot@b{\@Alph{\the\cntcol}}%
    \fi%
  }{\edftot@b{\@Alph{\the\cntcol}}}%
  % fin de modif
  \repeat%
  \addtot@b{\\&}%
  \collectcp@body}{\the\t@b}%
\makeatother

%%%
% Domino
%%%
\newtcolorbox{MyDominoMini}[1][]{%
  enhanced,
  nobeforeafter,
  left skip=0pt,
  right skip=0pt,
  left=0pt,right=0pt,top=0pt,bottom=0pt,
  width=\textwidth/\ColonneDomino,
  height=\textheight/\LigneDomino,
  segmentation style={solid, line width=1.5pt},
  colback=\CouleurDomino,
  center upper,
  valign upper=center,
  center lower,
  valign lower=center,
  arc=2pt,
  #1
}

\newtcolorbox{MyDominoLogo}[1][]{%
  enhanced,
  nobeforeafter,
  left skip=0pt,
  right skip=0pt,
  left=0pt,right=0pt,top=0pt,bottom=0pt,
  width=\textwidth/\ColonneDomino,
  height=\textheight/\LigneDomino,
  valign=center,
  halign=center,
  arc=2pt,
  colback=white,
  #1
}

\NewEnviron{TrameDomino}{%
  \setlength{\margev}{1cm}
  \setlength{\margeh}{1cm}
  \begin{tikzpicture}[remember picture,overlay]
    % quadrillages horizontal et vertical
    \coordinate[yshift=-\margev] (A0) at (current page.north west);
    \coordinate[yshift=-\margev] (B0) at (current page.north east);
    \foreach \i in {1,...,\useKV[Domino]{Lignes}}{%
      \coordinate[yshift=-\i*\textheight/\LigneDomino] (A\i) at (A0);
      \coordinate[yshift=-\i*\textheight/\LigneDomino] (B\i) at (B0);
    }
    \coordinate[xshift=\margeh] (C0) at (current page.north west);
    \coordinate[xshift=\margeh] (D0) at (current page.south west);
    \foreach \i in {1,...,\useKV[Domino]{Colonnes}}{
      \coordinate[xshift=\i*\textwidth/\ColonneDomino] (C\i) at (C0);
      \coordinate[xshift=\i*\textwidth/\ColonneDomino] (D\i) at (D0);
    }
    \foreach \i in {0,...,\LigneDomino}{%
      \draw (A\i) -- (B\i);
    }
    \foreach \i in {0,...,\ColonneDomino}{%
      \draw (C\i) -- (D\i);
    }
    \draw[blue, line width=3pt] (A0)--(B0);
    \draw[blue, line width=3pt] (A\LigneDomino)--(B\LigneDomino);
    \draw[blue, line width=3pt] (C0)--(D0);
    \draw[blue, line width=3pt] (C\ColonneDomino)--(D\ColonneDomino);
    % point pour placer les cartes
    \foreach \i in {0,...,\fpeval{\ColonneDomino-1}}{%
      \foreach \j in {0,...,\fpeval{\LigneDomino-1}}{%
        \coordinate[xshift=\margeh+(0.5\textwidth/\ColonneDomino)+\i*\textwidth/\ColonneDomino,yshift=-0.5\textheight/\LigneDomino-\j*\textheight/\LigneDomino]
        (Domino\fpeval{\i+\ColonneDomino*\j+1}) at (A0);
      }
    }
    \BODY
  \end{tikzpicture}
}

\setKVdefault[Domino]{Couleur=white,Trame,Ratio=0.5,Lignes=7,Colonnes=5,Superieur=false,Logo=false,Image=tiger.pdf}

\newcommand\Dominos[2][]{%
  \useKVdefault[Domino]%
  \setKV[Domino]{#1}%
  \setsepchar[*]{§*/}%
  \readlist*\ListeDominos{#2}%
  \xdef\CouleurDomino{\useKV[Domino]{Couleur}}%
  \xdef\ratiodomino{\useKV[Domino]{Ratio}}%
  \xdef\LigneDomino{\useKV[Domino]{Lignes}}%
  \xdef\ColonneDomino{\useKV[Domino]{Colonnes}}%
  \ifboolKV[Domino]{Trame}{%
    \clearpage
    \begin{TrameDomino}
      \foreach\i in {1,...,\fpeval{\LigneDomino*\ColonneDomino}}{%
        \node[] at (Domino\i){%
          \ifboolKV[Domino]{Superieur}{%
            \begin{MyDominoMini}[space=\ratiodomino]%
              \ListeDominos[\i,1]\tcblower\ListeDominos[\i,2]%
            \end{MyDominoMini}%
          }{%
            \begin{MyDominoMini}[sidebyside,sidebyside gap=4mm,righthand ratio=\ratiodomino]%
              \ListeDominos[\i,1]\tcblower\ListeDominos[\i,2]%          
            \end{MyDominoMini}%
          }%
        };
      }%
    \end{TrameDomino}%
    \ifboolKV[Domino]{Logo}{%
      \clearpage
      \begin{TrameDomino}
        \foreach\i in {1,...,\fpeval{\LigneDomino*\ColonneDomino}}{%
          \node at (Domino\i){%
            \begin{MyDominoLogo}%
              \includegraphics[height=\tcbtextheight]{\useKV[Domino]{Image}}
            \end{MyDominoLogo}%
          };
        }%
      \end{TrameDomino}%
    }{}%
  }{%
    \ifboolKV[Domino]{Superieur}{%
      \begin{MyDominoMini}[space=\ratiodomino]%
        \ListeDominos[1,1]\tcblower\ListeDominos[1,2]%
      \end{MyDominoMini}%
    }{%
      \begin{MyDominoMini}[sidebyside,sidebyside gap=4mm,righthand ratio=\ratiodomino]%
        \ListeDominos[1,1]\tcblower%
        \ListeDominos[1,2]%          
      \end{MyDominoMini}%
    }%
  }%
}%

%%%%
% Prog de calculs "simples"
%%%%
\setKVdefault[ClesProg]{%
  Ecart=2em,%
  Direct,%
  SansCalcul=false,%
  Application=false,
  Details=false,
  Enonce=false,
  Nom={},
  CouleurCadre=black,%
  CouleurFond=gray!10,%
  Largeur={.95\linewidth},%
  Epaisseur=.75pt,%
  Pointilles=0,
  ThemePerso=false,
}

\newcounter{NBprog}%
\setcounter{NBprog}{0}%

\newlength{\PointillesClesProg}%

\newcommand\ProgCalcul[2][]{%
  % #1 : cl\'es
  % #2 : \'etapes
  \useKVdefault[ClesProg]%
  \setKV[ClesProg]{#1}%
  \ifboolKV[ClesProg]{ThemePerso}{}{%
    \tcbset{ProgCalcul/.style={%
        boxsep=1mm,
        bottom=.75mm,
        middle=2mm,
        boxrule={\useKV[ClesProg]{Epaisseur}},
        text width={\useKV[ClesProg]{Largeur}},
        colframe={\useKV[ClesProg]{CouleurCadre}},
        colback={\useKV[ClesProg]{CouleurFond}},
        halign upper=center
      }%
    }%
  }%
  \ifboolKV[ClesProg]{Application}{%
    %    % by Thomas Dehon and cp
    \setsepchar[*]{§*,}
    % \setsepchar[*]{,* }%
    \ignoreemptyitems%
    \readlist*\ListeTotale{#2}%
    \xdef\PfCPCfoo{\ListeTotale[1]}%
    \xdef\PfCPCfaa{\ListeTotale[2]}%
    %% 
    \setsepchar{,}%    \ignoreemptyitems%
    \readlist*\ListeEtapes{\PfCPCfoo}%
    \setsepchar[*]{,* }\ignoreemptyitems%
    \readlist*\ListeProg{\PfCPCfaa}%
      \begin{tcolorbox}[%
        ProgCalcul,%
        ]
        \ifthenelse{\equal{\useKV[ClesProg]{Nom}}{}}%
        {}%
        {%
          {\color{\useKV[ClesProg]{CouleurCadre}}{\bfseries\useKV[ClesProg]{Nom}}}%
          \tcblower
        }%
        \ifboolKV[ClesProg]{SansCalcul}{%
          \begin{enumerate}
          \item Choisir un nombre~\pointilles~$\ListeProg[1]$%
            \foreachitem\etape\in\ListeEtapes{%
            \item \etape~\pointilles~$\ListeProg[3,\etapecnt]$
            }%
          \end{enumerate}
        }{\begin{enumerate}
          \item Choisir un nombre~\pointilles~\xdef\NbDepart{\ListeProg[1]}\num{\NbDepart}
            \foreachitem\etape\in\ListeEtapes{%
            \item \etape~\pointilles~\edef\Test{\ListeProg[2,\etapecnt]}%
              \expandarg%
              \StrSubstitute{\Test}{^}{\empty\dots{}^}[\tempa]%
              \StrSubstitute{\tempa}{**}{^}[\tempab]%
              \StrSubstitute{\tempab}{*}{\times}[\tempac]%
              \StrSubstitute{\tempac}{/}{\div}[\tempad]%
              $\ifboolKV[ClesProg]{Details}{\xintifboolexpr{\NbDepart<0}{(\num{\NbDepart})}{\num{\NbDepart}}\tempad=}{}\xdef\NbDepart{\fpeval{(\NbDepart)\ListeProg[2,\etapecnt]}}\num{\NbDepart}$%
            }%
          \end{enumerate}
        }
      \end{tcolorbox}
  }{%
    \ifboolKV[ClesProg]{Enonce}{%
      % by Thomas Dehon
      \setsepchar[*]{,* }%
      \ignoreemptyitems%
      \readlist*\ListeEtapes{#2}% 
      \begin{tcolorbox}[%
        ProgCalcul,%
        ]
        \ifthenelse{\equal{\useKV[ClesProg]{Nom}}{}}%
        {}%
        {%
          {\color{\useKV[ClesProg]{CouleurCadre}}{\bfseries\useKV[ClesProg]{Nom}}}%
          \tcblower
        }%
        \begin{enumerate}
          \foreachitem\etape\in\ListeEtapes{%
          \item \etape 
            \ifthenelse{\equal{\useKV[ClesProg]{Pointilles}}{0}}%
            {}%
            {%
              \setlength{\PointillesClesProg}{\useKV[ClesProg]{Pointilles}}
              \hfill \pointilles[\PointillesClesProg]%
            }%
          }
        \end{enumerate}
      \end{tcolorbox}
    }{%
      \setsepchar[*]{,* }\ignoreemptyitems%
      \readlist*\ListeProg{#2}%
      \stepcounter{NBprog}%
      \xdef\NbDepart{\ListeProg[1]}%
      \ifboolKV[ClesProg]{SansCalcul}{%
        $\NbDepart$\foreachitem\compteur\in\ListeProg[2]{%
          \hspace{0.2em}\tikzmark{A-\theNBprog-\compteurcnt}\hspace{\useKV[ClesProg]{Ecart}}\tikzmark{B-\theNBprog-\compteurcnt}\hspace{0.2em}$\ListeProg[3,\compteurcnt]$%
        }%
        \begin{tikzpicture}[remember picture, overlay]
          \foreachitem\compteur\in\ListeProg[2]{%
            \edef\Test{\ListeProg[2,\compteurcnt]}
            \expandarg%
            \StrSubstitute{\Test}{^}{\empty\dots{}^}[\tempa]%
            \StrSubstitute{\tempa}{**}{^}[\tempab]%
            \StrSubstitute{\tempab}{*}{\times}[\tempac]%
            \StrSubstitute{\tempac}{/}{\div}[\tempad]%
            \draw[-stealth,transform canvas={yshift=0.25em}] (pic cs:A-\theNBprog-\compteurcnt) --
            node[above]{\scriptsize$\tempad$}(pic cs:B-\theNBprog-\compteurcnt);
          }
        \end{tikzpicture}  
      }{%
        \num{\NbDepart}\foreachitem\compteur\in\ListeProg[2]{%
          \hspace{0.2em}\tikzmark{A-\theNBprog-\compteurcnt}\hspace{\useKV[ClesProg]{Ecart}}\tikzmark{B-\theNBprog-\compteurcnt}\xdef\NbDepart{\fpeval{(\NbDepart)\ListeProg[2,\compteurcnt]}}\hspace{0.2em}\num{\NbDepart}%
        }%
        \ifboolKV[ClesProg]{Direct}{%
          \begin{tikzpicture}[remember picture, overlay]
            \foreachitem\compteur\in\ListeProg[2]{%
              \edef\Test{\ListeProg[2,\compteurcnt]}
              \expandarg%
              \StrSubstitute{\Test}{^}{\empty\dots{}^}[\tempa]%
              \StrSubstitute{\tempa}{**}{^}[\tempab]%
              \StrSubstitute{\tempab}{*}{\times}[\tempac]%
              \StrSubstitute{\tempac}{/}{\div}[\tempad]%
              \draw[-stealth,transform canvas={yshift=0.25em}] (pic cs:A-\theNBprog-\compteurcnt) --
              node[above]{\scriptsize$\tempad$}(pic
              cs:B-\theNBprog-\compteurcnt);
            }
          \end{tikzpicture}
        }{%
          \begin{tikzpicture}[remember picture, overlay]
            \foreachitem\compteur\in\ListeProg[2]{%
              \edef\Test{\ListeProg[2,\compteurcnt]}
              \expandarg%
              \StrSubstitute{\Test}{^2}{\empty\sqrt{\dots{}}}[\tempa]%
              \StrSubstitute{\tempa}{**}{^}[\tempab]%
              \StrSubstitute{\tempab}{*}{\div}[\tempac]%
              \StrSubstitute{\tempac}{/}{\times}[\tempad]%
              \StrSubstitute{\tempad}{-}{+}[\tempae]%
              \StrSubstitute{\tempae}{++}{-}[\tempaf]%
              \draw[-stealth,transform canvas={yshift=0.25em}] (pic cs:B-\theNBprog-\compteurcnt) --  node[above]{\scriptsize$\tempaf$}(pic cs:A-\theNBprog-\compteurcnt);
            }
          \end{tikzpicture}
        }%
      }%
    }%
  }%
}%

%%%
% Papiers
%%%
\setKVdefault[Papiers]{Cinq=true,Seyes=false,Isometrique=false,IsometriquePointe=false,Millimetre=false,Triangle=false,Largeur=5,Hauteur=4,Couleur=black,Grille=-1,GrillePointe=-1,PageEntiere=false,ZoneTexte=false,Baseline=false,CodeAfter=false}%
\defKV[Papiers]{Traces=\setKV[Papiers]{CodeAfter}}

%\def\MPBaseLineSkip#1#2#3{%à retravailler : ne fonctionne pas :(
%  %
%  \ifluatex
%  \mplibforcehmode
%  \begin{mplibcode}
%    path horizon,verticon;
%    horizon=(0,0)--(#1*cm,0);
%    %verticon=(0,0)--(0,#2*cm);
%    drawoptions(withcolor #3);
%    %for k=0 step 0.5 until #1:
%    %draw verticon shifted((k*cm,0));
%    %endfor;
%    for k=(#2-(\mpdim{1.6ex}/1cm)) step (-\mpdim{\baselineskip}/1cm) until 0:
%    draw horizon shifted((0,k*cm));
%    endfor;
%    drawoptions(withcolor blue);
%    for k=#2 step (-\mpdim{\baselineskip}/1cm) until 0:
%    draw horizon shifted((0,k*cm));
%    endfor;
%  \end{mplibcode}
%  \fi
%}

\def\MPGrille#1#2#3#4{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step (#4*100) until (#1*100):
    draw verticon shifted(((k/100)*cm,0));
    endfor;
    for k=0 step (#4*100) until (#2*100):
    draw horizon shifted((0,(k/100)*cm));
    endfor;
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 0.5 until #1:
    draw verticon shifted((k*cm,0));
    endfor;
    for k=0 step 0.5 until #2:
    draw horizon shifted((0,k*cm));
    endfor;
  \end{mpost}%
  \fi%
}%

\def\MPGrillePointe#1#2#3#4{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    drawoptions(withcolor #3);
    for k=0 step (#4*100) until (#1*100):
    for l=0 step (#4*100) until (#2*100):
    fill (cercles((0,0),1pt) shifted(((k/100)*cm,(l/100)*cm)));
    endfor;
    endfor;
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    drawoptions(withcolor #3);
    for k=0 step (#4*100) until (#1*100):
    for l=0 step (#4*100) until (#2*100):
    fill (cercles((0,0),0.5pt) shifted(((k/100)*cm,(l/100)*cm)));
    endfor;
    endfor;
  \end{mpost}%
  \fi%
}%

\def\MPCinq#1#2#3{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 0.5 until #1:
    draw verticon shifted((k*cm,0));
    endfor;
    for k=0 step 0.5 until #2:
    draw horizon shifted((0,k*cm));
    endfor;
    if \useKV[Papiers]{CodeAfter}:
    \useKV[Papiers]{Traces};
    fi;
  \end{mplibcode}%
  \else%
  \begin{mpost}
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 0.5 until #1:
    draw verticon shifted((k*cm,0));
    endfor;
    for k=0 step 0.5 until #2:
    draw horizon shifted((0,k*cm));
    endfor;
  \end{mpost}%
  \fi%
}%

\def\MPSeyes#1#2#3{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 8 until (#1*10):
    draw verticon shifted(((k/10)*cm,0));
    endfor;
    for k=0 step 2 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 0.5;
    endfor;
    for k=0 step 8 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 1.25;
    endfor;
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 8 until (#1*10):
    draw verticon shifted(((k/10)*cm,0));
    endfor;
    for k=0 step 2 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 0.5;
    endfor;
    for k=0 step 8 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 1.25;
    endfor;
  \end{mpost}
  \fi%
}%

\def\MPMillimetre#1#2#3{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 1 until (#1*10):
    draw verticon shifted(((k/10)*cm,0)) withpen pencircle scaled 0.2;
    endfor;
    for k=0 step 5 until (#1*10):
    draw verticon shifted(((k/10)*cm,0)) withpen pencircle scaled 0.5;
    endfor;
    for k=0 step 1 until (#1):
    draw verticon shifted((k*cm,0)) withpen pencircle scaled 1.25;
    endfor;
    for k=0 step 1 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 0.2;
    endfor;
    for k=0 step 5 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 0.5;
    endfor;
    for k=0 step 1 until (#2):
    draw horizon shifted((0,k*cm)) withpen pencircle scaled 1.25;
    endfor;
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    path horizon,verticon;
    horizon=(0,0)--(#1*cm,0);
    verticon=(0,0)--(0,#2*cm);
    drawoptions(withcolor #3);
    for k=0 step 1 until (#1*10):
    draw verticon shifted(((k/10)*cm,0)) withpen pencircle scaled 0.2;
    endfor;
    for k=0 step 5 until (#1*10):
    draw verticon shifted(((k/10)*cm,0)) withpen pencircle scaled 0.5;
    endfor;
    for k=0 step 1 until (#1):
    draw verticon shifted((k*cm,0)) withpen pencircle scaled 1.25;
    endfor;
    for k=0 step 1 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 0.2;
    endfor;
    for k=0 step 5 until (#2*10):
    draw horizon shifted((0,(k/10)*cm)) withpen pencircle scaled 0.5;
    endfor;
    for k=0 step 1 until (#2):
    draw horizon shifted((0,k*cm)) withpen pencircle scaled 1.25;
    endfor;
  \end{mpost}%
  \fi%
}%

\def\MPIsometrique#1#2#3{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    path diagon,antidiagon;
    diagon=(0,0)--#2*(sqrt(3)*cm,1*cm);
    antidiagon=(0,0)--#2*(-sqrt(3)*cm,1*cm);
    drawoptions(withcolor #3);
    for k=0 step 1 until (#1):
    draw diagon shifted((k*cm,0));
    draw antidiagon shifted((k*cm,0));
    endfor;
    for k=0 step (sqrt(3)/3) until (#2):
    draw diagon shifted((0,k*cm));
    draw antidiagon shifted((#1*cm,k*cm));
    endfor;
    clip currentpicture to polygone((0,0),(#1*cm,0),(#1*cm,#2*cm),(0,#2*cm));
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    path diagon,antidiagon;
    diagon=(0,0)--#2*(sqrt(3)*cm,1*cm);
    antidiagon=(0,0)--#2*(-sqrt(3)*cm,1*cm);
    drawoptions(withcolor #3);
    for k=0 step 1 until (#1):
    draw diagon shifted((k*cm,0));
    draw antidiagon shifted((k*cm,0));
    endfor;
    for k=0 step (sqrt(3)/3) until (#2):
    draw diagon shifted((0,k*cm));
    draw antidiagon shifted((#1*cm,k*cm));
    endfor;
    clip currentpicture to polygone((0,0),(#1*cm,0),(#1*cm,#2*cm),(0,#2*cm));
  \end{mpost}%
  \fi%
}%

\def\MPIsometriquePointe#1#2#3{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    pair diagon,antidiagon;
    diagon=(1pt,1pt);
    antidiagon=(1pt+0.5cm,1pt+0.5*(sqrt(3)*1cm/3));
    drawoptions(withcolor #3);
    for k=0 step (sqrt(3)/3) until (#2):
    for l=0 step 1 until (#1):
    fill (cercles(diagon,1pt) shifted((l*cm,k*cm)));
    fill (cercles(antidiagon,1pt) shifted((l*cm,k*cm)));
    endfor;
    endfor;
    clip currentpicture to polygone((0,0),(#1*cm+2pt,0),(#1*cm+2pt,#2*cm+1pt),(0,#2*cm+1pt));
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    pair diagon,antidiagon;
    diagon=(1pt,1pt);
    antidiagon=(1pt+0.5cm,1pt+0.5*(sqrt(3)*1cm/3));
    drawoptions(withcolor #3);
    for k=0 step (sqrt(3)/3) until (#2):
    for l=0 step 1 until (#1):
    fill (cercles(diagon,1pt) shifted((l*cm,k*cm)));
    fill (cercles(antidiagon,1pt) shifted((l*cm,k*cm)));
    endfor;
    endfor;
    clip currentpicture to polygone((0,0),(#1*cm+2pt,0),(#1*cm+2pt,#2*cm+1pt),(0,#2*cm+1pt));
  \end{mpost}%
  \fi%
}%

\def\MPTriangulaire#1#2#3{%
  \ifluatex%
  \mplibforcehmode%
  \begin{mplibcode}%
    path horizon,diagon,antidiagon;
    horizon=(0,0)--(#1*cm,0);
    diagon=(0,0)--#2*(sqrt(3)*cm/3,1*cm);
    antidiagon=(0,0)--#2*(-sqrt(3)*cm/3,1*cm);
    drawoptions(withcolor #3);
    for k=0 step 1 until #1:
    draw diagon shifted((k*cm,0));
    endfor;
    for k=0 step (sqrt(3)) until (#2):
    draw diagon shifted((0,k*cm));
    endfor;
    for k=0 step 1 until (#1):
    draw antidiagon shifted((k*cm,0));
    endfor;
    for k=0 step (sqrt(3)) until (#2):
    draw antidiagon shifted((#1*cm,k*cm));
    endfor;
    for k=0 step (sqrt(3)/2) until (#2):
    draw horizon shifted((0,k*cm));
    endfor;
    clip currentpicture to polygone((0,0),(#1*cm,0),(#1*cm,#2*cm),(0,#2*cm));
  \end{mplibcode}%
  \else%
  \begin{mpost}%
    path horizon,diagon,antidiagon;
    horizon=(0,0)--(#1*cm,0);
    diagon=(0,0)--#2*(sqrt(3)*cm/3,1*cm);
    antidiagon=(0,0)--#2*(-sqrt(3)*cm/3,1*cm);
    drawoptions(withcolor #3);
    for k=0 step 1 until #1:
    draw diagon shifted((k*cm,0));
    endfor;
    for k=0 step (sqrt(3)) until (#2):
    draw diagon shifted((0,k*cm));
    endfor;
    for k=0 step 1 until (#1):
    draw antidiagon shifted((k*cm,0));
    endfor;
    for k=0 step (sqrt(3)) until (#2):
    draw antidiagon shifted((#1*cm,k*cm));
    endfor;
    for k=0 step (sqrt(3)/2) until (#2):
    draw horizon shifted((0,k*cm));
    endfor;
    clip currentpicture to polygone((0,0),(#1*cm,0),(#1*cm,#2*cm),(0,#2*cm));
  \end{mpost}%
  \fi%
}%

\RequirePackage{ifoddpage}

\newlength{\PapierLeftCurrent}

\newcommand\Papiers[1][]{%
  \useKVdefault[Papiers]%
  \setKV[Papiers]{#1}%
  \xdef\PapierLargeur{\useKV[Papiers]{Largeur}}%
  \xdef\PapierHauteur{\useKV[Papiers]{Hauteur}}%
  \xdef\PapierCouleur{\useKV[Papiers]{Couleur}}%
  \xdef\PapierGrille{\useKV[Papiers]{Grille}}%
  \xdef\PapierGrillePointe{\useKV[Papiers]{GrillePointe}}%
  \ifboolKV[Papiers]{ZoneTexte}{%
    \checkoddpage\ifoddpage%
    \setlength{\PapierLeftCurrent}{\oddsidemargin}%
    \else%
    \setlength{\PapierLeftCurrent}{\evensidemargin}%
    \fi%
    \xdef\PapierLeft{\the\dimexpr1in+\PapierLeftCurrent}%
    \xdef\PapierBottom{\fpeval{\paperheight-\textheight-\voffset-\headheight-\topmargin-\headsep-1in}}%
    \xdef\PapierHauteur{\fpeval{\textheight/1cm}}%
    \xdef\PapierLargeur{\fpeval{\textwidth/1cm}}%
    \begin{tikzpicture}[remember picture,overlay]%
      \node[anchor=south west,inner sep=0pt,transform canvas={xshift=\PapierLeft,yshift=\PapierBottom}] at (current page.south west) {%
        \xintifboolexpr{\useKV[Papiers]{GrillePointe}>0}{%
          \MPGrillePointe{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}{\PapierGrillePointe}%
        }{%
          \xintifboolexpr{\useKV[Papiers]{Grille}>0}{%
            \MPGrille{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}{\PapierGrille}%
          }{\ifboolKV[Papiers]{Baseline}{%
              \MPBaseLineSkip{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
            }{%
              \ifboolKV[Papiers]{IsometriquePointe}{%
                \MPIsometriquePointe{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
              }{%
                \ifboolKV[Papiers]{Triangle}{%
                  \MPTriangulaire{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                }{\ifboolKV[Papiers]{Millimetre}{%
                    \MPMillimetre{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                  }{\ifboolKV[Papiers]{Isometrique}{%
                      \MPIsometrique{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                    }{\ifboolKV[Papiers]{Seyes}{%
                        \MPSeyes{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                      }{\MPCinq{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                      }%
                    }%
                  }%
                }%
              }%
            }%
          }%
        }%
      };%
    \end{tikzpicture}%
  }{%
    \ifboolKV[Papiers]{PageEntiere}{%
      \checkoddpage\ifoddpage%
      \setlength{\PapierLeftCurrent}{\oddsidemargin}%
      \else%
      \setlength{\PapierLeftCurrent}{\evensidemargin}%
      \fi%
      \xdef\PapierLeft{\the\dimexpr1in+\PapierLeftCurrent}%
      \xdef\PapierBottom{\fpeval{\paperheight-\textheight-\voffset-\headheight-\topmargin-\headsep-1in}}%
      \xdef\PapierHauteur{\fpeval{\paperheight/1cm}}%
      \xdef\PapierLargeur{\fpeval{\paperwidth/1cm}}%
      \begin{tikzpicture}[remember picture,overlay]%
        \node[anchor=south west,inner sep=0pt] at (current page.south west) {%
          \xintifboolexpr{\useKV[Papiers]{GrillePointe}>0}{%
            \MPGrillePointe{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}{\PapierGrillePointe}%
          }{%
            \xintifboolexpr{\useKV[Papiers]{Grille}>0}{%
              \MPGrille{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}{\PapierGrille}%
            }{\ifboolKV[Papiers]{IsometriquePointe}{%
                \MPIsometriquePointe{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
              }{\ifboolKV[Papiers]{Triangle}{%
                  \MPTriangulaire{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                }{\ifboolKV[Papiers]{Millimetre}{%
                    \MPMillimetre{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                  }{\ifboolKV[Papiers]{Isometrique}{%
                      \MPIsometrique{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                    }{\ifboolKV[Papiers]{Seyes}{%
                        \MPSeyes{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                      }{\MPCinq{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                      }%
                    }%
                  }%
                }%
              }%
            }%
          }%
        };%
      \end{tikzpicture}%
    }{%
      \xintifboolexpr{\useKV[Papiers]{GrillePointe}>0}{%
        \MPGrillePointe{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}{\PapierGrillePointe}%
      }{%
        \xintifboolexpr{\useKV[Papiers]{Grille}>0}{%
          \MPGrille{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}{\PapierGrille}%
        }{\ifboolKV[Papiers]{Baseline}{%
            \MPBaseLineSkip{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
          }{%
            \ifboolKV[Papiers]{IsometriquePointe}{%
              \MPIsometriquePointe{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
            }{%
              \ifboolKV[Papiers]{Triangle}{%
                \MPTriangulaire{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
              }{\ifboolKV[Papiers]{Millimetre}{%
                  \MPMillimetre{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                }{\ifboolKV[Papiers]{Isometrique}{%
                    \MPIsometrique{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                  }{\ifboolKV[Papiers]{Seyes}{%
                      \MPSeyes{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                    }{\MPCinq{\PapierLargeur}{\PapierHauteur}{\PapierCouleur}%
                    }%
                  }%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%

%%%%
% Scratch
%%%%
\newlength{\longbarreheight}
\setlength{\longbarreheight}{2.1ex+3pt}

\newlength{\longbarredepth}
\setlength{\longbarredepth}{0.9ex+3pt}
\def\longbarre{\vrule height\longbarreheight depth\longbarredepth width0pt}%

\def\barre{\vrule height2.1ex depth.9ex width0pt}%
\def\demibarre{\vrule height1.4ex depth.6ex width0pt}%

\setKVdefault[Scratch]{Impression=false,Numerotation=false,Echelle=1,Naturel=false}%

\ifluatex
\NewDocumentEnvironment{Scratch}{o +b}{%
  \useKVdefault[Scratch]%
  \setKV[Scratch]{#1}%
  \mplibforcehmode%
  \ifboolKV[Scratch]{Naturel}{}{\myfontScratch}%
  \begin{mplibcode}%
    boolean Naturel;
    Naturel=\useKV[Scratch]{Naturel};
    if Naturel: input PfCPseudo; print:=true; else: input PfCScratch; print:=\useKV[Scratch]{Impression}; fi;
    NumeroteLignes:=\useKV[Scratch]{Numerotation};%
    #2%
    picture recap;%
    recap:=currentpicture scaled \useKV[Scratch]{Echelle};%
    currentpicture:=nullpicture;%
    draw recap;%
  \end{mplibcode}%
  }{}
\else%
\NewDocumentEnvironment{Scratch}{o +b}{%
  \setKV[Scratch]{#1}%
  \begin{mpost}[mpsettings={boolean Naturel;Naturel=\useKV[Scratch]{Naturel};if Naturel: input PfCPseudo; print:=true; else: input PfCScratchpdf; print:=\useKV[Scratch]{Impression}; fi;NumeroteLignes:=\useKV[Scratch]{Numerotation};Echelle:=\useKV[Scratch]{Echelle};}]%
    #2%
    picture recap;%
    recap:=currentpicture scaled Echelle;%
    currentpicture:=nullpicture;%
    draw recap;%
  \end{mpost}
}{}%
\fi%