unit regmain;

{$IFDEF FPC}
  {$MODE Delphi}
{$ENDIF}

// options compilateur
// -dBorland -dVer150 -dDelphi7 -dCompiler6_Up -dPUREPASCAL

interface

uses
{$IFnDEF FPC}
  shellApi, Windows,
{$ELSE}
  LCLIntf, LCLType,
{$ENDIF}
  Dialogs, Menus, StdCtrls, Controls, Buttons, comCtrls,
  inifiles, Classes, SysUtils, Forms, Messages, ExtCtrls, graphics,
  clipBrd, Grids,
  constreg, regutil, math, maths, uniteker, fft, compile, valeurs,
  graphker, graphvar, graphpar, regdde, TDIClass, Contnrs, Types;

const
    maxMRU = 5;

type

  { TFRegressiMain }

  TFRegressiMain = class(TForm)
    MainMenu: TMainMenu;
    MenuFile: TMenuItem;
    FileNewItem: TMenuItem;
    FileOpenItem: TMenuItem;
    MenuHelp: TMenuItem;
    FileExitItem: TMenuItem;
    FileSaveItem: TMenuItem;
    FileSaveAsItem: TMenuItem;
    MenuEdition: TMenuItem;
    CutItem: TMenuItem;
    CopyItem: TMenuItem;
    MenuItem1: TMenuItem;
    GrandeursItem: TMenuItem;
    GrapheItem: TMenuItem;
    FourierItem: TMenuItem;
    StatItem: TMenuItem;
    GrapheParamItem: TMenuItem;
    PasteItem: TMenuItem;
    MenuPage: TMenuItem;
    PageSuivItem: TMenuItem;
    PagePrecItem: TMenuItem;
    PageDelItem: TMenuItem;
    DeleteItem: TMenuItem;
    FilePrintItem: TMenuItem;
    SeparatorItem: TMenuItem;
    NewClavierItem: TMenuItem;
    NewSimulationItem: TMenuItem;
    PrinterSetUpItem: TMenuItem;
    MruSeparator: TMenuItem;
    MRUItem0: TMenuItem;
    MruItem1: TMenuItem;
    MruItem2: TMenuItem;
    MruITem3: TMenuItem;
    MRUItem5: TMenuItem;
    FileAddItem: TMenuItem;
    AboutItem: TMenuItem;
    SeparatorAide: TMenuItem;
    FileNewClipItem: TMenuItem;
    N1: TMenuItem;
    CollerPageItem: TMenuItem;
    CollerNewDocItem: TMenuItem;
    OptionsItem: TMenuItem;
    PageTrierItem: TMenuItem;
    PageSelectItem: TMenuItem;
    PageAddItem: TMenuItem;
    PageGrouperItem: TMenuItem;
    SaveDialog: TSaveDialog;
    PageNewItem: TMenuItem;
    PageCopyItem: TMenuItem;
    PageCalculerItem: TMenuItem;
    PageNewClipItem: TMenuItem;
    FileCalcItem: TMenuItem;
    TDINB: TTDINoteBook;
    UtilisateurSepar: TMenuItem;
    UtilisateurItem: TMenuItem;
    OpenDialog: TOpenDialog;
    RestaurerItem: TMenuItem;
    RecupItem: TMenuItem;
    RazItem: TMenuItem;
    Annuler1: TMenuItem;
    PanelPage: TPanel;
    PageDebutBtn: TSpeedButton;
    PagePrecBtn: TSpeedButton;
    PageFinBtn: TSpeedButton;
    PagesBtn: TSpeedButton;
    PanelNumPage: TPanel;
    ConstHeader: TStatusBar;
    PageSuivBtn: TSpeedButton;
    CommentaireEdit: TEdit;
    ImageList1: TImageList;
    PageAddBtn: TSpeedButton;
    TOCitem: TMenuItem;
    RandomItem: TMenuItem;
    CommPagePanel: TPanel;
    CommPageEdit: TEdit;
    Groupercolonnes1: TMenuItem;
    ExporterLatex1: TMenuItem;
    MRUitem4: TMenuItem;
    FileBitmap: TMenuItem;
    Courbes2: TMenuItem;
    Rchantillonner1: TMenuItem;
    Distribuer1: TMenuItem;
    procedure FormCreate(Sender: TObject);
    procedure PanelPageClick(Sender: TObject);
    procedure TabGrapheParamContextPopup(Sender: TObject; MousePos: TPoint;
      var Handled: Boolean);
    procedure TDINBChange(Sender: TObject);
    procedure UpdateMenuItems(Sender: TObject);
    procedure FileOpenItemClick(Sender: TObject);
    procedure FileExitItemClick(Sender: TObject);
    procedure FileSaveItemClick(Sender: TObject);
    procedure FileSaveAsItemClick(Sender: TObject);
    procedure CutItemClick(Sender: TObject);
    procedure CopyItemClick(Sender: TObject);
    procedure PasteItemClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure AboutItemClick(Sender: TObject);
    procedure PageSuivClick(Sender: TObject);
    procedure PageAddClick(Sender: TObject);
    procedure PageDelClick(Sender: TObject);
    procedure FileNewClipItemClick(Sender: TObject);
    procedure NewClavierItemClick(Sender: TObject);
    procedure NewSimulationItemClick(Sender: TObject);
    procedure FourierBtnClick(Sender: TObject);
    procedure GrapheBtnClick(Sender: TObject);
    procedure GrandeursBtnClick(Sender: TObject);
    procedure FileAddItemClick(Sender: TObject);
    procedure StatistiqueBtnClick(Sender: TObject);
    procedure PagePrecClick(Sender: TObject);
    procedure MenuPageClick(Sender: TObject);
    procedure GrapheParamBtnClick(Sender: TObject);
    procedure MruItemClick(Sender: TObject);
    procedure MenuEditionClick(Sender: TObject);
    procedure DeleteItemClick(Sender: TObject);
    procedure PageDebutBtnClick(Sender: TObject);
    procedure PageFinBtnClick(Sender: TObject);
    procedure CommentaireEditChange(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure OptionsItemClick(Sender: TObject);
    procedure CollerPageItemClick(Sender: TObject);
    procedure PageTrierItemClick(Sender: TObject);
    procedure PageCalculerItemClick(Sender: TObject);
    procedure PageSelectItemClick(Sender: TObject);
    procedure PageCopyItemClick(Sender: TObject);
    procedure FilePrintItemClick(Sender: TObject);
    procedure PageGrouperItemClick(Sender: TObject);
    procedure FileCalcItemClick(Sender: TObject);
    procedure RestaurerItemClick(Sender: TObject);
    procedure PrinterSetUpItemClick(Sender: TObject);
    procedure ConstHeaderClick(Sender: TObject);
    procedure RecupItemClick(Sender: TObject);
    procedure RazItemClick(Sender: TObject);
    procedure EnregistreBtnClick(Sender: TObject);
    procedure PageNewSimulItemClick(Sender: TObject);
    procedure Annuler1Click(Sender: TObject);
    procedure PageAddBtnClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure RandomItemClick(Sender: TObject);
    procedure CommPageEditChange(Sender: TObject);
    function FormHelp(Command: Word; Data: Integer;
      var CallHelp: Boolean): Boolean;
    procedure Groupercolonnes1Click(Sender: TObject);
    procedure ExporterLatex1Click(Sender: TObject);
    procedure PageAddItemClick(Sender: TObject);
    procedure Courbes1Click(Sender: TObject);
    procedure Rchantillonner1Click(Sender: TObject);
    procedure Distribuer1Click(Sender: TObject);
  private
    MruList : TStringList;
    EditCtl : TCustomEdit; { pour menu édition }
    ActiveGrid : TStringGrid; { pour menu édition }
    GrecActif : boolean;
    NomFichierSauvegarde : string;
    HeureSauvegarde : TDateTime;
    procedure ShowHint(Sender: TObject);
    procedure CloseAll;
    procedure EnvoieMessage(TypeChange : integer);
    procedure MajPages;
    function LitFichierWin : boolean;
    procedure MruItemUpdate;
    procedure MruAdd(FileName: String);
    procedure MruDel(FileName: String);
  public
    NbreGrandeursSauvees : integer;
    KeypadReturn : boolean;
    function VerifSauve : boolean;
    procedure LitFichier(FileName : string;verif : boolean);
    procedure LitCalcul(FileName : string);
    Procedure AjouteFichier(NomFichier : string);
    procedure FinOuvertureFichier(LectureOK : boolean);
    procedure AppMessage(var Msg: TMsg; var Handled: Boolean);
    procedure SauveEtatCourant;
    procedure GrapheConstOpen;
    procedure GrapheOpen;
    procedure StatistiqueOpen;
    procedure FourierOpen;
    procedure GrandeursOpen;
    Procedure AffValeurParametre;
    Procedure VerifSauvegarde;
  protected
    procedure WMRegMaj(var Msg: TWMRegMessage); message wm_Reg_Maj;
    procedure WMRegFichier(var Msg: TWMRegMessage); message wm_Reg_Fichier;
  end;

var
  FRegressiMain: TFRegressiMain;

implementation

uses about, statisti, fileRRR, varkeyb, options, supprDlg,
     graphFFT, pagedistrib,
     regprint, pageCalc, selPage, pageCopy, selParam,
     FusionU, latexreg, CourbesU, pageechant;

  {$R *.lfm}

  {$I filerw3.pas}

const
    indexImageValeurs = 23;
    indexImageGraphe = 9;
    indexImageGrapheParam = 7;
    indexImageGrapheFFT = 8;
    indexImageGrapheStat = 24;

procedure TFregressiMain.AppMessage(var Msg: TMsg; var Handled: Boolean);

const
        GrecMaj : array[0..25] of UnicodeString =
  ('A','B','C',deltaMaj,'E',phiMaj,gammaMaj,'H',
   'I',psiMaj,'K',lambdaMaj,'M','N','O',piMaj,thetaMaj,
   'R',sigmaMaj,'T','U','V',omegaMaj,xiMaj,'Y','Z');

        GrecMin : array[0..25] of UnicodeString =
  (alphaMin,betaMin,chiMin,deltaMin,epsilonMin,phiMin,gammaMin,etaMin,iotaMin,psiMin,kappaMin,lambdaMin,
   muMin,nuMin,'o',piMin,thetaMin,rhoMin,sigmaMin,tauMin,upsilonMin,'v',omegaMin,xiMin,'y',zetaMin);

var codeCarac : integer;
    minuscule : boolean;
begin with Msg do
   if Message=wm_char
   then if (GetKeyState(vk_control)<0)  // Ctrl+
         then begin
              minuscule := (GetKeyState(vk_shift)>=0) and
                           (GetKeyState(vk_capital)>=0);
              if (Wparam=7) and minuscule
                 then GrecActif := true // Ctrl+G
                 else begin
                     if Wparam in [1..2,4..21,23..27] then // moins Ctrl+C(3) et Ctrl+V(22)
                     if minuscule
                         then Wparam := ord(GrecMin[Wparam-1,1])
                             // if Wparam>1 then ?
                         else Wparam := ord(GrecMaj[Wparam-1,1])
                 end
         end
         else begin
              if GrecActif then begin
                 CodeCarac := Wparam-ord('A');
                 if (CodeCarac<26) and (codeCarac>=0)
                    then Wparam := ord(GrecMaj[CodeCarac,1])
                    else begin
                       CodeCarac := Wparam-ord('a');
                       if (CodeCarac<26) and (codeCarac>=0)
                          then Wparam := ord(GrecMin[codeCarac,1]);
                    end;
              end;
              GrecActif := false;
         end
  // Interception des messages 'touche ENTER appuyée'
   else if (message=WM_KEYDOWN) and (wParam=VK_RETURN)
         then KeypadReturn := (Msg.lParam And $1000000)<>0;
end;

procedure TFRegressiMain.FormCreate(Sender: TObject);

Procedure LitCurrentUser;
var Rini : TIniFile;
    i : integer;
    zByte : byte;
    zz : string;

procedure litOptionGr(Ident : string;Aopt : ToptionGraphe);
begin
  if Rini.readBool('Graphe',Ident,Aopt in OptionGrapheDefault) then
     include(OptionGrapheDefault,Aopt);
end;

begin
  try
  Rini := TIniFile.create(NomFichierIni);
  try
  with Rini do begin
  for i := 0 to maxMRU do begin
      try
      zz := ReadString('Fichier','MRU'+IntToStr(i),'');
      MRUList.Add(zz);
      except
         MRUList.Add('');
      end;
  end;
  for i := 0 to MaxPages do begin
      couleurPages[i] := ReadInteger('Color','C'+IntToStr(i),couleurPages[i]);
      stylePages[i] := TpenStyle(ReadInteger('PenStyle','C'+IntToStr(i),ord(stylePages[i])));
      MotifPages[i] := Tmotif(ReadInteger('PointStyle','C'+IntToStr(i),ord(MotifPages[i])));
  end;
  couleurFondIdent := ReadInteger('Color','Ident',couleurFondIdent);
  MotifIdent := TmotifTexte(ReadInteger('Graphe','motifIdent',ord(MotifIdent)));
  hauteurIdent := ReadInteger('Graphe','hauteurIdent',hauteurIdent);
  avecCadreIdent := ReadBool('Graphe','cadreIdent',avecCadreIdent);
  isOpaqueIdent := ReadBool('Graphe','opaqueIdent',isOpaqueIdent);
  couleurMecanique[1] := ReadInteger('Color','Vitesse',clRed);
  couleurMecanique[2] := ReadInteger('Color','Acceleration',clBlue);
  CouleurVitesseImposee := ReadBool('Color','VitesseImposee',true);
  couleurGrille := ReadInteger('Color','Axe',couleurGrille);
  couleurTexte := ReadInteger('Color','Texte',couleurTexte);
  couleurLigne := ReadInteger('Color','Ligne',couleurLigne);
  imprimanteMonochrome := ReadBool('Printer','Mono',false);
  imprimanteMonochrome := imprimanteMonochrome or ReadBool('Imprimante','NB',false);
  try
  longueurTangente := 1/ReadInteger('Tangente','Largeur',1);
  except
      longueurTangente := 0.33;
  end;
  ReticuleComplet := ReadBool('Graphe','Reticule',true);
  zByte := ReadInteger('Graphe','ZoneVirage',1);
  FondReticule := ReadInteger('Color','FondMarque',clYellow);
  LigneRappelTangente := TligneRappel(ReadInteger('Graphe','Tangente',0));  
  avecOptionsXY := ReadBool('Graphe','OptionsXY',avecOptionsXY);
  ChercheUniteParam := ReadBool('Modele','UnitParam',ChercheUniteParam);
  AvecModeleManuel := ReadBool('Modele','Manuel',AvecModeleManuel);
  AvecReglagePeriode := ReadBool('FFT','ReglePeriode',false);
  NbreHarmoniqueAff := ReadInteger('FFT','NbreHarmAff',NbreHarmoniqueAff);
  HarmoniqueAff := ReadBool('FFT','HarmAff',HarmoniqueAff);  
  CouleurExp := ReadInteger('Color','Exp',couleurExp);
  CouleurNonExp := ReadInteger('Color','NonExp',couleurNonExp);
  TraceDefaut := TtraceDefaut(ReadInteger('Graphe','TracePoint',ord(traceDefaut)));
  PrecisionCorrel := ReadInteger('CoeffCorrel','Nchiffres',5);
  LitOptionGr('Grille',OgQuadrillage);
  LitOptionGr('ZeroIdem',OgMemeZero);
  if readBool('Sauvegarde','Arecuperer',false) then
     MruAdd(NomFichierSauvegarde);
  writeBool('Sauvegarde','Arecuperer',true);
  fenetre := Tfenetre(readInteger('FFT','Fenetre',ord(fenetre)));
  PasSonagrammeAff := readInteger('FFT','PasSonAff',25)/1000;
  PasSonCalcul := readInteger('FFT','PasSonCalcul',1);
  if pasSonCalcul<1 then pasSonCalcul := 1;
  if pasSonCalcul>3 then pasSonCalcul := 3;
  FreqMaxSonagramme := readInteger('FFT','FreqSonMax',5000);
end;
  finally
  Rini.free;
  end;
  except
  end;
end; // litCurrentUser

Procedure AppelFichier;
var NomFichier,zz : String;
    i : integer;
begin
    NomFichier := '';
    for i := 1 to paramCount do begin
        zz := ParamStr(i);
        if zz[1]<>'/' then if NomFichier=''
            then NomFichier := zz
            else NomFichier := NomFichier+' '+zz;
    end;
    if NomFichier<>'' then begin
       ClipBoard.AsText := NomFichier;
       PostMessage(handle,wm_reg_fichier,1,0);
    end;
end; // appelFichier

begin  // FormCreate
  Application.OnHint := ShowHint;
  Application.ShowHint := true;
  ModeAcquisition := AcqClavier;
  MruList := TStringList.Create;
  try
  litCurrentUser;
  except
  end;
  OptionsItem.visible := existeOption('O',true);
  MruItemUpdate; // Update MRU menu items
//  Application.OnMessage := AppMessage;
  ModifFichier := false;
  NomFichierData := '';
  if paramCount>0 then appelFichier;
  UpDateMenuItems(nil);
  HeureSauvegarde := now;
  openDialog.filterIndex := 1;
  NomFichierSauvegarde := mesDocsDir+'Regressi.rw3';
end; // FormCreate

procedure TFRegressiMain.PanelPageClick(Sender: TObject);
begin
end;

procedure TFRegressiMain.TabGrapheParamContextPopup(Sender: TObject;
  MousePos: TPoint; var Handled: Boolean);
begin
end;

procedure TFRegressiMain.TDINBChange(Sender: TObject);
begin
end;

procedure TFRegressiMain.ShowHint(Sender: TObject);
var FilePart : string;
begin
   if Application.Hint=''
      then begin
          Caption := 'Regressi';
          if NomFichierData<>'' then begin
             try
             FilePart := ExtractFileName(nomFichierData);
             Caption := 'Regressi ['+FilePart+']';
             except
             end;
          end;
      end
      else Caption := Application.Hint
end;

procedure TFRegressiMain.CloseAll;
begin
     Caption := 'Regressi';
     Fvaleurs.perform(WM_REG_MAJ,MajVide,0);
     FgrapheVariab.perform(WM_REG_MAJ,MajVide,0);
     FgrapheFFT.perform(WM_REG_MAJ,MajVide,0);
     FgrapheStat.perform(WM_REG_MAJ,MajVide,0);
     FgrapheParam.perform(WM_REG_MAJ,MajVide,0);
     commPagePanel.visible := false;
     resetEnTete;
     Application.ProcessMessages;
end;

Function TFregressiMain.VerifSauve : boolean;
var zz : string;
begin
  result := true;
  grandeursOpen;
  grapheOpen;
  if pageCourante>0 then begin
     if NomFichierData=''
        then zz := stData
        else zz := stModif+ExtractFileName(nomFichierData);
     if (pageCourante>0) and modifFichier
        then case MessageDlg(stSauve+zz,mtConfirmation,[mbYes,mbNo,mbCancel],0) of
           mrYes : if NomFichierData=''
               then FileSaveAsItemClick(nil)
               else FileSaveItemClick(nil);
           mrNo : result := true;
           mrCancel : result := false;
        end; // case
  end;
  if result then closeAll;
end;

procedure TFRegressiMain.FileOpenItemClick(Sender: TObject);
begin
    if OpenDialog.InitialDir='' then OpenDialog.InitialDir := MesDocsDir;
    OpenDialog.Title := stOuvrir;
    if OpenDialog.execute then
       LitFichier(openDialog.FileName,true);
end;

procedure TFRegressiMain.LitFichier(FileName : string;verif : boolean);
var verifLecture : boolean;
    extension : string;
begin
try
if FileExists(FileName)
  then begin
      if verif
           then begin if not verifSauve then exit end
           else closeAll;
     optionsDlg.resetConfig;
     grandeursOpen;
     grapheOpen;
     modeAcquisition := AcqFichier;
     Screen.cursor := crHourGlass;
     nomFichierData := FileName;
     ErreurDetectee := false;
     extension := AnsiUpperCase(extractFileExt(nomFichierData));
     if extension='' then nomFichierData := ChangeFileExt(nomFichierData,'.RW3');
     if extension='.RW3'
        then VerifLecture := litFichierWin
        else if extension='.CSV'
             then VerifLecture := litFichierCSV(nomFichierData,true)
             else if extension='.RXML'
             then VerifLecture := litFichierXML(nomFichierData)
                   else if (extension='.XML')
                     then VerifLecture := litFichierVotable (FileName)
                     else if (extension='.FIT') or (extension='.FITS')
                     then VerifLecture := litFichierFITS(FileName)
                     else verifLecture := FormDDE.importeFichierTableur(nomFichierData);
     FinOuvertureFichier(verifLecture);
     Screen.cursor := crDefault;
  end
  else begin
     codeErreurF := erFileNotExist+' : '+FileName;
     FinOuvertureFichier(false);
  end;
  except
     codeErreurF := '';
     FinOuvertureFichier(false);
  end;
end;

procedure TFRegressiMain.FileSaveItemClick(Sender: TObject);
begin
     if pageCourante>0 then if nomFichierData<>''
        then EcritFichierXML(NomFichierData)
        else FileSaveAsItemClick(sender);
end;

procedure TFRegressiMain.FileSaveAsItemClick(Sender: TObject);
var extension : string;
begin
if SaveDialog.InitialDir=''
   then SaveDialog.InitialDir := MesDocsDir;
with saveDialog do if Execute then begin
     extension := AnsiUpperCase(ExtractFileExt(FileName));
     case filterIndex of
          2 : extension := '.TXT';
          3 : extension := '.CSV';
          4 : extension := '.XML';
     end;
     if (ofExtensionDifferent in Options) or (filterIndex>1)
        then begin
            if extension='.CSV' then begin
                 FormDDE.exporteFichierTableur(FileName);
                 filterIndex := 3;
                 exit;
            end;
            if extension='.XML' then begin
                 EcritFichierXML(FileName);
                 filterIndex := 4;
                 exit;
            end;
            if extension='.TXT' then begin
                 FileName := ChangeFileExt(FileName,'.TXT');
                 FormDDE.exporteFichierTableur(FileName);
                 filterIndex := 2;
                 exit
            end;
    end;
    filterIndex := 1;
    MruAdd(FileName); // Update MRUList using saved filename
    NomFichierData := FileName;
    ecritFichierXML(FileName);
end end;

procedure TFRegressiMain.FileExitItemClick(Sender: TObject);
begin
    Close
end;

procedure TFRegressiMain.CutItemClick(Sender: TObject);

procedure CutRange;
var r1,c1,r2,c2,r,c:integer;
    list,flist:tstringlist;
begin with activeGrid do begin
 c1:=Selection.Left;
 r1:=selection.top;
 c2:=Selection.Right ;
 r2:=selection.Bottom ;
 if not ((c1>=0)and (r1>=0)and (c2>=c1)and (r2>=r1)) then exit;
 list:=tstringlist.create;
 flist:=tstringlist.create;
 for r:=r1 to r2 do begin
   flist.clear;
   for c:=c1 to c2 do begin
     flist.append(cells[c,r]);
     cells[c,r]:='';
   end;
   list.append(flist.commatext);
 end;
 clipboard.astext:=list.text;
 flist.free;
 list.free;
end end;

begin
   if Assigned(EditCtl) then with EditCtl do CutToClipBoard;
   if Assigned(ActiveGrid) then CutRange;
end; // CutItemClick

procedure TFRegressiMain.CopyItemClick(Sender: TObject);

procedure CopyRange;
var r1,c1,r2,c2,r,c:integer;
    list,flist:tstringlist;
begin with activeGrid do begin
 c1:=Selection.Left;
 r1:=selection.top;
 c2:=Selection.Right ;
 r2:=selection.Bottom ;
 if not ((c1>=0)and (r1>=0)and (c2>=c1)and (r2>=r1)) then exit;
 list:=tstringlist.create;
 flist:=tstringlist.create;
 for r:=r1 to r2 do begin
    flist.clear;
    for c:=c1 to c2 do flist.append(cells[c,r]);
    list.append(flist.commatext);
 end;
 clipboard.astext:=list.text;
 flist.free;
 list.free;
end end;

begin
    if Assigned(EditCtl)
       then with EditCtl do CopyToClipBoard
       else if Assigned(ActiveGrid)
       then CopyRange
       else begin
           if FgrapheVariab.focused then
              FgrapheVariab.CopierItemClick(sender);
           if FgrapheParam.focused then
              FgrapheParam.CopierItemClick(sender);
           if FgrapheFFT.focused then
              FgrapheFFT.CopierItemClick(sender);
           if FgrapheStat.focused then
              FgrapheStat.CopierItemClick(sender);
       end;
end; //CopyItemClick

procedure TFRegressiMain.Courbes1Click(Sender: TObject);
begin
     if not verifSauve then exit;
     try
     if courbesForm=nil then
         Application.CreateForm(TcourbesForm,courbesForm);
     courbesForm.WindowState := wsMaximized;
     NomFichierData := '';
     modeAcquisition := AcqCourbes;
     TDINB.ShowFormInPage(courbesForm,0);
   //  courbesForm.SetFocus;
     except
     end;
end;

procedure TFRegressiMain.PasteItemClick(Sender: TObject);

procedure PasteRange;
var r1,c1,r2,c2,r,c,i,j:integer;
    list,flist:tstringlist;
begin
if activeGrid=Fvaleurs.GridVariab then with activeGrid do begin
 if not clipboard.HasFormat(CF_TEXT) then exit;
 if not ((col>=0) and (row>=0)) then exit;
 list:=tstringlist.create;
 flist:=tstringlist.create;
 list.text:=clipboard.AsText ;
 if list.count>0 then begin
    c1:=col;
    r1:=row;
    flist.commatext:=list[0];
    c2:=c1+flist.count-1;
    r2:=r1+list.count-1;
    if c2>(colcount-1) then c2:=colcount-1;
    if r2>(rowcount-1) then r2:=rowcount-1;
    j:=0;
    for r:=r1 to r2 do begin
      flist.commatext:=list[j];
      i:=0;
      for c:=c1 to c2 do begin
        Fvaleurs.setValeurVariab(c,r,flist[i]);
        inc(i);
      end;
      inc(j);
   end;
 end;
 flist.free;
 list.free;
 Fvaleurs.MajGridVariab := true;
 Fvaleurs.traceGridVariab;
end end;

begin
   if Assigned(EditCtl) then begin
      if editCtl=Fvaleurs.memo
         then Fvaleurs.CollerItemClick(sender)
         else EditCtl.PasteFromClipBoard;
   end;
   if Assigned(ActiveGrid) then PasteRange;   
end; // PasteItemClick

procedure TFRegressiMain.UpdateMenuItems(Sender: TObject);
var p,NbrePagesExp : integer;
begin
   TDINB.enabled := pageCourante>0;
   FileSaveItem.Enabled := pageCourante>0;
   FileSaveAsItem.Enabled := pageCourante>0;
   FileAddItem.Enabled := pageCourante>0;
   FilePrintItem.enabled := pageCourante>0;
   ExporterLatex1.enabled := pageCourante>0;
   FileCalcItem.Enabled := pageCourante>0;
   MenuPage.Enabled := pageCourante>0;
   NbrePagesExp := 0;
   for p := 1 to nbrePages do
       if pages[p].experimentale then inc(NbrePagesExp);
   PageCalculerItem.Enabled := (NbrePagesExp>=2) and
                               (ModeAcquisition<>AcqSimulation);
   PageCopyItem.Enabled := ModeAcquisition<>AcqSimulation;
   PageSelectItem.Enabled := nbrePages>1;
end;

procedure TFRegressiMain.FormDestroy(Sender: TObject);
begin
   MruList.free;
end;

function TFRegressiMain.FormHelp(Command: Word; Data: Integer;
  var CallHelp: Boolean): Boolean;
begin
  result := false;
  inherited;
end;

procedure TFRegressiMain.EnvoieMessage(TypeChange : integer);
begin
     if (TypeChange=MajChangePage) and (pageCourante>0) then
        with pages[pageCourante] do begin
           affecteConstParam;
           affecteVariableP(false);
        end;
     Perform(WM_Reg_Maj,TypeChange,0)
end;

procedure TFRegressiMain.AffValeurParametre;
var i,index,imax,largeur,largeurCarac : integer;
    Asection : TstatusPanel;
    awidth : integer;
begin
     i := 0;
     while i<ListeConstAff.count do begin
         index := indexNom(ListeConstAff[i]);
         if (index=grandeurInconnue) or
            (grandeurs[index].genreG<>constante)
            then ListeConstAff.delete(i)
            else inc(i)
     end;
     if (NbreConst>0) and
        (ListeConstAff.count=0) then begin
           imax := pred(NbreConst);
           if imax>2 then imax := 2;
           for i := 0 to imax do
               ListeConstAff.add(grandeurs[indexConst[i]].nom);
     end;
     ConstHeader.panels.clear;
     aWidth := 0;
     largeurCarac := ConstHeader.canvas.textWidth('A');
     for i := 0 to pred(ListeConstAff.count) do begin
         index := indexNom(ListeConstAff[i]);
         Asection := ConstHeader.panels.add;
         Asection.text := grandeurs[index].FormatNomEtUnite(pages[pageCourante].valeurConst[index]);
         largeur := ConstHeader.canvas.textWidth(Asection.text)+2*largeurCarac;
         if largeur<10*largeurCarac then largeur := 10*largeurCarac;
         Asection.width := Largeur;
         inc(aWidth,largeur);
     end;
     ConstHeader.width := aWidth;
end;

procedure TFRegressiMain.MajPages;
var i : integer;
begin
     lectureFichier := false;
     lecturePage := false;
     if pageCourante>NbrePages then pageCourante := NbrePages;
     PanelPage.visible := NbrePages>1;
     CommPagePanel.visible := NbrePages=1;
     if pageCourante>0 then
        CommentaireEdit.text := pages[pageCourante].commentaireP;
     if NbrePages=1 then
        CommPageEdit.text := pages[1].commentaireP;
     for i := 1 to NbrePages do pages[i].numero := i;
     PanelNumPage.Caption := IntToStr(PageCourante)+'/'+IntToStr(NbrePages);
     PanelNumPage.Font.color := couleurPages[pageCourante];
     CommentaireEdit.Font.color := couleurPages[pageCourante];
     AffValeurParametre;
end;

procedure TFRegressiMain.AboutItemClick(Sender: TObject);
begin
     AboutBox := TaboutBox.create(self);
     AboutBox.ShowModal;
     AboutBox.free;
end;

procedure TFRegressiMain.WMRegFichier(var Msg: TWMRegMessage);
var clipspn,ficspn,NomComplet : string;
begin
     nomComplet := clipBoard.asText;
     clipspn := ExtractShortPathName(nomComplet);
     if clipspn='' then clipspn := 'clip';
     ficspn := ExtractShortPathName(nomFichierData);
     if ficspn='' then ficspn := 'fichier';
     if not AnsiSameText(nomComplet,NomFichierData) and
        not AnsiSameText(clipspn,ficspn)
            then LitFichier(nomComplet,true);
end;

procedure TFRegressiMain.WMRegMaj(var Msg: TWMRegMessage);
begin with Msg do begin
     case typeMaj of
          MajNumeroMesure : Fvaleurs.Perform(WM_Reg_Maj,MajNumeroMesure,CodeMaj);
          MajFichier : begin
             majPages;
             Fvaleurs.Perform(WM_Reg_Maj,MajFichier,CodeMaj);
          end
          else begin
             if TypeMaj in [MajGrandeur,MajAjoutPage,
                   MajSelectPage,MajGroupePage,MajChangePage,MajSupprPage] then
                       majPages;
             if TypeMaj in [MajAjoutPage,MajSupprPage,MajTri] then SauveEtatCourant;
             UpDateMenuItems(nil);
             Fvaleurs.Perform(WM_Reg_Maj,TypeMaj,CodeMaj); // en premier
             FgrapheVariab.Perform(WM_Reg_Maj,TypeMaj,CodeMaj);
             FgrapheFFT.Perform(WM_Reg_Maj,TypeMaj,CodeMaj);
             FgrapheStat.Perform(WM_Reg_Maj,TypeMaj,CodeMaj);
             FgrapheParam.Perform(WM_Reg_Maj,TypeMaj,CodeMaj);
        end
    end;
end end;

procedure TFRegressiMain.PageSuivClick(Sender: TObject);
begin
  envoieMessage(MajSauvePage);
  if pageCourante<NbrePages
     then inc(PageCourante)
     else pageCourante := 1;
  envoieMessage(MajChangePage);
end; // PageSuivante

procedure TFRegressiMain.PagePrecClick(Sender: TObject);
begin
    envoieMessage(MajSauvePage);
    if pageCourante>1
       then dec(pageCourante)
       else pageCourante := NbrePages;
    envoieMessage(MajChangePage)
end; // PagePrecedente

procedure TFRegressiMain.PageAddClick(Sender: TObject);
var i : integer;
begin
     case ModeAcquisition of
          AcqClavier,AcqClipBoard : if ajoutePage then begin
             for i := 1 to NbreConstExp do
                 Pages[NbrePages].valeurConst[i] := pages[pred(NbrePages)].valeurConst[i];
             if NbreConstExp>0 then
                FValeurs.Feuillets.ActivePage := Fvaleurs.paramSheet;
             envoieMessage(MajAjoutPage);
             ModifFichier := true;
             if NbreConstExp>0 then TDINB.ShowFormInPage(FValeurs,indexImageValeurs);
          end;
          AcqCan : ;
          AcqFichier : FileAddItemClick(sender);
          AcqSimulation : PageNewSimulItemClick(sender);
          AcqCourbes : begin
              if courbesForm=nil then
                 Application.CreateForm(TcourbesForm,courbesForm);
              courbesForm.WindowState := wsMaximized;
              TDINB.ShowFormInpage(courbesForm,1);
            //  courbesForm.SetFocus;
          end;
     end;
     modifFichier := true;
end;

procedure TFRegressiMain.PageAddItemClick(Sender: TObject);
begin
  inherited;
  CollerPageItem.Visible := ModeAcquisition=AcqClipBoard;
  PageNewItem.Visible := true;
  case ModeAcquisition of
        AcqClavier,AcqClipBoard : PageNewItem.Caption := 'Créer page vierge';
        AcqCan : ;
        AcqFichier : PageNewItem.Caption := 'Fusionner';
        AcqSimulation : PageNewItem.Caption := 'Créer page simulée';
        else begin
           PageNewItem.Caption := '';
           PageNewItem.Visible := false;
        end;
  end;
end;

procedure TFRegressiMain.PageDelClick(Sender: TObject);
begin
     if OKformat(OkDelPage,[IntToStr(pageCourante)]) then begin
        supprimePage(pageCourante,true);
        envoieMessage(MajSupprPage);
     end;
end;

procedure TFRegressiMain.FileNewClipItemClick(Sender: TObject);
begin
    ModifFichier := true;
    FgrapheVariab.Perform(WM_Reg_Maj,MajVide,0);
    FormDDE.ImportePressePapier;
    FgrapheVariab.Perform(WM_Reg_Maj,MajFichier,0);
end;

procedure TFRegressiMain.NewClavierItemClick(Sender: TObject);
begin
      if NewClavierDlg=nil then
         Application.CreateForm(TNewClavierDlg,NewClavierDlg);
      if NewClavierDlg.showModal=mrOK then begin
         FichierTrie := DataTrieGlb;
         AjoutePage;
         Pages[1].CommentaireP := NewClavierDlg.MemoClavier.lines[0];
         ModifFichier := true;
         optionsDlg.resetConfig;
         ClavierAvecGraphe := false;
         FgrapheVariab.Perform(WM_Reg_Maj,MajVide,0);
         FgrapheVariab.configCharge := true;
         FgrapheVariab.Graphes[1].useDefaut := NewClavierDlg.grapheMinMax;
         FgrapheVariab.Perform(WM_Reg_Maj,MajFichier,0);
         pages[pageCourante].affectevariableP(false);
         FValeurs.Perform(WM_Reg_Maj,MajFichier,0);
         FValeurs.feuillets.ActivePage := Fvaleurs.VariabSheet;
         FValeurs.TraceGrid;
         TDINB.ShowFormInPage(FValeurs,indexImageValeurs);
      end;
end;

procedure TFRegressiMain.NewSimulationItemClick(Sender: TObject);
begin
    if not verifSauve then exit;
    NomFichierData := '';
    ModeAcquisition := AcqSimulation;
    OrdreLissage := 3;
    OrdreFiltrage := 2;
    AjoutePage;
    optionsDlg.resetConfig;
    ajouteExperimentale('t',variable);
    Grandeurs[0].NomUnite := 's';
    GrandeursBtnClick(nil);
    Fvaleurs.Perform(WM_Reg_Maj,MajFichier,0);
 //   TDINB.ShowFormInPage(Fvaleurs,indexImageValeurs);
end;

procedure TFRegressiMain.FourierBtnClick(Sender: TObject);
begin
     FourierOpen;
end;

procedure TFRegressiMain.FourierOpen;
begin
    if FGrapheFFT=nil then begin
       Application.CreateForm(TFGrapheFFT, FGrapheFFT);
    end;
    TDINB.ShowFormInPage(FgrapheFFT, indexImageGrapheFFT);
end;

procedure TFRegressiMain.ExporterLatex1Click(Sender: TObject);
begin
     if LatexDlg=nil
        then Application.CreateForm(TLatexDlg, LatexDlg);
     LatexDlg.showModal;
end;

procedure TFRegressiMain.GrandeursOpen;
begin
     if FValeurs=nil then begin
        Application.CreateForm(TFValeurs, FValeurs);
     end;
     TDINB.ShowFormInPage(FValeurs,indexImageValeurs);
end;

procedure TFRegressiMain.GrapheBtnClick(Sender: TObject);
begin
     grapheOpen;
end;

procedure TFRegressiMain.GrandeursBtnClick(Sender: TObject);
begin
     grandeursOpen;
end;

procedure TFRegressiMain.FileAddItemClick(Sender: TObject);

procedure AddFichier(NomFichier : string);
var extension : string;
    p,pageDebut : codePage;
begin
       extension := AnsiUpperCase(extractFileExt(NomFichier));
       if extension='' then begin
          nomFichier := ChangeFileExt(nomFichier,'.RW3');
          extension := '.RW3'
       end;
       PageDebut := succ(PageCourante);
       if extension = '.RW3'
          then AjouteFichier(NomFichier)
          else if extension = '.CSV'
                  then LitFichierCSV(NomFichier,false)
                  else if (extension='.FIT') or (extension='.FITS')
                     then ajouteFichierFits(NomFichier)
                     else FormDDE.AjouteFichierTableur(NomFichier);
       for p := pageDebut to NbrePages do pages[p].recalculP;
end;

var i : integer;
begin
   OpenDialog.Title := 'Fusionner';
   OpenDialog.options := OpenDialog.options + [ofAllowMultiSelect];
   Screen.cursor := crHourGlass;
   lecturePage := true;
   if OpenDialog.execute then
      if OpenDialog.Files.count>1
         then begin
             for i := 0 to OpenDialog.Files.Count - 1 do
               AddFichier(OpenDialog.Files.Strings[I])
         end
         else AddFichier(openDialog.FileName);
   envoieMessage(MajFichier);
   OpenDialog.options := OpenDialog.options - [ofAllowMultiSelect];
   Screen.cursor := crDefault;
   modifFichier := true;
end;

procedure TFRegressiMain.StatistiqueBtnClick(Sender: TObject);
begin
     if pageCourante>0 then statistiqueOpen;
end;

procedure TFRegressiMain.StatistiqueOpen;
begin
    if FGrapheStat=nil then
         Application.CreateForm(TFGrapheStat, FGrapheStat);
    TDINB.ShowFormInPage(FgrapheStat, indexImageGrapheStat);
end;

procedure TFRegressiMain.FinOuvertureFichier(LectureOK : boolean);
var p : integer;
begin
     LectureFichier := false;
     LecturePage := false;
     ModifFichier := false;
     if LectureOK
         then begin
           p := 1;
           while (p<NbrePages) and not pages[p].active do inc(p);
           if not pages[p].active then pages[1].active := true;
           MruAdd(nomFichierData);  // Update MRUList 
           Caption := 'Regressi Linux ['+nomFichierData+']';
           for p := 1 to NbrePages do
               pages[p].NbrePointsSauves := pages[p].nmes;
        end
        else begin
           MruDel(nomFichierData);
           nomFichierData := '';
           if codeErreurF<>'' then AfficheErreur(codeErreurF,0);
           Caption := 'Regressi Linux';
        end;
     if NbrePages>0
         then begin
             PageCourante := 1;
             if FgrapheVariab.ModelePagesIndependantesMenu.checked and
                 (Pages[1].TexteModeleP.count>0) then begin
                    ModelePagesIndependantes := true;
                    TexteModele.clear;
                    TexteModele := pages[1].TexteModeleP;
              end;
         end
         else PageCourante := 0;
     envoieMessage(MajFichier); // Fvaleurs uniquement ; fait également majPages
     NbreGrandeursSauvees := NbreGrandeurs;
     UpDateMenuItems(nil);
     if lectureOK then begin
        if erreurDetectee or (NbreVariab<2)
           then TDINB.ShowFormInPage(Fvaleurs,indexImageValeurs)
           else TDINB.ShowFormInPage(FgrapheVariab,indexImagegraphe);
     end;
end;

procedure TFRegressiMain.MenuPageClick(Sender: TObject);
begin
     PageSuivItem.enabled := NbrePages>1;
     PagePrecItem.enabled := NbrePages>1;
     PageDelItem.enabled := NbrePages>1;
     PageGrouperItem.enabled := NbrePages>1;
     PageAddItem.enabled := NbrePages<MaxPages;
     PageNewClipItem.visible := ModeAcquisition=AcqClipBoard;
     PageNewItem.visible := true;
end;

procedure TFRegressiMain.GrapheParamBtnClick(Sender: TObject);
begin
     GrapheConstOpen;
     FgrapheParam.configCharge := true;
     FgrapheParam.MajFichierEnCours := false;
end;

procedure TFRegressiMain.GrapheConstOpen;
begin
    if FgrapheParam=nil then
       Application.CreateForm(TFGrapheParam, FGrapheParam);
    TDINB.ShowFormInPage(FGrapheParam, indexImageGrapheParam);
end;

procedure TFRegressiMain.GrapheOpen;
begin
    if FgrapheVariab=nil then
       Application.CreateForm(TFGrapheVariab, FGrapheVariab);
    TDINB.ShowFormInPage(FGrapheVariab, indexImageGraphe);
end;

procedure TFRegressiMain.Groupercolonnes1Click(Sender: TObject);
var NomFichierTemp : string;
begin
   if OKreg(okPageVersCol,0) then begin
      EcritFichierXML(NomFichierTemp);
      groupePageColonnes;
      modifFichier := true;
   end;
end;

procedure TFRegressiMain.MruItemClick(Sender: TObject);
var index : Integer;
    nom : string;
begin
  Index := TMenuItem(Sender).Tag;
  nom := MruList[Index];
  if FileExists(nom)
     then LitFichier(nom,true)
     else afficheErreur(TMenuItem(Sender).caption+erNotExists,0)
end;

procedure TFRegressiMain.MruItemUpdate;
var i,ii : integer;
begin
  ii := MRUSeparator.MenuIndex+1;
  for i := 0 to pred(MRUList.count) do begin
     if length(MRUList[i])>0 then
        MenuFile.Items[i+ii].Caption := '&'+IntToStr(succ(i))+' '+
            MRUList[i][1]+': '+ ExtractFileName(MRUList[i]);
     MenuFile.Items[i+ii].Visible := (MRUList[i]<>''); // Visible if not blank
  end;
  MRUSeparator.Visible :=  (MRUList[0] <> ''); // Seperator visible if not blank
end;

procedure TFRegressiMain.MruAdd(FileName: String);
begin
  if FileName='' then exit;
  MruDel(FileName);
  while MruList.count > maxMru do MRUList.delete(MRUList.Count - 1);
  while MruList.count < maxMru do MRUList.add('');
  MruList.Insert(0,Filename);
  MruItemUpdate;
end;

procedure TFRegressiMain.MruDel(FileName: String);
var
  Index: Integer;
begin
  Index := 0;
// Compare FileName to MRUList items
  while Index < (MRUList.count - 1) do
    if AnsiUpperCase(FileName) = AnsiUpperCase(MRUList[Index])
       then MRUList.delete(Index) // If already there, delete occurrence
       else inc(Index) // If not try next item
end;

procedure TFRegressiMain.MenuEditionClick(Sender: TObject);
var S : tsauvegarde;
begin
   UtilisateurItem.visible := true;
   UtilisateurSepar.visible := true;
   CollerPageItem.enabled := NbrePages>0;
   RazItem.enabled := NbrePages>0;
   RestaurerItem.visible := PileSauvegarde.count>0;
//   UndoBtn.Hint := 'Annuler';
   If restaurerItem.visible then begin
      S := PileSauvegarde.peek;
      case S.undo of
           UsupprPage : restaurerItem.caption := stUndo+'page';
           UsupprPoint : restaurerItem.caption := stUndo+'points';
           UsupprConst,UsupprVariab :
              restaurerItem.caption := stUndo+S.GrandeurSauvee.nom;
           Ugrouper : restaurerItem.caption := stUndoGr;
      end;
  //    UndoBtn.Hint := restaurerItem.caption;
   end;
//   undoBtn.Hint := restaurerItem.caption;
   EditCtl := nil;
   ActiveGrid := nil;
   if Screen.ActiveControl is TCustomEdit
      then EditCtl := Screen.ActiveControl as TCustomEdit
      else if (Screen.ActiveControl is TCustomGrid)
           then ActiveGrid := Screen.ActiveControl as TstringGrid;
//  if Assigned(EditCtl) and (EditCtl.SelLength=0) then EditCtl.selLength := 1;
  if Assigned(EditCtl) or Assigned(ActiveGrid)
    then begin
       CutItem.Enabled := true;
       CopyItem.Enabled := CutItem.Enabled;
       PasteItem.Enabled := ClipBoard.AsText <> '';
       DeleteItem.Enabled := CutItem.Enabled;
    end
    else begin
       CutItem.Enabled := false;
       CopyItem.Enabled := true;
       PasteItem.Enabled := False;
       DeleteItem.Enabled := False;
    end;
end;

procedure TFRegressiMain.DeleteItemClick(Sender: TObject);
begin
   if Assigned(EditCtl) then with EditCtl do ClearSelection;
end;

procedure TFRegressiMain.Distribuer1Click(Sender: TObject);
begin
     PageDistribDlg := TPageDistribDlg.create(self);
     PageDistribDlg.showModal;
     PageDistribDlg.free;
end;

procedure TFRegressiMain.PageDebutBtnClick(Sender: TObject);
begin
     if PageCourante>1 then begin
        envoieMessage(MajSauvePage);
        PageCourante := 1;
        envoieMessage(MajChangePage);
     end;
end;

procedure TFRegressiMain.PageFinBtnClick(Sender: TObject);
begin
     if PageCourante<NbrePages then begin
        envoieMessage(MajSauvePage);
        PageCourante := NbrePages;
        envoieMessage(MajChangePage);
     end;
end;

procedure TFRegressiMain.CommentaireEditChange(Sender: TObject);
begin
    if pageCourante>0 then
       pages[pageCourante].commentaireP := CommentaireEdit.text
end;

procedure TFRegressiMain.CommPageEditChange(Sender: TObject);
begin
    pages[1].commentaireP := CommPageEdit.text
end;

procedure TFRegressiMain.FormClose(Sender: TObject;var Action: TCloseAction);

Procedure EcritCurrentUser;
var i : integer;
    Rini : TInifile;
begin
    MruDel(NomFichierSauvegarde);
    try
    RIni := TIniFile.create(NomFichierIni);
    with RIni do begin
    for i := 0 to maxMru do
        WriteString('Fichier','MRU'+IntToStr(i),MRUList[i]);
    for i := 0 to MaxPages do begin
        WriteInteger('Color','C'+IntToStr(i),couleurPages[i]);
        WriteInteger('PenStyle','C'+IntToStr(i),ord(stylePages[i]));
        WriteInteger('PointStyle','C'+IntToStr(i),ord(MotifPages[i]));
    end;
    WriteInteger('Color','Ident',couleurFondIdent);
    WriteInteger('Graphe','motifIdent',ord(MotifIdent));
    WriteInteger('Graphe','hauteurIdent',hauteurIdent);
    WriteBool('Graphe','cadreIdent',avecCadreIdent);
    WriteBool('Graphe','opaqueIdent',isOpaqueIdent);
    WriteInteger('Color','Vitesse',couleurMecanique[1]);
    WriteInteger('Color','Acceleration',couleurMecanique[2]);
    WriteBool('Color','VitesseImposee',CouleurVitesseImposee);
    WriteInteger('Color','Axe',couleurGrille);
    WriteInteger('Color','Texte',couleurTexte);
    WriteInteger('Color','Ligne',couleurLigne);
    WriteBool('Graphe','Reticule',ReticuleComplet);
    WriteBool('Printer','Mono',imprimanteMonochrome);
    WriteBool('Imprimante','NB',imprimanteMonochrome);
    WriteBool('FFT','ReglePeriode',AvecReglagePeriode);
    WriteInteger('Tangente','Largeur',round(1/longueurTangente));
    for i := 1 to MaxOrdonnee do begin
        WriteInteger('Color','O'+IntToStr(i),couleurInit[i]);
        WriteInteger('PointStyle','O'+IntToStr(i),ord(MotifInit[i]));
    end;      
    for i := 1 to MaxIntervalles do begin
        WriteInteger('Color','M'+IntToStr(i),couleurModele[i]);
        WriteInteger('Color','S'+IntToStr(i),couleurModele[-i]);
    end;
    WriteInteger('Color','FondMarque',FondReticule);
    WriteInteger('Graphe','Tangente',ord(LigneRappelTangente));
    WriteInteger('Fichier','Filtre',OpenDialog.filterIndex);
    WriteBool('Modele','UnitParam',ChercheUniteParam);
    WriteBool('Modele','Manuel',AvecModeleManuel);
    writeBool('Graphe','OptionsXY',avecOptionsXY);
    writeBool('Graphe','Grille',OgQuadrillage in OptionGrapheDefault);
    writeBool('Graphe','ZeroIdem',OgMemeZero in OptionGrapheDefault);
    writeBool('Graphe','ZeroGradue',OgZeroGradue in OptionGrapheDefault);
    writeBool('CoeffCorrel','Affiche',WithCoeffCorrel);
    writeBool('Graphe','Pvaleur',WithPvaleur);
    writeInteger('Graphe','AffIncertParam',ord(affIncertParam));
    writeBool('Graphe','BandeConfiance',WithBandeConfiance);    
    writeInteger('CoeffCorrel','Nchiffres',PrecisionCorrel);
    writeInteger('FFT','Fenetre',ord(fenetre));
    writeInteger('FFT','PasSonAff',round(PasSonagrammeAff*1000));
    writeInteger('FFT','PasSonCalcul',PasSonCalcul);
    writeInteger('FFT','FreqSonMax',round(FreqMaxSonagramme));
    writeInteger('FFT','NbreHarmAff',NbreHarmoniqueAff);
    WriteBool('FFT','HarmAff',HarmoniqueAff);
    WriteInteger('Color','Exp',couleurExp);
    WriteInteger('Color','NonExp',couleurNonExp);
    WriteInteger('Graphe','TracePoint',ord(TraceDefaut));
    WriteBool('Sauvegarde','Arecuperer',false);
    end;
    except
    end;
end; // EcritCurrentUser

begin
    action := caNone;
    if not VerifSauve then exit;
    action := caFree;
    Fvaleurs.perform(WM_REG_MAJ,MajVide,0);
    FgrapheVariab.perform(WM_REG_MAJ,MajVide,0);
    EcritCurrentUser;
    inherited;
end; // FormClose

procedure TFRegressiMain.OptionsItemClick(Sender: TObject);
var i : integer;
begin
     if OptionsDlg.showModal=mrOK then begin
        if OptionsDlg.modifPreferences then MruItemUpdate;
        if Fvaleurs=nil then exit;
        for i := 0 to pred(NbreGrandeurs) do with grandeurs[i]
            do if formatU=fDefaut then precisionU := precision;
        Fvaleurs.MajGridVariab := true;
        if OptionsDlg.modifUniteSI
           then PostMessage(Fvaleurs.handle,WM_Reg_Calcul,CalculCompile,1)
           else if OptionsDlg.modifDerivee then begin
                recalculE;
                EnvoieMessage(MajValeur);
           end;
        if OptionsDlg.modifPolice then EnvoieMessage(MajPolice);
        if OptionsDlg.modifGraphe then
           FgrapheVariab.Perform(WM_Reg_Maj,MajOptionsGraphe,0);
        if OptionsDlg.modifPreferences then begin
            EnvoieMessage(MajPreferences);
        end;
     end
end;

procedure TFRegressiMain.CollerPageItemClick(Sender: TObject);
begin
    FormDDE.AjoutePressePapier
end;

procedure TFRegressiMain.PageTrierItemClick(Sender: TObject);
var index : integer;
begin
     if suppressionDlg=nil then Application.CreateForm(TSuppressionDlg, SuppressionDlg);
     SuppressionDlg.operation := oTriPage;
     index := indexConst[0];
     if index=grandeurInconnue then exit;
     SuppressionDlg.nomDefaut := grandeurs[index].nom;
     if SuppressionDlg.showModal=mrOk then begin
        envoieMessage(MajChangePage);
        if Fvaleurs.Feuillets.ActivePage=Fvaleurs.ParamSheet then
           Fvaleurs.traceGridParam;
     end;
end;

procedure TFRegressiMain.PageCalculerItemClick(Sender: TObject);
begin
     PageCalcDlg := TPageCalcDlg.create(self);
     PageCalcDlg.showModal;
     PageCalcDlg.free;
end;

procedure TFRegressiMain.PageSelectItemClick(Sender: TObject);
begin
     if selectPageDlg=nil then Application.CreateForm(TselectPageDlg, selectPageDlg);
     SelectPageDlg.caption := stChoixPages;
     SelectPageDlg.appelPrint := false;
     SelectPageDlg.showModal;
end;

procedure TFRegressiMain.PageCopyItemClick(Sender: TObject);
begin
     PageCopyDlg := TPageCopyDlg.create(self);
     PageCopyDlg.showModal;
     PageCopyDlg.free;
end;

procedure TFRegressiMain.FilePrintItemClick(Sender: TObject);
begin
     if PrintDlg=nil
        then Application.CreateForm(TPrintDlg, PrintDlg);
     PrintDlg.showModal;
end;

procedure TFRegressiMain.PageGrouperItemClick(Sender: TObject);
begin
   if selectPageDlg=nil then Application.CreateForm(TselectPageDlg, selectPageDlg);
   SelectPageDlg.caption := stChoixPagesGr;
   SelectPageDlg.statusBar.SimpleText := stGroupeSuper;
   SelectPageDlg.statusBar.visible := true;
   if SelectPageDlg.showModal=mrOK then begin
      groupePage;
      modifFichier := true;
   end;
   SelectPageDlg.statusBar.visible := false;
end;

procedure TFRegressiMain.FileCalcItemClick(Sender: TObject);
var sauveFiltre : string;
begin
    sauveFiltre := OpenDialog.filter;
    OpenDialog.filter := 'Regressi |*.rw3|';
    OpenDialog.Title := stImportCalc;
    if openDialog.execute then
       LitCalcul(openDialog.FileName);
    OpenDialog.filter := sauveFiltre;
end;

procedure TFRegressiMain.RestaurerItemClick(Sender: TObject);
var S : tsauvegarde;
    SauveNom : string;
begin
   if not RestaurerItem.visible or (PileSauvegarde.count=0)  then begin
      Annuler1Click(sender);
      exit;
   end;
   S := PileSauvegarde.pop;
   S.restaure;
   case S.undo of
      UsupprPage : Perform(WM_Reg_Maj,MajAjoutPage,0);
      UsupprPoint : Perform(WM_Reg_Maj,MajAjoutValeur,0);
      UsupprConst : Perform(WM_Reg_Maj,MajGrandeur,0);
      UsupprVariab : Perform(WM_Reg_Maj,MajGrandeur,0);
      Ugrouper : begin
          closeAll;
          SauveNom := NomFichierData;
          FinOuvertureFichier(litFichierWin);
          NomFichierData := SauveNom;
          Perform(WM_Reg_Maj,MajAjoutPage,0);
      end;
   end;
   S.free;
end;

procedure TFRegressiMain.PrinterSetUpItemClick(Sender: TObject);
begin
   if PrintDlg=nil then
      Application.CreateForm(TPrintDlg, PrintDlg);
end;

procedure TFRegressiMain.ConstHeaderClick(Sender: TObject);
begin
    selParamDlg := TselParamDlg.create(self);
    selParamDlg.showModal;
    selParamDlg.free;
    AffValeurParametre;
end;

procedure TFRegressiMain.RecupItemClick(Sender: TObject);
begin
     grandeursOpen;
     grapheOpen;
     closeAll;
     NomFichierData := NomFichierSauvegarde;
     FinOuvertureFichier(litFichierWin);
     NomFichierData := '';
     modifFichier := true;
end;

procedure TFRegressiMain.RandomItemClick(Sender: TObject);
begin
  inherited;
  Fvaleurs.RandomBtnClick(sender);
end;

procedure TFRegressiMain.RazItemClick(Sender: TObject);
begin
    Fvaleurs.MajBtnClick(nil);
    FgrapheVariab.RaZModeleClick(nil);
end;

procedure TFRegressiMain.Rchantillonner1Click(Sender: TObject);
begin
     PageEchantillonDlg := TPageEchantillonDlg.create(self);
     PageEchantillonDlg.showModal;
     PageEchantillonDlg.free;
end;

procedure TFRegressiMain.EnregistreBtnClick(Sender: TObject);
begin
   FileSaveItemClick(Sender)
end;

procedure TFRegressiMain.PageNewSimulItemClick(Sender: TObject);
var i : integer;
begin
     if ajoutePage then begin
           for i := 1 to NbreConstExp do
                 Pages[NbrePages].valeurConst[i] := pages[pred(Nbrepages)].valeurConst[i];
           with Pages[NbrePages] do begin
                copyVecteur(valeurVar[0],pages[1].valeurVar[0]);
                nmes := pages[1].nmes;
                miniSimulation := pages[1].miniSimulation;
                maxiSimulation := pages[1].maxiSimulation;
                numero := NbrePages;
                recalculP;
           end;
           if NbreConstExp>0 then
                FValeurs.Feuillets.ActivePage := Fvaleurs.paramSheet;
           envoieMessage(MajAjoutPage);
           ModifFichier := true;
           if NbreConstExp>0 then TDINB.ShowFormInPage(FValeurs,indexImageValeurs);
     end;
end;

procedure TFRegressiMain.Annuler1Click(Sender: TObject);
begin
   if Screen.ActiveControl is TCustomEdit
      then EditCtl := Screen.ActiveControl as TCustomEdit
      else if (Screen.ActiveControl is TCustomGrid)
           then ActiveGrid := Screen.ActiveControl as TstringGrid;
   if Assigned(EditCtl) then EditCtl.Undo
end;

procedure TFRegressiMain.PageAddBtnClick(Sender: TObject);
begin
   PageAddClick(Sender);
end;

procedure TFRegressiMain.FormActivate(Sender: TObject);
begin
  inherited;
  MruItemUpdate; // Update MRU menu items
end;

end.




