function main_identification(obj,evnt)
%main_identification Pilot the task PARAMETRIC IDENTIFICATION
% INPUT
% 'obj' and 'evnt' are ignored, except in the non-interactive mode, i.e
% when a series of tests is run in non-interactive mode.
% In this case, 'evnt' is the name of a file which contains the results
% of a previous execution.
%% ======================================================
global input_error;
input_error=[];
% input_error: fieldnames of  input_error will be equal to the tag property
% of the uicontrol where an error has been found by the function
% control_saisie


bgcolor = [0.95 0.95 0.95 ];
h=figure('units','normalized',...
    'color',[1 1 1],...
    'position',[.1 .1 .8 .8],...
    'menubar','none',...
    'numbertitle','off',...
    'resize','off',...
    'tag','interface',...
    'keypressfcn',@raccourci_clavier);

 
if nargin ==0
    % mode interactif
    set(h,    'CloseRequestFcn',@my_closereq);
    set(h, 'userdata', {'parameters identification', '1'});
else
    set(h,    'CloseRequestFcn',@batch_closereq);
end

% full size figure
maximize
% figure title
set(h, 'Name', sprintf('FILTREX: PARAMETRIC IDENTIFICATION'));


%% menus of the top bar
% To center the menu above hpanel_control
for i=1:3
    uimenu(  'Label','      ');    
end

% Model choice
% Note: si on utilise HTML pour mettre en gras le label de l'item du menu,
% quand on clique sur l'item, l'inversion des couleurs du label
% ne se fait pas: le label apparait en noir sur fond bleu 
% et on ne le voit pas. Il faut choisir alors une foregroundcolor qui
% se voit a la fois sur le fond gris (item pas cliqué) et bleu (item
% choisi) mais ces couleurs  dépendent du système!
% edit = uimenu(  'Label','<html><b>Dynamics</b></html>', ...
%     'ForeGroundColor', 'w');

edit = uimenu(  'Label','Dynamics');

% Note: on ne laisse pas le choix du noyau a l'utilisateur car le noyau Picard a revoir
% config=uimenu(edit,'Label','Configuration');
% uimenu(config,'Label','Redistribution',...
%     'callback',@confuguration,...
%     'tag','redistribution');
% uimenu(config,'Label','Noyau Picard','Separator','on',...
%     'callback',@confuguration,...
%     'tag','nlaplacien');
uimenu(edit,'Label','Model equation',...
    'Accelerator','D',...
    'userdata', 'c', ...
    'Callback',@dynamique)
uimenu(edit,'Label','Fix/unfix parameters',...
    'tag','dynamique_tag',...
    'visible','off');
uimenu(edit,'Label','Set parameters to the maximal range', ...
    'tag', 'plagesmax_tag', ...
    'Callback',@plagesmax_mod, ...
    'visible','off');
uimenu(edit, 'Label', 'Set parameters to default values', ...
       'visible','off', ...
       'tag', 'resetmod_tag', ...
    'Callback',@reinit_mod);
uimenu(edit,'Label','Help about model equations', ...
   'Separator','on',...
   'Callback',@help_dynamics);

% Observations dataset choice
uimenu('Label','Data',...
    'Interruptible','off',...
    'Accelerator','O',...
    'Callback',@openfichier);


% Reinitialisation
raz = uimenu('Label','Reset to default values');
uimenu(raz, 'Label', 'Observation model parameters', ...
    'Callback',@reinit_modobs );
uimenu(raz, 'Label', 'Filter parameters', ...
       'tag', 'resetdparam_tag', ...
       'Visible', 'off', ...
    'Callback',@reinit_filtre);
uimenu(raz, 'Label', 'Dynamics parameters', ...
    'Callback',@reinit_mod);
uimenu(raz, 'Label', 'All', ...
    'Accelerator','Z',...
    'Callback',@reinitialiser);

% Save/Restore
uimenu('Label','Save project',...
    'Interruptible','off',...
    'Accelerator','S',...
    'userdata', {0}, ...
    'tag', 'sauver_modele_tag', ...
    'Callback',@sauver_modele);
uimenu('Label','Restore project',...
    'Interruptible','off',...
    'Accelerator','R',...
    'Callback',@restore);

% Infos
helpm=uimenu('Label','Help');
uimenu(helpm, 'Label','Pratical Tips',...
    'Callback',@filtrexhelp,...
    'Accelerator','H');
uimenu(helpm, 'Label','Help about model equations', ...
   'Separator','on',...
   'Callback',@help_dynamics);


uimenu('Label','About',...
    'callback',@about);

% Menus to quit
uimenu('Label','Return to menu',...
    'Interruptible','off',...
    'userdata', {'' '2'}, ...
    'Callback',@my_closereq, ...
    'Separator','on');
uimenu('Label','Quit task',...
    'Interruptible','off',...
    'userdata', {'' '1'}, ...
    'Callback',@my_closereq, ...
    'Separator','on');
uimenu('Label','Quit FILTREX',...
    'Interruptible','off',...
    'Callback','delete(gcf)',...
    'Separator','on');
uimenu('Label','Quit Matlab',...
    'Interruptible','off',...
    'BusyAction','cancel',...
    'Callback','exit',...
    'Separator','on',...
    'Accelerator','Q');
%% End of topbar menus


%%  hpanel_control: input panel
hpanel_control=uipanel('FontSize',30,...
    'borderWidth',3,...
    'Position',[.05 .05 0.4 .92]);
% hpanel_work: result panel
hpanel_work=uipanel('FontSize',30,...
    'borderWidth',3,...
    'BackgroundColor',[1 1 1],...
    'Position',[.45 .05 0.5 .92]);

% Split hpanel_control into different parts
groupebutton2 = uibuttongroup('Parent',hpanel_control,...
    'backgroundcolor',bgcolor,...
    'Position',[0 .5 1 .5]);
groupebutton_obs = uibuttongroup('Parent',groupebutton2,...
    'Position',[0 .9 .4 .10]);
groupebutton_filtre = uibuttongroup('Parent',groupebutton2,...
    'Position',[.4 .9 .6 .10]);
uicontrol('parent',groupebutton_obs,...
    'units','normalized',...
    'fontsize',10,...
    'foregroundcolor',[.3 .1 .5],...
    'backgroundcolor',bgcolor,...
    'position',[0 0 1 1],...
    'style','text',...
    'string',{'','OBSERVATION MODEL PARAMETERS',' '});
uicontrol('parent',groupebutton_filtre,...
    'units','normalized',...
    'fontsize',10,...
    'foregroundcolor',[.4 0 .2],...
    'backgroundcolor',bgcolor,...
    'position',[0 0 1 1],...
    'style','text',...
    'backgroundcolor',bgcolor,...
    'string',{' ','FILTER PARAMETERS',' '});

%% Input panels relative to the observations model
groupebutton21 = uibuttongroup('Parent',groupebutton2,...
    'backgroundcolor',bgcolor,...
    'Position',[0 .47 .25 .43]);
uicontrol('parent',groupebutton21,...
    'backgroundcolor',bgcolor,...
    'units','normalized',...
    'position',[0 0 1 1],...
    'style','text');
groupebutton22 = uibuttongroup('Parent',groupebutton2,...
    'backgroundcolor',bgcolor,...
    'Position',[.25 .47 .15 .43]);
uicontrol('parent',groupebutton22,...
    'backgroundcolor',bgcolor,...
    'units','normalized',...
    'position',[0 0 1 1],...
    'style','text');

groupebutton221 = uibuttongroup('Parent',groupebutton2,...
    'Position',[0.15 .47 .25 .11]);

uicontrol('parent',groupebutton221,...
    'units','normalized',...
    'foregroundcolor',[.3 .1 .5],...
    'position',[0 0 1 1],...
    'backgroundcolor',bgcolor,...
    'style','checkbox',...
    'tag','cvinparam_tag',...
    'callback',@modifier_estimer_CVs,...
    'string', '     Estimate CV');

%% Input panels relative to the filter parameters
groupebutton23 = uibuttongroup('Parent',groupebutton2,...
    'Position',[.4 .47 .4 .43]);
uicontrol('parent',groupebutton23,...
    'units','normalized',...
    'position',[0 0 1 1],...
    'backgroundcolor',bgcolor,...
    'style','text');
groupebutton24 = uibuttongroup('Parent',groupebutton2,...
    'Position',[.8 .47 .2 .43]);
uicontrol('parent',groupebutton24,...
    'units','normalized',...
    'backgroundcolor',bgcolor,...
    'position',[0 0 1 1],...
    'style','text');

% Parametres link to time
groupebutton= uibuttongroup('Parent',groupebutton2,...
    'backgroundcolor',bgcolor,...
    'Position',[0 .345 1 .13]);
groupebuttontime= uibuttongroup('Parent',groupebutton,...
    'backgroundcolor',bgcolor,...
    'Position',[0 0 1 1]);
%% Panel where to ask stability study and histogramms plots
groupebuttonsh=  uibuttongroup('Parent',groupebutton2,...
    'Position',[0 0.24 1 .11],...
    'backgroundcolor',bgcolor);

uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
    'position',[.38 0.05 .1 0.95],...
    'FontSize', 8, ...
    'backgroundcolor',bgcolor,...
    'style','checkbox',...
    'tag','etude_stab_tag',...
    'callback',@etude_stabilite,...
    'string','STATISTICAL CI');
uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
  'FontSize', 8, ...
    'position',[0.25 0.05 .24 0.95],...
    'backgroundcolor',bgcolor,...
    'tag','hist_txt_tag',...
    'style', 'text', ...
    'string',{'','NUMBER OF HISTOGRAMS'}, ...
    'visible','off');
uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
    'position',[0.05 0.05 .29 0.95],...
    'FontSize', 8, ...
    'backgroundcolor',bgcolor,...
    'style','checkbox',...
    'tag','hist_tag',...
    'callback',@set_nbhisto,...
    'string','HISTOGRAMS');
% When the above box "histograms" is selected, it is shifted on the left
% to make the box "number of histograms" appear. 
% The below box "histograms" is the left shifted one.
uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
    'position',[.05 0.05 .2 0.95],...
    'FontSize', 8, ...
    'backgroundcolor',bgcolor,...
    'style','checkbox',...
    'tag','hist2_tag',...
    'callback',@maj_nbhisto,...
    'string','HISTOGRAMS',...
    'visible','off');
uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
    'position',[.485 .2 .15 .6],...
    'backgroundcolor','w',...
    'tag','hist_edit_tag',...
    'fontAngle', 'Italic', ...
    'callback',@control_saisie_an,...
    'interruptible','off',...
	  'userdata',{{'1','20', 'ALL'},'HISTOGRAMS'},...
    'style','edit',...
    'visible','off');
%% Panels when stability study (CI)
uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
	  'fontSize', 8, ...
    'foregroundcolor',[0 0 0],...
    'position',[.25 0.05 .15 0.95],...
    'backgroundcolor',bgcolor,...
    'tag','level_stab_txt_tag',...
    'style', 'text', ...
    'string',{'','CI LEVEL'},...
    'visible','off');
uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
    'position',[ 0.4 0 .15 1],...
    'backgroundcolor','w',...
    'tag','level_stab_edit_tag',...
    'Min', 1,  'Max', 1,...
    'String', '     90% |     95% |     99% ',...
    'Value', 2 , ...
    'style','listbox', ...
    'visible','off');

uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
	  'fontSize', 8, ...
    'foregroundcolor',[0 0 0],...
    'position',[.64 0.05 .165 0.95],...
    'backgroundcolor',bgcolor,...
    'tag','stab_txt_tag',...
    'style', 'text', ...
    'string',{'','NUMBER OF DYNAMICS'},...
    'visible','off');
% Bouton help pour les windows
help_icon = imread('SRC/IMG/help.jpg', 'jpg');

        % rajouter l'icone d'aide
        uicontrol('parent',groupebuttonsh,...
            'units', 'normalized', ...
            'style', 'pushbutton', ...
            'position',[0.79 0.32 0.016 0.4],...
            'backgroundcolor',bgcolor,...
            'cdata', help_icon, ...
            'enable', 'inactive', ...
		  'Visible', 'off', ...
		  'tag', 'help_numberofdyn_tag', ...
            'ButtonDownFcn', @help_numberofdyn);
        

uicontrol('parent',groupebuttonsh,...
    'units','normalized',...
    'position',[.825 .2 .15 .63],...
    'backgroundcolor','w',...
    'tag','stab_edit_tag',...
    'callback',@control_saisie,...
    'interruptible','off',...
	  'userdata',{ {'2','10000'},'NUMBER OF DYNAMICS'},...
    'style','edit',...
    'visible','off');


%% Parameters relative to the observations dataset file or restored file
groupebuttonfic= uibuttongroup('Parent',groupebutton2,...
    'backgroundcolor',bgcolor,...
    'Position',[0 0.13 1 .115]);

uicontrol('parent',groupebuttonfic,...
    'units','normalized',...
    'fontsize',10,...
    'position',[0 0 1 1],...
    'backgroundcolor',bgcolor,...
    'style','edit',...
    'tag', 'fichier_type_tag', ...
    'string','NO DATA');

% Name of the observations dataset file
fichier_chemin_tag= uicontrol('parent',groupebuttonfic,...
    'units','normalized',...
    'position',[0 0.05 1 0.95],...
    'FontSize', 10, ...
    'style','text',...
    'tag','fichier_chemin_tag',...
    'backgroundcolor',bgcolor,...
    'visible', 'off');

% Characteristics of the observations dataset
uicontrol('parent',groupebuttonfic,...
    'units','normalized',...
    'position',[0 0 1 0.5],...
    'FontSize', 10, ...
    'style','text',...
    'tag','fichier_descr_tag',...
    'backgroundcolor',bgcolor,...
    'visible', 'off');

% Icon by which observations dataset plot is required
chart_line_icon=imread('SRC/IMG/chart_line.jpg', 'jpg');
uicontrol('parent',groupebutton2,...
    'units','normalized',...
    'position',[0.94 0.15 0.03  .06],...
    'style','pushbutton', ...
    'tag','plotdata_tag', ...
    'visible', 'off', ...
    'enable', 'inactive', ...
    'cdata', chart_line_icon, ...
    'ButtonDownFcn', @plot_obs);

%% To model display
groupebutton3 = uibuttongroup('Parent',hpanel_control,...
    'Position',[0 0 1 .57],...
    'backgroundcolor','w',...
    'tag','groupebutton3_tag');
uicontrol('parent',groupebutton3,...
    'units','normalized',...
    'fontsize',15,...
    'position',[0 0 1 1],...
    'style','text',...
    'backgroundcolor','w',...
    'foregroundcolor',[0 0 0],...
    'tag','modele_tag');

uibuttongroup('Parent',groupebutton3,...
    'Position',[.15 0 .25 .8],...
    'backgroundcolor','w',...
    'tag','groupebutton30_tag');
uicontrol('parent',groupebutton3,...
    'units','normalized',...
    'fontsize',10,...
    'position',[.37 .8 .12 .05],...
    'backgroundcolor',[1 1 1],...
    'foregroundcolor','k',...
    'style','text',...
    'string','MIN',...
    'tag','min_tag',...
    'visible','off');
uibuttongroup('Parent',groupebutton3,...
    'Position',[.35 0 .15 .8],...
    'tag','groupebutton31_tag');
uicontrol('parent',groupebutton3,...
    'units','normalized',...
    'fontsize',10,...
    'position',[.5 .8 .12 .05],...
    'style','text',...
    'backgroundcolor',[1 1 1],...
    'foregroundcolor','k',...
    'string','MAX',...
    'tag','max_tag',...
    'visible','off');
uibuttongroup('Parent',groupebutton3,...
    'Position',[.5 0 .15 .8],...
    'tag','groupebutton32_tag');
% Note:dans cette version, le bruit est non visible: il est fixé a la valeur par défaut
% On garde les uicontrol au cas ou on voudrait le remettre
uicontrol('parent',groupebutton3,...
    'units','normalized',...
    'fontsize',10,...
    'position',[.6 .8 .15 .05],...
    'style','text',...
    'backgroundcolor',[1 1 1],...
    'foregroundcolor','k',...
    'string','NOISE TYPE',...
    'tag','bruit_tag',...
    'visible','off');
uibuttongroup('Parent',groupebutton3,...
    'Position',[.6 0 .15 .8],...
    'tag','groupebutton33_tag');


%%  GO button
hgo=uicontrol('parent',hpanel_control,...
    'units','normalized',...
    'position',[ 0.92 0 0.08 0.05],...
    'FontUnits', 'normalized', ...
    'FontSize', 0.3, ...
    'interruptible','on',...
    'backgroundcolor','r',...
    'BusyAction','cancel',...
    'tag','estimation_tag',...
    'Style','pushbutton',...
    'String','GO',...
    'userdata',0,...
    'callback',@ESTIMATION);



data = init_estimation(groupebutton21,groupebutton22,...
    groupebutton23,groupebutton24,  groupebuttontime, bgcolor);

data.fichier_chemin_tag=fichier_chemin_tag; % Matlab2013a 29/1/14


%% save the graphical components of the panels
handles=guihandles(1);
% concatenation of the structures handles and data
data=catstruct(handles,data);
% save the results panel
data.hpanel_work=hpanel_work;
% uptodate the main structure: data
guidata(1,data);



%% Noninteractive case: load a backup file to make it run again

if nargin>0
    restore(obj,evnt);
    % Launch execution of a test
    ESTIMATION(hgo,1);
end

end % end main_identification
%% =================================================
function ESTIMATION(obj,evnt)
%ESTIMATION  Calculations manager (called when hit on GO) 
% INPUT
% The property "userdata" of obj is equal to 1 when execution should be stopped
%  and 0 when execution should be started.
% evnt is equal to 1 in noninteractive mode, i.e when a series of tests
% is being executing.
%% ======================================================

% Input check
if verif_input(obj)==1
    return
end


% Get the main structure: data
data=guidata(1);


% Set property "Pointer" of the figure to busy state
Busy(1)
% Change the GO/STOP button
if get(obj,'userdata')
    set(obj,'interruptible','off','userdata',0)
    return
else
    set(obj,'interruptible','on','userdata',1,'string','STOP')
end


% Uptodate the graphical changes
drawnow


% Delete the possible sons of the input panel hpanel_work
delete(get(data.hpanel_work,'children'))

%% Get input from the input panel hpanel_work

%% Check there is a number of dynamics when CI are required
if get(data.etude_stab_tag,'value')
    data.nombre_dynamique=str2double(get(data.stab_edit_tag,'string'));
    if isnan(data.nombre_dynamique)
        errordlg(...
            'When statistical confidence intervals are required, you have to enter a number of dynamics', 'BAD INPUT');
        %set(data.etude_stab_tag,'value',0)
        set(obj,'interruptible','on','userdata',0,'string','GO')
        Idle(1)
        return
    end
    
    % Note: pas besoin de verifier s'il y a un niveau de confiance (c'est un list button)
    data.level_stab= get(data.level_stab_edit_tag,'value');
    
else
    data.nombre_dynamique=1;
end

%% Get the other inputs
try
    [data, tobs, deltaT, bruitetat,Fnoyau,Fpert, iclevel, ...
        tracehistogramme, nbparticules,...
        graineAlea] = recup_interface( data, evnt, 1);
catch
    % some input are missing or invalid
    %errordlg('Des entrées manquent ou sont mauvaises');
    set(obj,'interruptible','on','userdata',0,'string','GO')
    Idle(1)
    return
end



%% Store the program which calculates the model
% strip the possible blank characters inside the model name
lemodele = strrep(data.modelepop,' ', '');
% strip the possible dashes inside the model name
lemodele = strrep(lemodele,'-', '');
modelepop= eval(['@' lemodele]);
nomparam=data.nomparam;
yobs=data.yobs;
logNbestime=data.logNbestime;
paramobs=data.paramobs;
nmoda=NaN; % to store, possibly, the parameters "mod"

%% To store panels numerotation 
data.com_tab_tag = uicontrol('parent',data.hpanel_work,...
    'units','normalized',...
    'foregroundcolor','k',...
    'backgroundcolor',[1 1 1],...
    'position',[0 0  1 .02],...
    'tag','com_tab_tag',...
    'style','text');
%% Change the background color of the input panel: hpanel_work
set(data.hpanel_work,'backgroundcolor',[1 1 1])

%% Create a progressing bar
    ssize=get(0,'screensize');
    jPb = javax.swing.JProgressBar;
    %9/1/2012    set(jPb,'StringPainted','on','Value',0,'Indeterminate','off');
    jPb.setIndeterminate(false);
    %9/1/2012    jPb.setStringpainted(true);
    hPb= javacomponent(jPb,[2*ssize(3)/4 4*ssize(4)/9 ssize(3)/3 ssize(4)/9],gcf);
    data.hPb=hPb;

%% Uptodate the main structure: data
indice_panel=0;
data.indice_panel=indice_panel;

handles=guihandles;
ndata=catstruct(data,handles);
guidata(gcf,ndata);
nbrep=1;


%% random seed
try
    RandStream.setGlobalStream(RandStream('mt19937ar','seed',graineAlea)); % version 2012a matlab
catch
    try
        RandStream.setDefaultStream(RandStream('mt19937ar','seed',graineAlea)); % version 2008b-2011b matlab
    catch
        rand(graineAlea);% Matlab previous versions
    end
end

%% Prepare filter routine arguments
vobs=0:deltaT:tobs(end); % computational times
vobs_or=convert_obs(vobs, data); % convert in the genuine time unit
nmod=0; % here, one model only. Its index ignored.

%% Determination of the required histograms
if tracehistogramme
    [nbhisto_tot nbhisto_deb nbhisto_fin]= ...
        cptehisto(tobs, data);
else
    nbhisto_deb=0;
    nbhisto_fin= 0;
    nbhisto_tot=0;
    
end %fin if tracehistogramme

%% CI level
switch iclevel
    case 1
        % 90%
        level=90;
    case 2
        level=95;
    case 3
        level=99;
end
icbinf=(1-level/100)/2; 
icbsup= 1-icbinf;

%% estimation=filtering
Moyenne={};
while nbrep<=data.nombre_dynamique
    try
        
        [Moyenne,ET,ICInf,ICSup, nmoda, indice_panel, ignore, structHisto]=filtre_particulaire(modelepop,...
            @y_theorique,paramobs,yobs,nbparticules,tobs,...
            vobs,  vobs_or, deltaT,  ...
            data.ajoutbruit,...
            bruitetat,Fnoyau,Fpert, icbinf, icbsup, ...
            indice_panel, nbrep, ...
            nmod, data.nomparam,data.nomparamS, data, lemodele, ...
            tracehistogramme,  nbhisto_tot, nbhisto_deb,nbhisto_fin);
        
        
        % User interruption?
        if  (get(obj,'userdata')==0) || isempty(Moyenne)
            break
        end;
        
        nbparammodel=size(Moyenne,1)-1;
        paramfin=[Moyenne(1:nbparammodel,end);0];
        
        % Store estimated values of the parameters        
        RESULTAT{nbrep}=paramfin(1:nbparammodel);
        
        nbrep=nbrep+1;
    catch err
        %DEBUG         err.identifier
          %DEBUG            err.message
        if ~ishandle(obj)% interruption via a button quit
            return
        end
        if get(obj,'userdata')==0
            break;% interruption via button STOP
        end;
        
        % Change GO/STOP button and change seed value
        set(obj,'backgroundcolor','r')
        drawnow
        
        graineAlea=graineAlea+nbrep;
        try
            RandStream.setGlobalStream(RandStream('mt19937ar','seed',graineAlea));% version 2012a matlab
        catch
            try
                RandStream.setDefaultStream(RandStream('mt19937ar','seed',graineAlea));% version 2008b-2011b matlab
            catch
                rand('state', graineAlea);% Matlab previous versions
            end
        end
    end
    
end

%% Have we succeeded?
if isempty(Moyenne)
    set(obj, 'userdata', 0)
end
% erase the progression bar if it exists
    try
        delete(data.hPb);
    end
    

if get(obj,'userdata') ~=0
    % In case of no fail nor interruption
%% Results display    
    data=guidata(gcf);
   
        if exist( 'structHisto', 'var') && ~isempty(structHisto)
            % il y a des histogrammes
          for ihisto=1:length(structHisto)
           [indice_panel, data] = histofiltre(indice_panel, '', data, ...
               nbparammodel, data.nomparam, ...
               structHisto{ihisto}{1}, structHisto{ihisto}{2});
         end
            
        end
   
    
    
    if ~get(data.etude_stab_tag,'value')
        % No stability study
        indice_panel= indice_panel+1;
        tag=['panel' num2str(indice_panel) '_tag'];
        data=plot_evolution_para(tag, data, ...
            nbparammodel, nomparam, ...
            vobs_or,Moyenne,ICInf,  ICSup, ...
            nbparticules);
        
        
        temps= data.tobs; % les temps lus
        
        pop=zeros(1,length(temps));
        for i=1:length(temps)
            t=temps(i);
            tempo=modelepop(paramfin,t,0,  ...
                data.nomparam, data.nomparamS, data);
            pop(i)=tempo(end);
        end
        
        
        indice_panel=indice_panel+1;
        tag=['panel' num2str(indice_panel) '_tag'];
        data=plot_dyn_obs(tag, data, ...
			  temps, vobs_or, pop, ...
             logNbestime, Moyenne, ...
            ICInf, ICSup);
        
        
        set(data.com_tab_tag,'visible','off')
        indice_panel=indice_panel+1;
        tag=['panel' num2str(indice_panel) '_tag'];
        data=ecrire_result(tag, data, ...
            nbparammodel, nomparam, paramfin, nmoda);
        
        data=put_indices_panels(data, indice_panel, data.hpanel_work);
    else
        % Stability study (CI)
        data=etudestab(data.nombre_dynamique, indice_panel, nbparammodel, ...
            nomparam, RESULTAT);
    end %end  Stability study
    
    %% Store the mean and mod of the estimated values of the parameters
    data.paramfin = paramfin;
    data.nmoda= nmoda;
    %% Store the calculation times in the data unit
    data.vobs_or = vobs_or;
    
end % end else (no interruption)


%% Store the  histograms into the property userdata of sauver_modele_tag
if tracehistogramme || isfield(data, 'AC')
    p=get(data.sauver_modele_tag, 'userdata');
    if tracehistogramme
        p{2}=structHisto;
   end
   if isfield(data, 'AC') % histograms when Stability study
      p{3}=data.AC;
   end
   set(data.sauver_modele_tag, 'userdata', p);
end


handles=guihandles;
ndata=catstruct(data,handles);
guidata(gcf,ndata)

%% If you want to put himself on the first panel
%for i=1:(indice_panel - 1)
%    retrancher_tab();
%end
set(obj,'interruptible','on','userdata',0,'backgroundcolor','r','string','GO')
drawnow
Idle(1)

end % end ESTIMATION
%% =================================================

function raccourci_clavier(~,evnt)
%raccourci_clavier Launch calculation when the user hits on Return  key
%% ======================================================

if strcmpi(evnt.Key,'return')
    ESTIMATION()
end
end % end raccourci_clavier
%% ======================================================

function dynamique(~,~)
%dynamique Model dynamics choice
% INPUT
% input arguments are ignored
%% ======================================================
global input_error;

data=guidata(gcf);
Basemodeles=init_Basemodeles();
data.Basemodeles=Basemodeles;

str=data.Basemodeles.nom;
[s,v] = listdlg('PromptString','Select model:',...
    'ListSize',[200 350],...
    'SelectionMode','single',...
    'ListString',str);

guidata(1,data);
if v
    input_error=[];
    CVs=data.CVs;
    for c=1:length(CVs.nomparamS)
        var=[CVs.nomparamS{c},'_tag'];
        set(data.(var),'enable','on');
    end
    % Cancel the possible previous CVs estimation
    if get(data.cvinparam_tag, 'value')==1
        set(data.cvinparam_tag, 'value', 0);
        hd=uicontrol('visible', 'off', ...
            'value', 0);
        modifier_estimer_CVs(hd);
        data=guidata(1);
    end
 
    
    %% Display the model with its default values
    
    trace_modele(s);

    
    delete(get(data.dynamique_tag,'children'))
    Basemodeles=data.Basemodeles;
    data.modelepop=Basemodeles.nom{s};
    nomparamP=data.Basemodeles.nomparamP{s};
    
    
    for i=1:length(nomparamP)
        uimenu(data.dynamique_tag, ...
	       'Label',traduc_nom(nomparamP{i}),...
            'userdata',{nomparamP{i}}, ...
            'callback',@gestion_parametres,...
            'checked','on');
        
    end
    set(data.dynamique_tag,'visible','on')
    set(data.plagesmax_tag, 'visible','on')
    set(data.resetmod_tag, 'visible','on')
    set(data.resetdparam_tag, 'visible','on')
end
end % end dynamique
%% ======================================================
function [nbhisto_tot nbhisto_deb nbhisto_fin]= ...
    cptehisto(tobs, data)
%cptehisto Count the number of histograms, nbhisto_tot, which will be
% plotted for each parameter:
% They are as many histograms as observations times, and we know that there
% is a computatinal time at each observations time.
nbhisto_tot=length(tobs);

% Get the number of required histograms
try
    nombre_histogramme=eval(get(data.hist_edit_tag,'string'));
    % we cannot asked more histograms than there are
    nombre_histogramme= min( nbhisto_tot, nombre_histogramme);
catch
    nombre_histogramme=nbhisto_tot; % all are required
end % try

% We limit the number of histograms pages to 20
nombre_histogramme= min(20, nombre_histogramme);

if (nombre_histogramme== nbhisto_tot)
    % all histograms are required
    nbhisto_deb= 1; % number of histograms at the beginning
    nbhisto_fin= nbhisto_tot-1;% number of histograms at the end
else
    % 80%=4/5 of histograms at the beginning
    nbhisto_deb= idivide(int32(nombre_histogramme*4),int32(5));
    % 20%=1/5  of histograms at the end, with at least one
    nbhisto_fin= max(idivide(int32(nombre_histogramme), int32(5)), 1);
end
end % end cptehisto

%% ======================================================
