Index: /trunk/src/check_files.m
===================================================================
--- /trunk/src/check_files.m	(revision 597)
+++ /trunk/src/check_files.m	(revision 598)
@@ -117,5 +117,4 @@
     'view_field.m';...% function for visualisation of projected fields'
     'view_field.fig';...%GUI for view_field
-    'write_plot_param';...%update plotting parameters after plot, TODO: change into a general function: fill_GUI
     'xml2struct';...% read an xml file as a Matlab structure, converts numeric character strings into numbers
     };
Index: /trunk/src/editxml.m
===================================================================
--- /trunk/src/editxml.m	(revision 597)
+++ /trunk/src/editxml.m	(revision 598)
@@ -345,16 +345,17 @@
         xs=xmltree(schemafile);
     else
-        msgbox_uvmat('WARNING','The xml schema is not found, check the file PARAM.xml')
-        [FileName, PathName]=uigetfile( ...
-            {'*.xsd', '(*.xsd)';
-            '*.xsd',  '.xsd files '; ...
-            '*.*',  'All Files (*.*)'}, ...
-            'Pick a .xsd schema' ,schemafile); %file browser
-        if ischar(PathName) && ischar(FileName) && exist(fullfile(PathName,FileName),'file')
-            DataIn.Schema=fullfile(PathName,FileName);
-            xs=xmltree(DataIn.Schema);%open the associated schema file
-        else
+%         msgbox_uvmat('WARNING','The xml schema is not found, check the file PARAM.xml')
+%         [FileName, PathName]=uigetfile( ...
+%             {'*.xsd', '(*.xsd)';
+%             '*.xsd',  '.xsd files '; ...
+%             '*.*',  'All Files (*.*)'}, ...
+%             'Pick a .xsd schema' ,schemafile); %file browser
+%         if ischar(PathName) && ischar(FileName) && exist(fullfile(PathName,FileName),'file')
+%             DataIn.Schema=fullfile(PathName,FileName);
+%             xs=xmltree(DataIn.Schema);%open the associated schema file
+%         else
             xs=[];
-        end
+% 
+
     end
     %         end
Index: /trunk/src/fill_GUI.m
===================================================================
--- /trunk/src/fill_GUI.m	(revision 597)
+++ /trunk/src/fill_GUI.m	(revision 598)
@@ -14,5 +14,9 @@
 %------------------------------------------------------------------------
 errormsg='';
-handles=guidata(GUI_handle); 
+%handles=guidata(GUI_handle); 
+            children=get(GUI_handle,'children');
+            for ichild=1:numel(children)
+                handles.(get(children(ichild),'tag'))=children(ichild);
+            end
 UserData=get(GUI_handle,'UserData');
 fields=fieldnames(Param);%list of fields in Param
Index: /trunk/src/series.m
===================================================================
--- /trunk/src/series.m	(revision 597)
+++ /trunk/src/series.m	(revision 598)
@@ -70,5 +70,5 @@
 set(hObject,'Units','pixels')
 set(handles.PairString,'ColumnName',{'pairs'})
-set(handles.PairString,'ColumnEditable',logical(0))
+set(handles.PairString,'ColumnEditable',false)
 set(handles.PairString,'ColumnFormat',{'char'})
 set(handles.PairString,'Data',{''})
@@ -84,7 +84,7 @@
 [path_series,name,ext]=fileparts(which('series'));% path to the GUI series
 path_series_fct=fullfile(path_series,'series');%path of the functions in subdirectroy 'series'
-path_bin=fullfile(path_series,'bin');%path of the binary functions (compiled)
+%path_bin=fullfile(path_series,'bin');%path of the binary functions (compiled)
 ActionPathList=regexprep(ActionList,'^.+$',path_series_fct);% set path=path_series to each function in the list ('^.+$'=any non empty nbre of char form beginning to end of char string)
-ActionPathList=[ActionPathList regexprep(ActionList,'^.+$',path_bin)];% set path to compiled functions
+ActionPathList=[ActionPathList ActionPathList];% set path to .sh commands for compiled functions
 ActionExtList={'.m';'.sh'};% default choice of extensions (Matlab fct .m or compiled version .sh)
 RunModeList={'local';'background'};% default choice of extensions (Matlab fct .m or compiled version .sh)
@@ -1366,5 +1366,5 @@
     if exist(xmlfile,'file')
         s=xml2struct(xmlfile);
-        if strcmp(RunMode,'cluster') && isfield(s,'BatchParam')
+        if strcmp(RunMode,'cluster_oar') && isfield(s,'BatchParam')
             if isfield(s.BatchParam,'RunTime')
                 RunTime=s.BatchParam.RunTime;
@@ -1382,9 +1382,9 @@
         end
     end
-    if isempty(RunTime) && strcmp(RunMode,'cluster')
+    if isempty(RunTime) && strcmp(RunMode,'cluster_oar')
         msgbox_uvmat('ERROR','RunTime name not found in PARAM.xml, compiled version .sh cannot run on cluster')
         return
     end
-    Series.RunTime=RunTime;
+%     Series.RunTime=RunTime;
 end
 
@@ -1442,5 +1442,8 @@
         if isempty(Series.IndexRange.NbSlice)
             Series.IndexRange.first_i=first_i+(iprocess-1)*BlockLength;
-            Series.IndexRange.last_i=first_i+(iprocess)*BlockLength-1;
+            if Series.IndexRange.first_i>last_i
+                break
+            end
+            Series.IndexRange.last_i=min(first_i+(iprocess)*BlockLength-1,last_i);
         else
             Series.IndexRange.first_i= first_i+iprocess-1;
@@ -1459,7 +1462,7 @@
                     case {'PCWIN','PCWIN64'} %Windows system
                         filexml=regexprep(filexml,'\\','\\\\');% add '\' so that '\' are left as characters
-                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' Series.RunTime ' ' filexml]);% TODO: adapt to DOS system
+                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);% TODO: adapt to DOS system
                     case {'GLNX86','GLNXA64','MACI64'}%Linux  system
-                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' Series.RunTime ' ' filexml]);
+                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);
                 end
         end
@@ -1492,5 +1495,9 @@
         if isempty(Series.IndexRange.NbSlice)% process by blocks of i index
             Series.IndexRange.first_i=first_i+(iprocess-1)*BlockLength;
-            Series.IndexRange.last_i=first_i+(iprocess)*BlockLength-1;
+            if Series.IndexRange.first_i>last_i
+                NbProcess=iprocess-1;
+                break% leave the loop, we are at the end of the calculation
+            end
+            Series.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength-1);
         else% process by slices of i index if NbSlice is defined, computation in a single process if NbSlice =1
             Series.IndexRange.first_i= first_i+iprocess-1;
@@ -1506,6 +1513,8 @@
         
         %create the executable file
-        filebat=fullfile_uvmat(DirBat,'',Series.InputTable{1,3},'.bat',OutputNomType,...
-            Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
+%         filebat=fullfile_uvmat(DirBat,'',Series.InputTable{1,3},'.bat',OutputNomType,...
+%             Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
+         filebat=fullfile_uvmat(DirBat,'',Series.InputTable{1,3},'.sh',OutputNomType,...
+           Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
         batch_file_list{iprocess}=filebat;
         [fid,message]=fopen(filebat,'w');% create the executable file
@@ -1551,5 +1560,5 @@
                             'hostname && date \n '...
                             'umask 002 \n'...
-                            fullfile(ActionPath,[ActionName '.sh']) ' ' Series.RunTime ' ' filexml];%allow writting access to created files for user group
+                            fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml];%allow writting access to created files for user group
                         fprintf(fid,cmd);%fill the executable file with the  char string cmd
                         fclose(fid);% close the executable file
@@ -1590,5 +1599,5 @@
         fid=fopen(filename_joblist,'w');
         for p=1:length(batch_file_list)
-            fprintf(fid,[batch_file_list{p} '\n']);% list of exe files (TODO: create them)
+            fprintf(fid,[batch_file_list{p} '\n']);% list of exe files 
         end
         fclose(fid);
@@ -1705,6 +1714,6 @@
 end
 Series.IndexRange=rmfield(Series.IndexRange,'TimeTable');
-Series.IndexRange=rmfield(Series.IndexRange,'MinIndex');
-Series.IndexRange=rmfield(Series.IndexRange,'MaxIndex');
+% Series.IndexRange=rmfield(Series.IndexRange,'MinIndex');
+% Series.IndexRange=rmfield(Series.IndexRange,'MaxIndex');
 empty_line=false(size(Series.InputTable,1),1);
 for iline=1:size(Series.InputTable,1)
@@ -1726,4 +1735,6 @@
     end
 end
+set(handles.ActionName,'BackgroundColor',[1 1 0])
+drawnow
 
 %% get Action name and path
@@ -1752,5 +1763,6 @@
     end
     [ActionPath,ActionName,ActionExt]=fileparts(FileName);
-    % insert the choice in the menu
+    
+    % insert the choice in the menu ActionName
     ActionIndex=find(strcmp(ActionName,ActionList),1);% look for the selected function in the menu Action
     if isempty(ActionIndex)%the input string does not exist in the menu
@@ -1759,34 +1771,34 @@
         set(handles.ActionName,'String',ActionList)
     end
-    %set(handles.ActionName,'Value',ActionIndex)
-    %list_path{ActionIndex}=PathName;
+    
+    % record the file extension and extend the path list if it is a new extension
+    ActionExtList=get(handles.ActionExt,'String');
+    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
+    if isempty(ActionExtIndex)
+        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
+        ActionExtIndex=numel(ActionExtList)+1;
+        ActionPathNew=cell(size(ActionPathList,1),1);%new column of ActionPath
+        ActionPathList=[ActionPathList ActionPathNew];
+    end
+    set(handles.ActionName,'UserData',ActionPathList);
+
     % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
     if length(ActionList)>nb_builtin_ACTION+5; %nb_builtin=nbre of functions always remaining in the initial menu
         nbremove=length(ActionList)-nb_builtin_ACTION-5;
         ActionList(nb_builtin_ACTION+1:end-5)=[];
-        ActionPathList(nb_builtin_ACTION+1:end-4)=[];
+        ActionPathList(nb_builtin_ACTION+1:end-4,:)=[];
         ActionIndex=ActionIndex-nbremove;
     end
+    
+    % record action menu, choice and path
     set(handles.ActionName,'Value',ActionIndex)
     set(handles.ActionName,'String',ActionList)
-    ActionPathList{ActionIndex}=PathName;
-    set(handles.ActionPath,'enable','inactive')% indicate that the current path is accessible (not 'off')
-    
-    % record the file extension and update the paths in userdata
-    ActionExtList=get(handles.ActionExt,'String');
-    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
-    if isempty(ActionExtIndex)
-        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
-        set(handles.ActionExt,'Value',numel(ActionExtList)+1)
-        ActionPathNew=cell(size(ActionPathList,1),1);%new column of ActionPath
-        ActionPathNew{ActionIndex}=ActionPath;
-        ActionPathList=[ActionPathList ActionPathNew];
-    end
-    set(handles.ActionName,'UserData',ActionPathList);
-    
-    %record the current menu in personal file profil_perso
+    set(handles.ActionExt,'Value',ActionExtIndex)
+    ActionPathList{ActionIndex,ActionExtIndex}=PathName;
+        
+    %record the user defined menu additions in personal file profil_perso
     dir_perso=prefdir;
     profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
-    if nb_builtin_ACTION+1<=length(ActionList)-1
+    if nb_builtin_ACTION+1<=numel(ActionList)-1
         ActionListUser=ActionList(nb_builtin_ACTION+1:numel(ActionList)-1);
         ActionPathListUser=ActionPathList(nb_builtin_ACTION+1:numel(ActionList)-1,:);
@@ -1811,9 +1823,9 @@
 
 %% default setting for the visibility of the GUI elements
-set(handles.FieldTransform,'Visible','off')
-set(handles.CheckObject,'Visible','off');
-set(handles.ProjObject,'Visible','off');
-set(handles.CheckMask,'Visible','off')
-set(handles.Mask,'Visible','off')
+% set(handles.FieldTransform,'Visible','off')
+% set(handles.CheckObject,'Visible','off');
+% set(handles.ProjObject,'Visible','off');
+% set(handles.CheckMask,'Visible','off')
+% set(handles.Mask,'Visible','off')
 
 %% create the function handle for Action
@@ -1834,6 +1846,6 @@
 end
 
-%% prepare the input param
-[Series,tild,errormsg]=prepare_jobs(handles);
+%% Activate the Action fct
+[Series,tild,errormsg]=prepare_jobs(handles);% read the parameters from the GUI series
 if ~isempty(errormsg)
     msgbox_uvmat('ERROR',errormsg)
@@ -1842,5 +1854,5 @@
 ParamOut=h_fun(Series);
 
-%% Put the first line of the selected Action fct as tootip help
+%% Put the first line of the selected Action fct as tooltip help
 try
     [fid,errormsg] =fopen([ActionName '.m']);
@@ -1849,8 +1861,4 @@
     set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
 end
-% if ~isequal(path_series,PathName)
-%     rmpath(PathName)
-% end
-Param_list={};
 
 %% Detect the types of input files
@@ -1998,9 +2006,13 @@
     set(handles.ActionInput,'Visible','on')
     set(handles.ActionInput_title,'Visible','on')
+    set(handles.ActionInputView,'Visible','on')
+    set(handles.ActionInputView,'Value',0)
     set(handles.ActionInput,'String',ActionName)
+    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
     SeriesData.ActionInput=ParamOut.ActionInput;
 else
     set(handles.ActionInput,'Visible','off')
     set(handles.ActionInput_title,'Visible','off')
+    set(handles.ActionInputView,'Visible','off')
     if isfield(SeriesData,'ActionInput')
     SeriesData=rmfield(SeriesData,'ActionInput');
@@ -2008,4 +2020,13 @@
 end   
 set(handles.series,'UserData',SeriesData)
+set(handles.ActionName,'BackgroundColor',[1 1 1])
+
+%------------------------------------------------------------------------
+% --- Executes on button press in ActionInputView.
+function ActionInputView_Callback(hObject, eventdata, handles)
+%------------------------------------------------------------------------
+if get(handles.ActionInputView,'Value')
+ActionName_Callback(hObject, eventdata, handles)
+end
 
 %------------------------------------------------------------------------
@@ -2427,4 +2448,6 @@
     if strcmp(FileType,'txt')
         edit(FullSelectName)
+    elseif strcmp(FileType,'xml')
+        editxml(FullSelectName)
     else
         uvmat(FullSelectName)
@@ -2606,2 +2629,4 @@
 NbSlice=str2num(get(handles.num_NbSlice,'String'));
 set(handles.num_NbProcess,'String',num2str(NbSlice))
+
+
Index: /trunk/src/series/aver_stat.m
===================================================================
--- /trunk/src/series/aver_stat.m	(revision 597)
+++ /trunk/src/series/aver_stat.m	(revision 598)
@@ -166,157 +166,156 @@
 end
 
-%% MAIN LOOP ON SLICES
 % for i_slice=1:NbSlice
-   % index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
-    nbfiles=0;
-    nbmissing=0;
-
-    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
-    for index=1:nbfield
-    %for index=index_slice
-          if checkrun
-                stopstate=get(Param.RUNHandle,'BusyAction');
-                update_waitbar(Param.WaitbarHandle,index/nbfield)
-          else
-                stopstate='queue';
-          end
-        if isequal(stopstate,'queue')% enable STOP command
-            
-        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
-        for iview=1:nbview
-            % reading input file(s)
-            [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
+% index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
+nbfiles=0;
+nbmissing=0;
+
+%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
+for index=1:nbfield
+%for index=index_slice
+      if checkrun
+            stopstate=get(Param.RUNHandle,'BusyAction');
+            update_waitbar(Param.WaitbarHandle,index/nbfield)
+      else
+            stopstate='queue';
+      end
+    if isequal(stopstate,'queue')% enable STOP command
+
+    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
+    for iview=1:nbview
+        % reading input file(s)
+        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
+        if ~isempty(errormsg)
+            errormsg=['error of input reading: ' errormsg];
+            break
+        end
+        if ~isempty(NbSlice_calib)
+            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
+        end
+    end
+    else
+        errormsg='stop';
+    end
+    %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
+    %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
+    % EDIT FROM HERE
+
+    if isempty(errormsg)
+        Field=Data{1}; % default input field structure
+        %% coordinate transform (or other user defined transform)
+        if ~isempty(transform_fct)
+            switch nargin(transform_fct)
+                case 4
+                    if length(Data)==2
+                        Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
+                    else
+                        Field=transform_fct(Data{1},XmlData{1});
+                    end
+                case 3
+                    if length(Data)==2
+                        Field=transform_fct(Data{1},XmlData{1},Data{2});
+                    else
+                        Field=transform_fct(Data{1},XmlData{1});
+                    end
+                case 2
+                    Field=transform_fct(Data{1},XmlData{1});
+                case 1
+                    Field=transform_fct(Data{1});
+            end
+        end
+
+        %% calculate tps coefficients if needed
+        if isfield(Param,'ProjObject')&&isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
+            Field=tps_coeff_field(Field,check_proj_tps);
+        end
+
+        %field projection on an object
+        if Param.CheckObject
+            [Field,errormsg]=proj_field(Field,Param.ProjObject);
             if ~isempty(errormsg)
-                errormsg=['error of input reading: ' errormsg];
-                break
-            end
-            if ~isempty(NbSlice_calib)
-                Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
-            end
-        end
-        else
-            errormsg='stop';
-        end
-        %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
-        %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
-        % EDIT FROM HERE
-    
-        if isempty(errormsg)
-            Field=Data{1}; % default input field structure
-            %% coordinate transform (or other user defined transform)
-            if ~isempty(transform_fct)
-                switch nargin(transform_fct)
-                    case 4
-                        if length(Data)==2
-                            Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
-                        else
-                            Field=transform_fct(Data{1},XmlData{1});
-                        end
-                    case 3
-                        if length(Data)==2
-                            Field=transform_fct(Data{1},XmlData{1},Data{2});
-                        else
-                            Field=transform_fct(Data{1},XmlData{1});
-                        end
-                    case 2
-                        Field=transform_fct(Data{1},XmlData{1});
-                    case 1
-                        Field=transform_fct(Data{1});
+                msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
+                return
+            end
+        end
+        nbfiles=nbfiles+1;
+
+        %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
+        %update sum
+        if nbfiles==1 %first field
+            time_1=[];
+            if isfield(Field,'Time')
+                time_1=Field.Time(1);
+            end
+            DataOut=Field;%default
+            for ivar=1:length(Field.ListVarName)
+                VarName=Field.ListVarName{ivar};
+                DataOut.(VarName)=double(DataOut.(VarName));
+            end
+        else   %current field
+            for ivar=1:length(Field.ListVarName)
+                VarName=Field.ListVarName{ivar};
+                sizmean=size(DataOut.(VarName));
+                siz=size(Field.(VarName));
+                if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
+                    msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
+                    return
+                else
+                    DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
                 end
             end
-            
-            %% calculate tps coefficients if needed
-            if isfield(Param,'ProjObject')&&isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
-                Field=tps_coeff_field(Field,check_proj_tps);
-            end
-
-            %field projection on an object
-            if Param.CheckObject
-                [Field,errormsg]=proj_field(Field,Param.ProjObject);
-                if ~isempty(errormsg)
-                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
-                    return
-                end
-            end
-            nbfiles=nbfiles+1;
-            
-            %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
-            %update sum
-            if nbfiles==1 %first field
-                time_1=[];
-                if isfield(Field,'Time')
-                    time_1=Field.Time(1);
-                end
-                DataOut=Field;%default
-                for ivar=1:length(Field.ListVarName)
-                    VarName=Field.ListVarName{ivar};
-                    DataOut.(VarName)=double(DataOut.(VarName));
-                end
-            else   %current field
-                for ivar=1:length(Field.ListVarName)
-                    VarName=Field.ListVarName{ivar};
-                    sizmean=size(DataOut.(VarName));
-                    siz=size(Field.(VarName));
-                    if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
-                        msgbox_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'])
-                        return
-                    else
-                        DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
-                    end
-                end
-            end
-            %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
-        else
-            display(errormsg)
-        end
-    end
-    %%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
-    
-    for ivar=1:length(Field.ListVarName)
-        VarName=Field.ListVarName{ivar};
-        DataOut.(VarName)=DataOut.(VarName)/nbfiles; % normalize the mean
-    end
-    if nbmissing~=0
-        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
-    end
-    if isempty(time) % time is read from files
-        if isfield(Field,'Time')
-            time_end=Field.Time(1);%last time read
-            if ~isempty(time_1)
-                DataOut.Time=time_1;
-                DataOut.Time_end=time_end;
-            end
-        end
-    else  % time from ImaDoc prevails if it exists
+        end
+        %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
+    else
+        display(errormsg)
+    end
+end
+%%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
+
+for ivar=1:length(Field.ListVarName)
+    VarName=Field.ListVarName{ivar};
+    DataOut.(VarName)=DataOut.(VarName)/nbfiles; % normalize the mean
+end
+if nbmissing~=0
+    msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
+end
+if isempty(time) % time is read from files
+    if isfield(Field,'Time')
+        time_end=Field.Time(1);%last time read
+        if ~isempty(time_1)
+            DataOut.Time=time_1;
+            DataOut.Time_end=time_end;
+        end
+    end
+else  % time from ImaDoc prevails if it exists
 %         j1=1;%default
 %         if ~isempty(j1_series{1})
 %             j1=j1_series{1};
 %         end
-        %DataOut.Time=time(1,i1_series{1}(1),j1);
-        %DataOut.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
-        DataOut.Time=time(1);
-        DataOut.Time_end=time(end);
-    end
-    
-    %writting the result file
-    OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),j1_series{1}(1),j1_series{1}(end));
-    if CheckImage{1} %case of images
-        if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
-            DataOut.A=uint16(DataOut.A);
-            imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
-        else
-            DataOut.A=uint8(DataOut.A);
-            imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
-        end
+    %DataOut.Time=time(1,i1_series{1}(1),j1);
+    %DataOut.Time_end=time(end,i1_series{end}(end),j1_series{end}(end));
+    DataOut.Time=time(1);
+    DataOut.Time_end=time(end);
+end
+
+%writting the result file
+OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),j1_series{1}(1),j1_series{1}(end));
+if CheckImage{1} %case of images
+    if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
+        DataOut.A=uint16(DataOut.A);
+        imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
+    else
+        DataOut.A=uint8(DataOut.A);
+        imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
+    end
+    display([OutputFile ' written']);
+else %case of netcdf input file , determine global attributes
+    errormsg=struct2nc(OutputFile,DataOut); %save result file
+    if isempty(errormsg)
         display([OutputFile ' written']);
-    else %case of netcdf input file , determine global attributes
-        errormsg=struct2nc(OutputFile,DataOut); %save result file
-        if isempty(errormsg)
-            display([OutputFile ' written']);
-        else
-            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
-            display(errormsg)
-        end
-    end  % end averaging  loop
+    else
+        msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
+        display(errormsg)
+    end
+end  % end averaging  loop
 % end
 %%%%%%%%%%%%%%%% end loop on slices %%%%%%%%%%%%%%%%
Index: /trunk/src/series/civ_input.m
===================================================================
--- /trunk/src/series/civ_input.m	(revision 597)
+++ /trunk/src/series/civ_input.m	(revision 598)
@@ -25,5 +25,5 @@
 
 
-% Last Modified by GUIDE v2.5 30-Mar-2013 09:15:21
+% Last Modified by GUIDE v2.5 01-Apr-2013 10:00:57
 % Begin initialization code - DO NOT EDIT
 gui_Singleton = 1;
@@ -35,19 +35,6 @@
     'gui_Callback',   []);
 
-if nargin
-    if ischar(varargin{1}) && ~isempty(regexp(varargin{1},'_Callback$','once'))
+if nargin && ischar(varargin{1}) && ~isempty(regexp(varargin{1},'_Callback$','once'))
         gui_State.gui_Callback = str2func(varargin{1});
-    elseif isstruct(varargin{1}) && isequal(varargin{1}.Action.RUN,0)
-        % set the input elements needed on the GUI series when the action is selected in the menu ActionName
-        ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
-            ParamOut.WholeIndexRange='off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
-            ParamOut.NbSlice='off'; ...%nbre of slices ('off' by default)
-            ParamOut.VelType='two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
-            ParamOut.FieldName='two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
-            ParamOut.FieldTransform = 'off';...%can use a transform function
-            ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
-            ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
-            ParamOut.OutputDirExt='.civ';%set the output dir extension
-    end
 end
 
@@ -71,81 +58,37 @@
 set(hObject,'WindowButtonDownFcn',{'mouse_down'}) % allows mouse action with right button (zoom for uicontrol display)
 
-%% Adjust the GUI according to the binaries available in PARAM.xml
-path_civ=fileparts(which('civ_series')); %path to civ
-addpath (path_civ) ; %add the path to civ, (useful in case of change of working directory after civ has been s opened in the working directory)
-errormsg=[];%default error message
-xmlfile=fullfile(path_civ,'PARAM.xml');
-test_batch=0;%default: ,no batch mode available
-sparam=[];
-if ~exist(xmlfile,'file')
-    [success,message]=copyfile(fullfile(path_civ,'PARAM.xml.default'),xmlfile);
-end
-if exist(xmlfile,'file')
-    try
-        t=xmltree(xmlfile);
-        sparam=convert(t);
-    catch ME
-        errormsg={' Unable to read the file PARAM.xml defining the civx binaries:';ME.message};
-         msgbox_uvmat('WARNING',errormsg);
-    end
-else
-    [s,w]=system('oarstat');
-    if ~isequal(s,0)
-        [s,w]=system('qstat');
-    end
-    if isequal(s,0)
-        test_batch=1;
-    end           
-end
-if isfield(sparam,'BatchParam') && isfield(sparam.BatchParam,'BatchMode')
-    batch_mode=sparam.BatchParam.BatchMode;
-    test_command='';
-    switch batch_mode
-        case 'sge'
-            test_command='qstat';
-        case 'oar'
-            test_command='oarstat';
-    end
-    if ~isempty(test_command)
-        [s,w]=system(test_command);
-        if isequal(s,0)
-            test_batch=1;
-        end
-    end
-end
-RUNVal=get(handles.RunMode,'Value');
-if test_batch==0
-   if RUNVal>2
-       set(handles.RunMode,'Value',1)
-   end
-   set(handles.RunMode,'String',{'local';'background'})
-else
-    set(handles.RunMode,'String',{'local';'background';'cluster'})
-end
-
-%% load the list of previously browsed files in the upper bar menu Open/
-dir_perso=prefdir; % path to the directory .matlab for personal data
-profil_perso=fullfile(dir_perso,'uvmat_perso.mat');% personal data file uvmauvmat_perso.mat' in .matlab
-if exist(profil_perso,'file')
-    h=load (profil_perso);
-    if isfield(h,'MenuFile')
-        for ifile=1:min(length(h.MenuFile),5)
-            eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',h.MenuFile{ifile});'])
-        end
-    end
-end
-
-%% prepare the GUI with parameters from the input file if opened from uvmat
+%% set visibility options
+        set(handles.num_MaxDiff,'Visible','on')
+        set(handles.num_MaxVel,'Visible','on')
+        set(handles.title_MaxVel,'Visible','on')
+        set(handles.title_MaxDiff,'Visible','on')
+        set(handles.num_Nx,'Visible','off')
+        set(handles.num_Ny,'Visible','off')
+        set(handles.title_Nx,'Visible','off')
+        set(handles.title_Ny,'Visible','off')
+        set(handles.num_CorrSmooth,'Style','popupmenu')
+        set(handles.num_CorrSmooth,'Value',1)
+        set(handles.num_CorrSmooth,'String',{'1';'2'})
+        set(handles.CheckThreshold,'Visible','on')
+        set(handles.CheckDeformation,'Value',0)% desactivate (work in progress)
+        set(handles.CheckDecimal,'Value',0)% desactivate (work in progress)
+        
+%% prepare the GUI with input parameters 
+% from the GUI series
+
+%from the input file
 filecell=get_file_series(Param);
-    set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
-    errormsg=display_file_name(handles,filecell{1});
-    if ~isempty(errormsg)
-        msgbox_uvmat('ERROR',errormsg)
-    end
-    set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
-    
-    set(handles.civ_series,'WindowStyle','modal')% Make the GUI modal 
+set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
+errormsg=display_file_name(handles,filecell{1});
+if ~isempty(errormsg)
+    msgbox_uvmat('ERROR',errormsg)
+end
+set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
+if isfield(Param,'ActionInput')&&isfield(Param.ActionInput,'Program')&& strcmp(Param.ActionInput.Program,'civ_series')
+    fill_GUI(Param.ActionInput,handles.civ_input)
+end
+set(handles.civ_input,'WindowStyle','modal')% Make the GUI modal
 drawnow
-uiwait(handles.civ_series);
+uiwait(handles.civ_input);
 
 %Program_Callback([],[], handles)
@@ -157,14 +100,14 @@
 % Get default command line output from handles structure
 varargout{1} = handles.output;
-delete(handles.civ_series)
+delete(handles.civ_input)
 
 % --- Executes when user attempts to close get_field.
-function civ_series_CloseRequestFcn(hObject, eventdata, handles)
+function civ_input_CloseRequestFcn(hObject, eventdata, handles)
 if isequal(get(handles.get_field, 'waitstatus'), 'waiting')
     % The GUI is still in UIWAIT, us UIRESUME
-    uiresume(handles.civ_series);
+    uiresume(handles.civ_input);
 else
     % The GUI is no longer waiting, just close it
-    delete(handles.civ_series);
+    delete(handles.civ_input);
 end
 %------------------------------------------------------------------------
@@ -343,10 +286,10 @@
 
 %% enable OK, BATCH button and 'status' display
-set(handles.OK, 'Enable','On')
-set(handles.OK,'BackgroundColor',[1 0 0])%set RUN button to red color
-if isfield(handles,'status')
-    set(handles.status,'Value',0);       %suppress the 'status' display
-    status_Callback([], [], handles)
-end
+% set(handles.OK, 'Enable','On')
+% set(handles.OK,'BackgroundColor',[1 0 0])%set RUN button to red color
+% if isfield(handles,'status')
+%     set(handles.status,'Value',0);       %suppress the 'status' display
+%     status_Callback([], [], handles)
+% end
 
 %% determine nomenclature types and extension of the input files
@@ -861,7 +804,7 @@
 %------------------------------------------------------------------------
 
-handles.output.ActionInput=read_GUI(handles.civ_series);
+handles.output.ActionInput=read_GUI(handles.civ_input);
 guidata(hObject, handles);% Update handles structure
-uiresume(handles.civ_series);
+uiresume(handles.civ_input);
 drawnow
 
@@ -886,850 +829,850 @@
 end
 
-%-------------------------------------------------------------------
-% --- Executes on button press in status.
-function status_Callback(hObject, eventdata, handles)
-%-------------------------------------------------------------------
-val=get(handles.status,'Value');
-if val==0
-    set(handles.status,'BackgroundColor',[0 1 0])
-    hfig=findobj(allchild(0),'name','civ_status');
-    if ~isempty(hfig)
-        delete(hfig)
-    end
-    return
-end
-set(handles.status,'BackgroundColor',[1 1 0])
-drawnow
-listtype={'civ1','fix1','patch1','civ2','fix2','patch2'};
-Param.CheckCiv1=get(handles.CheckCiv1,'Value');
-Param.CheckFix1=get(handles.CheckFix1,'Value');
-Param.CheckPatch1=get(handles.CheckPatch1,'Value');
-Param.CheckCiv2=get(handles.CheckCiv2,'Value');
-Param.CheckFix2=get(handles.CheckFix2,'Value');
-Param.CheckPatch2=get(handles.CheckPatch2,'Value');
-box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
-
-option_civ=find(box_test,1,'last');%last selected option (non-zero index of box_test)
-filecell=get(handles.civ_series,'UserData');%retrieve the list of output files expected for PIV
-test_new=0;
-if ~isfield(filecell,'nc')
-    test_new=1;
-    [ref_i,ref_j,errormsg]=find_ref_indices(handles);
-    if ~isempty(errormsg)
-        msgbox_uvmat('ERROR',errormsg)
-        return
-    end
-    filecell=set_civ_filenames(handles,ref_i,ref_j,box_test);%determine the output file expected from the GUI status
-end
-if ~isequal(box_test(4:6),[0 0 0])
-    civ_files=filecell.nc.civ2;%case of civ2 operations
-else
-    civ_files=filecell.nc.civ1;
-end
-[root,filename,ext]=fileparts(civ_files{1});
-[rootroot,SubDir,extdir]=fileparts(root);
-hfig=findobj(allchild(0),'name','civ_status');
-if isempty(hfig)
-    hfig=figure('DeleteFcn',@stop_status);
-    set(hfig,'MenuBar','none')% suppress the menu bar
-    set(hfig,'NumberTitle','off')%suppress the fig number in the title
-    set(hfig,'name','civ_status')
-    set(hfig,'tag','civ_status')
-    set(hfig,'UserData',civ_files)
-    hlist= uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', {'open_uvmat'},'tag','list');
-    uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','msgbox','Max',2,'String','checking files...');
-    uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
-    %uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@close_GUI);
-    uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@stop_status);
-    hrefresh=uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.1 0.01 0.2 0.07],'String','Refresh','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@refresh_GUI);
-    BarPosition=[0.05 0.81 0.01 0.05];
-    uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
-    drawnow 
-end
-StatusData.time_ref=get(handles.OK,'UserData');% get the time of launch
-StatusData.option_civ=option_civ;
-set(hrefresh,'UserData',StatusData)
-filepath=fileparts(civ_files{1});
-set(hlist,'UserData',fileparts(filepath))
-refresh_GUI(hrefresh,[])
-
-%------------------------------------------------------------------------   
-% launched by refreshing the status figure
-function refresh_GUI(hObject, eventdata)
-%------------------------------------------------------------------------
-Tabchar={};
-BarPosition=[0.05 0.81 0.01 0.05];
-hfig=get(hObject,'parent');
-StatusData=get(hObject,'UserData');
-civ_files=get(hfig,'UserData');
-[filepath,filename,ext]=fileparts(civ_files{1});
-[tild,SubDir,extdir]=fileparts(filepath);
-SubDir=[SubDir extdir];
-option_civ=StatusData.option_civ;
-nbfiles=numel(civ_files);
-testrecent=0;
-count=0;
-datnum=zeros(1,nbfiles);
-filefound=cell(1,nbfiles);
-for ifile=1:nbfiles
-    detect=exist(civ_files{ifile},'file'); % check the existence of the file
-    option=0;
-    if detect==0
-        option_str='not created';
-    else
-        datfile=dir(civ_files{ifile});
-        if isfield(datfile,'datenum')
-            datnum(ifile)=datfile.datenum;%only available in recent matlab versions
-            testrecent=1;
-        end
-        filefound(ifile)={datfile.name};
-        
-        % check the content  netcdf file
-        Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','CivStage','patch2','fix2','civ2','patch','fix');
-        option_list={'civ1','fix1','patch1','civ2','fix2','patch2'};
-        if ~isempty(Data.CivStage)
-            option=Data.CivStage;%case of Matlab civ
-        else
-            if ~isempty(Data.patch2) && isequal(Data.patch2,1)
-                option=6;
-            elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
-                option=5;
-            elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
-                option=4;
-            elseif ~isempty(Data.patch) && isequal(Data.patch,1);
-                option=3;
-            elseif ~isempty(Data.fix) && isequal(Data.fix,1);
-                option=2;
-            else
-                option=1;
-            end
-        end
-        option_str=option_list{option};
-        if datnum(ifile)<StatusData.time_ref
-            option_str=[option_str '  --OLD--'];
-        end
-    end
-    if option >= option_civ
-        count=count+1;
-    end
-    [filepath,filename,ext]=fileparts(civ_files{ifile});
-    Tabchar{ifile,1}=[fullfile(SubDir,filename) ext  '...' option_str];
-end
-datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
-if isempty(datnum)
-    if testrecent
-        message='no civ result created yet';
-    else
-        message='';
-    end
-else
-    datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
-    [first,ind]=min(datnum);
-    [last,indlast]=max(datnum);
-    message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
-        ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
-end
-hlist=findobj(hfig,'tag','list');
-hmsgbox=findobj(hfig,'tag','msgbox');
-hwaitbar=findobj(hfig,'tag','waitbar');
-set(hlist,'String',Tabchar)
-set(hmsgbox,'String', message)
-if count>0 %&& ~test_new
-    BarPosition(3)=0.9*count/nbfiles;
-    set(hwaitbar,'Position',BarPosition)
-end
-
-
-%------------------------------------------------------------------------   
-% launched by deleting the status figure
-function stop_status(hObject, eventdata)
-%------------------------------------------------------------------------
-hciv=findobj(allchild(0),'tag','civ');
-hhciv=guidata(hciv);
-set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
-set(hhciv.status,'BackgroundColor',[0 1 0])
+% %-------------------------------------------------------------------
+% % --- Executes on button press in status.
+% function status_Callback(hObject, eventdata, handles)
+% %-------------------------------------------------------------------
+% val=get(handles.status,'Value');
+% if val==0
+%     set(handles.status,'BackgroundColor',[0 1 0])
+%     hfig=findobj(allchild(0),'name','civ_status');
+%     if ~isempty(hfig)
+%         delete(hfig)
+%     end
+%     return
+% end
+% set(handles.status,'BackgroundColor',[1 1 0])
+% drawnow
+% listtype={'civ1','fix1','patch1','civ2','fix2','patch2'};
+% Param.CheckCiv1=get(handles.CheckCiv1,'Value');
+% Param.CheckFix1=get(handles.CheckFix1,'Value');
+% Param.CheckPatch1=get(handles.CheckPatch1,'Value');
+% Param.CheckCiv2=get(handles.CheckCiv2,'Value');
+% Param.CheckFix2=get(handles.CheckFix2,'Value');
+% Param.CheckPatch2=get(handles.CheckPatch2,'Value');
+% box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
+% 
+% option_civ=find(box_test,1,'last');%last selected option (non-zero index of box_test)
+% filecell=get(handles.civ_input,'UserData');%retrieve the list of output files expected for PIV
+% test_new=0;
+% if ~isfield(filecell,'nc')
+%     test_new=1;
+%     [ref_i,ref_j,errormsg]=find_ref_indices(handles);
+%     if ~isempty(errormsg)
+%         msgbox_uvmat('ERROR',errormsg)
+%         return
+%     end
+%     filecell=set_civ_filenames(handles,ref_i,ref_j,box_test);%determine the output file expected from the GUI status
+% end
+% if ~isequal(box_test(4:6),[0 0 0])
+%     civ_files=filecell.nc.civ2;%case of civ2 operations
+% else
+%     civ_files=filecell.nc.civ1;
+% end
+% [root,filename,ext]=fileparts(civ_files{1});
+% [rootroot,SubDir,extdir]=fileparts(root);
+% hfig=findobj(allchild(0),'name','civ_status');
+% if isempty(hfig)
+%     hfig=figure('DeleteFcn',@stop_status);
+%     set(hfig,'MenuBar','none')% suppress the menu bar
+%     set(hfig,'NumberTitle','off')%suppress the fig number in the title
+%     set(hfig,'name','civ_status')
+%     set(hfig,'tag','civ_status')
+%     set(hfig,'UserData',civ_files)
+%     hlist= uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', {'open_uvmat'},'tag','list');
+%     uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','msgbox','Max',2,'String','checking files...');
+%     uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
+%     %uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@close_GUI);
+%     uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@stop_status);
+%     hrefresh=uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.1 0.01 0.2 0.07],'String','Refresh','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@refresh_GUI);
+%     BarPosition=[0.05 0.81 0.01 0.05];
+%     uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
+%     drawnow 
+% end
+% StatusData.time_ref=get(handles.OK,'UserData');% get the time of launch
+% StatusData.option_civ=option_civ;
+% set(hrefresh,'UserData',StatusData)
+% filepath=fileparts(civ_files{1});
+% set(hlist,'UserData',fileparts(filepath))
+% refresh_GUI(hrefresh,[])
 
 % %------------------------------------------------------------------------   
-% % launched by pressing OK on the status figure
-% function close_GUI(hObject, eventdata)
+% % launched by refreshing the status figure
+% function refresh_GUI(hObject, eventdata)
 % %------------------------------------------------------------------------
-%     delete(gcbf)
-
-
-%------------------------------------------------------------------------
-% --- Main lauch command, called by OK and BATCH
-function errormsg=launch_jobs(hObject, eventdata, handles)
-%------------------------------------------------------------------------
-errormsg='';%default
-
-%% read the input parameters from the  GUI civ_input
-Param=read_GUI(handles.civ_series);
-
-%% check the selected list of operations:
-operations={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
-box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
-index_first=find(box_test==1,1);
-if isempty(index_first)
-    errormsg='no selected operation';
-    return
-end
-index_last=find(box_test==1,1,'last');
-box_used=box_test(index_first : index_last);
-[box_missing,ind_missing]=min(box_used);
-if isequal(box_missing,0); %there is a missing step in the sequence of operations
-    errormsg=['missing' cell2mat(operations(ind_missing))];
-    return
-end
-
-%% check mask if selecetd 
-%could be included in get_mask callback ?
-if isequal(get(handles.CheckMask,'Value'),1)
-    maskname=get(handles.Mask,'String');
-    if ~exist(maskname,'file')
-        get_mask_civ1_Callback(hObject, eventdata, handles);
-    end
-end
-if isequal(get(handles.CheckMask,'Value'),1)
-    maskname=get(handles.Mask,'String');
-    if ~exist(maskname,'file')
-        get_mask_fix1_Callback(hObject, eventdata, handles);
-    end
-end
-if isequal(get(handles.CheckMask,'Value'),1)
-    maskname=get(handles.Mask,'String');
-    if ~exist(maskname,'file')
-        get_mask_civ2_Callback(hObject, eventdata, handles);
-    end
-end
-if isequal(get(handles.CheckMask,'Value'),1)
-    maskname=get(handles.Mask,'String');
-    if ~exist(maskname,'file')
-        get_mask_fix2_Callback(hObject, eventdata, handles);
-    end
-end
-
-%% reinitialise status callback 
-if isfield(handles,'status')
-    set(handles.status,'Value',0);%suppress status display
-    status_Callback([], [], handles)
-end
-
-%% read the PARAM.xml file to get the binaries (and batch_mode if batch)
-path_civ=fileparts(which('civ')); %path to the source directory of uvmat
-xmlfile=fullfile(path_civ,'PARAM.xml');
-s=[];
-if exist(xmlfile,'file')% search parameter xml file in the whole matlab path
-    t=xmltree(xmlfile);
-    s=convert(t);
-end% default configuration
-if ~isfield(s,'RunParam')
-    Param.xml.Civ1Bin=fullfile('bin','civ1');
-    Param.xml.Civ2Bin=fullfile('bin','civ2');
-    Param.xml.FixBin=fullfile('bin','fix_flag');
-    Param.xml.PatchBin=fullfile('bin','patch_up');
-end
-if strcmp(Param.RunMode,'cluster') %computation dispatched on a cluster
-    if isfield(s,'BatchParam')
-        Param.xml=s.BatchParam;
-        if isfield(Param.xml,'BatchMode')
-            batch_mode=Param.xml.BatchMode;
-            if ~ismember(batch_mode,{'sge','oar'})
-                errormsg=['batch mode ' batch_mode ' not supported by UVMAT'];
-                return
-            end
-        end
-    else
-        %default configuration
-        Param.xml.Civ1Bin=fullfile('bin','civ1');
-        Param.xml.Civ2Bin=fullfile('bin','civ2');
-        Param.xml.FixBin=fullfile('bin','fix_flag');
-        Param.xml.PatchBin=fullfile('bin','patch_up');
-   %     Param.xml.CivmBin=fullfile('bin','civ_matlab');
-        Param.xml.BatchMode='oar';% TODO : allow choice for sge
-    end
-else % run
-    if isfield(s,'RunParam')
-        Param.xml=s.RunParam;
-    else %default configuration
-        Param.xml.Civ1Bin=fullfile('bin','civ1');
-        Param.xml.Civ2Bin=fullfile('bin','civ2');
-        Param.xml.FixBin=fullfile('bin','fix_flag');
-        Param.xml.PatchBin=fullfile('bin','patch_up');
-    end
-end
-%Param.xml.CivmBin=fullfile('bin','civ_matlab');
-
-%% check if the binaries exist : to move in civ_opening
-binary_list={};
-switch Param.Program
-    case 'CivX'
-        binary_list={'Civ1Bin','Civ2Bin','PatchBin','FixBin'};
-    case 'CivAll'% desactivated option
-        binary_list={'Civ'};
-%     case 'civ_matlab.sh'% compiled version of civ_matlab 
-%         binary_list={'CivmBin'};         
-end
-for bin_name=binary_list %loop on the list of binaries
-    if isfield(Param.xml,bin_name{1})% bin_name{1} =current name in the list
-        if ~isunix
-        Param.xml.(bin_name{1})=[regexprep(Param.xml.(bin_name{1}),'/','\') '.exe'];
-        end
-        if exist(Param.xml.(bin_name{1}),'file')
-            [path,name,ext]=fileparts(Param.xml.(bin_name{1}));
-            currentdir=pwd;
-            if isempty(path)
-                path=fileparts(which('civ.m'));
-            end
-            if exist(path,'dir')
-                cd(path);
-                binpath=pwd;%path of the binary
-                Param.xml.(bin_name{1})=fullfile(binpath,[name ext]);
-                cd(currentdir);
-            else
-                errormsg=['path ' path ' for binaries specified in PARAM.xml does not exist'];
-                return
-            end          
-        else  %look for the full path if the file name has been defined with a relative path in PARAM.xm
-            fullname=fullfile(path_civ,Param.xml.(bin_name{1}));
-            if exist(fullname,'file')
-                Param.xml.(bin_name{1})=fullname;
-            else
-                errormsg=['Binary ' Param.xml.(bin_name{1}) ' specified in PARAM.xml does not exist'];
-                return
-            end
-        end
-    end
-end
-if strcmp(Param.Program,'civ_matlab.sh')
-    if ~exist(fullfile(path_civ,'civ_matlab.sh'),'file')
-        errormsg=[{'no file civ_matlab.sh found'}; {'run compile_functions.m to create it by compiling civ_matlab.m'}];
-            return
-    end
-end
-
-%% set the list of files and check them
-display('checking the files...')
-[ref_i,ref_j,errormsg]=find_ref_indices(handles);
-if ~isempty(errormsg)
-    return
-end
-[filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,tild,tild,compare,errormsg]=...
-    set_civ_filenames(handles,ref_i,ref_j,box_test);
-if ~isempty(errormsg)
-    return
-end
-set(handles.civ_series,'UserData',filecell);%store for futur use of status callback
-display('files OK, processing...')
-
-%% create subfolders for log, cmx, nml, xml, bat
-RootBat=fileparts(filecell.nc.civ1{1,1});
-switch(Param.Program)
-    case {'CivX','CivAll'}
-dir_list={'0_BAT','0_CMX','0_LOG'};
-    case {'civ_matlab','civ_matlab.sh'}
-        dir_list={'0_BAT','0_XML'};
-end
-for k=1:length(dir_list)
-    if ~exist(fullfile(RootBat,dir_list{k}),'dir')
-        mkdir(fullfile(RootBat,dir_list{k}));
-    end
-end
-
-%% get information on input images or movies
-nbfield=numel(i1_civ1);
-nbslice=numel(j1_civ1);
-% if strcmp(Param.Program,'civ_matlab')
-    if Param.CheckCiv1
-        [Param.Civ1.FileTypeA,ImageInfoA_civ1,Param.Civ1.ImageA]=get_file_type(filecell.ima1.civ1{1});
-        [Param.Civ1.FileTypeB,ImageInfoB_civ1,Param.Civ1.ImageB]=get_file_type(filecell.ima2.civ1{1});
-    end
-    if Param.CheckCiv2
-        [Param.Civ2.FileTypeA,ImageInfoA_civ2,Param.Civ2.ImageA]=get_file_type(filecell.ima1.civ2{1});
-        [Param.Civ2.FileTypeB,ImageInfoB_civ2,Param.Civ2.ImageB]=get_file_type(filecell.ima2.civ2{1});
-    end
+% Tabchar={};
+% BarPosition=[0.05 0.81 0.01 0.05];
+% hfig=get(hObject,'parent');
+% StatusData=get(hObject,'UserData');
+% civ_files=get(hfig,'UserData');
+% [filepath,filename,ext]=fileparts(civ_files{1});
+% [tild,SubDir,extdir]=fileparts(filepath);
+% SubDir=[SubDir extdir];
+% option_civ=StatusData.option_civ;
+% nbfiles=numel(civ_files);
+% testrecent=0;
+% count=0;
+% datnum=zeros(1,nbfiles);
+% filefound=cell(1,nbfiles);
+% for ifile=1:nbfiles
+%     detect=exist(civ_files{ifile},'file'); % check the existence of the file
+%     option=0;
+%     if detect==0
+%         option_str='not created';
+%     else
+%         datfile=dir(civ_files{ifile});
+%         if isfield(datfile,'datenum')
+%             datnum(ifile)=datfile.datenum;%only available in recent matlab versions
+%             testrecent=1;
+%         end
+%         filefound(ifile)={datfile.name};
+%         
+%         % check the content  netcdf file
+%         Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','CivStage','patch2','fix2','civ2','patch','fix');
+%         option_list={'civ1','fix1','patch1','civ2','fix2','patch2'};
+%         if ~isempty(Data.CivStage)
+%             option=Data.CivStage;%case of Matlab civ
+%         else
+%             if ~isempty(Data.patch2) && isequal(Data.patch2,1)
+%                 option=6;
+%             elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
+%                 option=5;
+%             elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
+%                 option=4;
+%             elseif ~isempty(Data.patch) && isequal(Data.patch,1);
+%                 option=3;
+%             elseif ~isempty(Data.fix) && isequal(Data.fix,1);
+%                 option=2;
+%             else
+%                 option=1;
+%             end
+%         end
+%         option_str=option_list{option};
+%         if datnum(ifile)<StatusData.time_ref
+%             option_str=[option_str '  --OLD--'];
+%         end
+%     end
+%     if option >= option_civ
+%         count=count+1;
+%     end
+%     [filepath,filename,ext]=fileparts(civ_files{ifile});
+%     Tabchar{ifile,1}=[fullfile(SubDir,filename) ext  '...' option_str];
 % end
-
-%% MAIN LOOP
-time=get(handles.ImaDoc,'UserData'); %get the set of times
-TimeUnit=get(handles.TimeUnit,'String');
-checkframe=strcmp(TimeUnit,'frame');
-batch_file_list=[];%should be renamed file_list, can be used for xml or bash files
-NomTypeIma=get(handles.NomType,'String');
-for ifile=1:nbfield
-    for j=1:nbslice
-            
-        % define output file name
-        if Param.CheckCiv2==1 || Param.CheckFix2==1 || Param.CheckPatch2==1
-            Param.OutputFile=filecell.nc.civ2{ifile,j};
-        else
-            Param.OutputFile=filecell.nc.civ1{ifile,j};
-        end
-        Param.OutputFile=regexprep(Param.OutputFile,'.nc','');
-
-        if Param.CheckCiv1
-            % read image-dependent parameters          
-            if ~checkframe% && size(time,1)>=i2_civ1(ifile) && size(time,2)>=j2_civ1(j)
-                Param.Civ1.Dt=(time(i2_civ1(ifile)+1,j2_civ1(j)+1)-time(i1_civ1(ifile)+1,j1_civ1(j)+1));
-            else
-                Param.Civ1.Dt=1;
-            end
-            Param.Civ1.Time=((time(i2_civ1(ifile)+1,j2_civ1(j)+1)+time(i1_civ1(ifile)+1,j1_civ1(j)+1))/2);
-            if strcmp(Param.Program,'CivX')
-                Param.Civ1.term_a=num2stra(j1_civ1(j),nom_type_nc);%UTILITE?
-                Param.Civ1.term_b=num2stra(j2_civ1(j),nom_type_nc);%
-            end
-            Param.Civ1.ImageA=filecell.ima1.civ1{ifile,j};
-            Param.Civ1.ImageB=filecell.ima2.civ1{ifile,j};
-            Param.Civ1.ImageBitDepth=ImageInfoA_civ1.BitDepth;
-            Param.Civ1.ImageWidth=ImageInfoA_civ1.Width;
-            Param.Civ1.ImageHeight=ImageInfoA_civ1.Height;
-            if strcmp(NomTypeIma,'*')
-                Param.Civ1.FrameIndexA=i1_civ1(ifile);
-                Param.Civ1.FrameIndexB=i2_civ1(ifile);
-            else% case of movies indexed with i, the frame index is then in j
-                Param.Civ1.FrameIndexA=j1_civ1(j);
-                Param.Civ1.FrameIndexB=j2_civ1(j);
-            end
-            % read mask )parameters
-            if Param.Civ1.CheckMask % the lines below should be changed with the new gui
-                if ~exist(Param.Civ1.Mask,'file')
-                    maskbase=[filecell.filebase '_' Param.Civ1.Mask]; %
-                    nbslice_mask=str2double(Param.Civ1.Mask(1:end-4)); %
-                    i1_mask=mod(i1_civ1(ifile)-1,nbslice_mask)+1;
-                    [RootPathMask,RootFileMask]=fileparts(maskbase);
-                    Param.Civ1.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
-                end
-            end
-            % read grid parameters
-            if Param.Civ1.CheckGrid
-                if numel(Param.Civ1.Grid)>=4 && isequal(Param.Civ1.Grid(end-3:end),'grid')
-                    nbslice_grid=str2double(Param.Civ1.Grid(1:end-4)); %
-                    if ~isnan(nbslice_grid)
-                        i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
-                        Param.Civ1.Grid=[filecell.filebase '_' fullfile_uvmat('','',Param.Civ1.Grid,'.grid','_1',i1_grid)];
-                        if ~exist(Param.Civ1.GridName,'file')
-                            errormsg='grid file absent for civ1';
-                            return
-                        end
-                    elseif ~exist(Param.Civ1.Grid,'file')
-                        errormsg='grid file absent for civ1';
-                        return
-                    end
-                end
-            end
-            
-        end
-        
-        if Param.CheckCiv2==1
-            Param.Civ2.ImageA=filecell.ima1.civ2{ifile,j};
-            Param.Civ2.ImageB=filecell.ima2.civ2{ifile,j};          
-            if ~checkframe %&& size(time,1)>=i2_civ2(ifile) && size(time,2)>=j2_civ2(j)
-                Param.Civ2.Dt=time(i2_civ2(ifile)+1,j2_civ2(j)+1)-time(i1_civ2(ifile)+1,j1_civ2(j)+1);
-            else
-                Param.Civ2.Dt=1;
-            end
-            Param.Civ2.Time=(time(i2_civ2(ifile)+1,j2_civ2(j)+1)+time(i1_civ2(ifile)+1,j1_civ2(j)+1))/2;
-            if strcmp(Param.Program,'CivX')
-                Param.Civ2.term_a=num2stra(j1_civ2(j),nom_type_nc);
-                Param.Civ2.term_b=num2stra(j2_civ2(j),nom_type_nc);
-            end
-            Param.Civ2.filename_nc1=filecell.nc.civ1{ifile,j};
-            Param.Civ2.filename_nc1(end-2:end)=[]; % remove '.nc'
-            
-            % mask
-            if Param.Civ2.CheckMask
-                if ~exist(Param.Civ2.Mask,'file')
-                    maskbase=[filecell.filebase '_' Param.Civ2.Mask]; %
-                    nbslice_mask=str2double(Param.Civ2.Mask(1:end-4)); %
-                    i1_mask=mod(i1_civ2(ifile)-1,nbslice_mask)+1;
-                    [RootPathMask,RootFileMask]=fileparts(maskbase);
-                    Param.Civ2.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
-                    %                     Param.Civ2.Mask=name_generator(maskbase,i1_mask,1,'.png','_i');
-                end
-            end
-            %grid
-            if Param.Civ2.CheckGrid
-                if numel(Param.Civ2.Grid)>=4 && isequal(Param.Civ2.Grid(end-3:end),'grid')
-                    nbslice_grid=str2double(Param.Civ2.Grid(1:end-4)); %
-                    if ~isnan(nbslice_grid)
-                        i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
-                        Param.Civ2.Grid=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
-                        %                         Param.Civ2.Grid=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
-                    end
-                end
-            end
-
-            Param.Civ2.ImageBitDepth=ImageInfoA_civ2.BitDepth;
-            Param.Civ2.ImageWidth=ImageInfoA_civ2.Width;
-            Param.Civ2.ImageHeight=ImageInfoA_civ2.Height;
-            if strcmp(NomTypeIma,'*')
-                Param.Civ2.FrameIndexA=i1_civ2(ifile);
-                Param.Civ2.FrameIndexB=i2_civ2(ifile);
-            else% case of movies indexed with i, the frame index is then in j
-                Param.Civ2.FrameIndexA=j1_civ2(j);
-                Param.Civ2.FrameIndexB=j2_civ2(j);
-            end
-        end
-       
-        % write the command and eventually the cmx, xml or nml files
-        cmd=write_cmd(Param);
-        write_param(Param);
-              
-        % create the command file name .m, .bat or .sh depending on the ok option
-        switch Param.Program
-            case {'civ_matlab'}
-                filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.m');           
-                [BatRoot,BatFile]=fileparts(filename_bat);
-                 BatFile=regexprep(BatFile,'-','__');%transform name to suppress'-' (not valid for .m files)
-                 filename_bat=[fullfile(BatRoot,BatFile) '.m'];
-            case {'CivX','CivAll','civ_matlab.sh'}
-                switch computer
-                    case {'PCWIN','PCWIN64'}
-                        filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.bat');
-                    case {'GLNX86','GLNXA64','MACI64'}
-                        filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
-                end
-        end
-        
-        % print the command in the bat file
-        [fid,message]=fopen(filename_bat,'w');
-        if isequal(fid,-1)
-            errormsg=['creation of .bat file: ' message];
-            return
-        end
-        fprintf(fid,cmd);
-        fclose(fid);
-        
-        % special case for civ_matlab on cluster
-        if strcmp(Param.Program,'civ_matlab') && strcmp(Param.RunMode,'cluster')
-            filename_bat2=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
-            [fid,message]=fopen(filename_bat2,'w');
-            if isequal(fid,-1)
-                errormsg=['creation of .bat file: ' message];
-                return
-            end
-            fprintf(fid,['#!/bin/bash \n' ...
-                '/etc/sysprofile \n'...
-                'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
-                'addpath(''' path_civ ''');\n']);
-%             for p=1:length(batch_file_list)
-                fprintf(fid,['run ' filename_bat '\n']);
+% datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
+% if isempty(datnum)
+%     if testrecent
+%         message='no civ result created yet';
+%     else
+%         message='';
+%     end
+% else
+%     datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
+%     [first,ind]=min(datnum);
+%     [last,indlast]=max(datnum);
+%     message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
+%         ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
+% end
+% hlist=findobj(hfig,'tag','list');
+% hmsgbox=findobj(hfig,'tag','msgbox');
+% hwaitbar=findobj(hfig,'tag','waitbar');
+% set(hlist,'String',Tabchar)
+% set(hmsgbox,'String', message)
+% if count>0 %&& ~test_new
+%     BarPosition(3)=0.9*count/nbfiles;
+%     set(hwaitbar,'Position',BarPosition)
+% end
+% 
+% 
+% %------------------------------------------------------------------------   
+% % launched by deleting the status figure
+% function stop_status(hObject, eventdata)
+% %------------------------------------------------------------------------
+% hciv=findobj(allchild(0),'tag','civ');
+% hhciv=guidata(hciv);
+% set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
+% set(hhciv.status,'BackgroundColor',[0 1 0])
+% 
+% % %------------------------------------------------------------------------   
+% % % launched by pressing OK on the status figure
+% % function close_GUI(hObject, eventdata)
+% % %------------------------------------------------------------------------
+% %     delete(gcbf)
+% 
+
+% %------------------------------------------------------------------------
+% % --- Main lauch command, called by OK and BATCH
+% function errormsg=launch_jobs(hObject, eventdata, handles)
+% %------------------------------------------------------------------------
+% errormsg='';%default
+% 
+% %% read the input parameters from the  GUI civ_input
+% Param=read_GUI(handles.civ_input);
+% 
+% %% check the selected list of operations:
+% operations={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
+% box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
+% index_first=find(box_test==1,1);
+% if isempty(index_first)
+%     errormsg='no selected operation';
+%     return
+% end
+% index_last=find(box_test==1,1,'last');
+% box_used=box_test(index_first : index_last);
+% [box_missing,ind_missing]=min(box_used);
+% if isequal(box_missing,0); %there is a missing step in the sequence of operations
+%     errormsg=['missing' cell2mat(operations(ind_missing))];
+%     return
+% end
+% 
+% %% check mask if selecetd 
+% %could be included in get_mask callback ?
+% if isequal(get(handles.CheckMask,'Value'),1)
+%     maskname=get(handles.Mask,'String');
+%     if ~exist(maskname,'file')
+%         get_mask_civ1_Callback(hObject, eventdata, handles);
+%     end
+% end
+% if isequal(get(handles.CheckMask,'Value'),1)
+%     maskname=get(handles.Mask,'String');
+%     if ~exist(maskname,'file')
+%         get_mask_fix1_Callback(hObject, eventdata, handles);
+%     end
+% end
+% if isequal(get(handles.CheckMask,'Value'),1)
+%     maskname=get(handles.Mask,'String');
+%     if ~exist(maskname,'file')
+%         get_mask_civ2_Callback(hObject, eventdata, handles);
+%     end
+% end
+% if isequal(get(handles.CheckMask,'Value'),1)
+%     maskname=get(handles.Mask,'String');
+%     if ~exist(maskname,'file')
+%         get_mask_fix2_Callback(hObject, eventdata, handles);
+%     end
+% end
+% 
+% %% reinitialise status callback 
+% if isfield(handles,'status')
+%     set(handles.status,'Value',0);%suppress status display
+%     status_Callback([], [], handles)
+% end
+% 
+% %% read the PARAM.xml file to get the binaries (and batch_mode if batch)
+% % path_civ=fileparts(which('civ')); %path to the source directory of uvmat
+% % xmlfile=fullfile(path_civ,'PARAM.xml');
+% % s=[];
+% % if exist(xmlfile,'file')% search parameter xml file in the whole matlab path
+% %     t=xmltree(xmlfile);
+% %     s=convert(t);
+% % end% default configuration
+% % if ~isfield(s,'RunParam')
+% %     Param.xml.Civ1Bin=fullfile('bin','civ1');
+% %     Param.xml.Civ2Bin=fullfile('bin','civ2');
+% %     Param.xml.FixBin=fullfile('bin','fix_flag');
+% %     Param.xml.PatchBin=fullfile('bin','patch_up');
+% % end
+% % if strcmp(Param.RunMode,'cluster') %computation dispatched on a cluster
+% %     if isfield(s,'BatchParam')
+% %         Param.xml=s.BatchParam;
+% %         if isfield(Param.xml,'BatchMode')
+% %             batch_mode=Param.xml.BatchMode;
+% %             if ~ismember(batch_mode,{'sge','oar'})
+% %                 errormsg=['batch mode ' batch_mode ' not supported by UVMAT'];
+% %                 return
+% %             end
+% %         end
+% %     else
+% %         %default configuration
+% %         Param.xml.Civ1Bin=fullfile('bin','civ1');
+% %         Param.xml.Civ2Bin=fullfile('bin','civ2');
+% %         Param.xml.FixBin=fullfile('bin','fix_flag');
+% %         Param.xml.PatchBin=fullfile('bin','patch_up');
+% %    %     Param.xml.CivmBin=fullfile('bin','civ_matlab');
+% %         Param.xml.BatchMode='oar';% TODO : allow choice for sge
+% %     end
+% % else % run
+% %     if isfield(s,'RunParam')
+% %         Param.xml=s.RunParam;
+% %     else %default configuration
+% %         Param.xml.Civ1Bin=fullfile('bin','civ1');
+% %         Param.xml.Civ2Bin=fullfile('bin','civ2');
+% %         Param.xml.FixBin=fullfile('bin','fix_flag');
+% %         Param.xml.PatchBin=fullfile('bin','patch_up');
+% %     end
+% % end
+% % %Param.xml.CivmBin=fullfile('bin','civ_matlab');
+% % 
+% % %% check if the binaries exist : to move in civ_opening
+% % binary_list={};
+% % switch Param.Program
+% %     case 'CivX'
+% %         binary_list={'Civ1Bin','Civ2Bin','PatchBin','FixBin'};
+% %     case 'CivAll'% desactivated option
+% %         binary_list={'Civ'};
+% % %     case 'civ_matlab.sh'% compiled version of civ_matlab 
+% % %         binary_list={'CivmBin'};         
+% % end
+% % for bin_name=binary_list %loop on the list of binaries
+% %     if isfield(Param.xml,bin_name{1})% bin_name{1} =current name in the list
+% %         if ~isunix
+% %         Param.xml.(bin_name{1})=[regexprep(Param.xml.(bin_name{1}),'/','\') '.exe'];
+% %         end
+% %         if exist(Param.xml.(bin_name{1}),'file')
+% %             [path,name,ext]=fileparts(Param.xml.(bin_name{1}));
+% %             currentdir=pwd;
+% %             if isempty(path)
+% %                 path=fileparts(which('civ.m'));
+% %             end
+% %             if exist(path,'dir')
+% %                 cd(path);
+% %                 binpath=pwd;%path of the binary
+% %                 Param.xml.(bin_name{1})=fullfile(binpath,[name ext]);
+% %                 cd(currentdir);
+% %             else
+% %                 errormsg=['path ' path ' for binaries specified in PARAM.xml does not exist'];
+% %                 return
+% %             end          
+% %         else  %look for the full path if the file name has been defined with a relative path in PARAM.xm
+% %             fullname=fullfile(path_civ,Param.xml.(bin_name{1}));
+% %             if exist(fullname,'file')
+% %                 Param.xml.(bin_name{1})=fullname;
+% %             else
+% %                 errormsg=['Binary ' Param.xml.(bin_name{1}) ' specified in PARAM.xml does not exist'];
+% %                 return
+% %             end
+% %         end
+% %     end
+% % end
+% % if strcmp(Param.Program,'civ_matlab.sh')
+% %     if ~exist(fullfile(path_civ,'civ_matlab.sh'),'file')
+% %         errormsg=[{'no file civ_matlab.sh found'}; {'run compile_functions.m to create it by compiling civ_matlab.m'}];
+% %             return
+% %     end
+% % end
+% % 
+% % %% set the list of files and check them
+% % display('checking the files...')
+% % [ref_i,ref_j,errormsg]=find_ref_indices(handles);
+% % if ~isempty(errormsg)
+% %     return
+% % end
+% % [filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,tild,tild,compare,errormsg]=...
+% %     set_civ_filenames(handles,ref_i,ref_j,box_test);
+% % if ~isempty(errormsg)
+% %     return
+% % end
+% % set(handles.civ_input,'UserData',filecell);%store for futur use of status callback
+% % display('files OK, processing...')
+% % 
+% % %% create subfolders for log, cmx, nml, xml, bat
+% % RootBat=fileparts(filecell.nc.civ1{1,1});
+% % switch(Param.Program)
+% %     case {'CivX','CivAll'}
+% % dir_list={'0_BAT','0_CMX','0_LOG'};
+% %     case {'civ_matlab','civ_matlab.sh'}
+% %         dir_list={'0_BAT','0_XML'};
+% % end
+% % for k=1:length(dir_list)
+% %     if ~exist(fullfile(RootBat,dir_list{k}),'dir')
+% %         mkdir(fullfile(RootBat,dir_list{k}));
+% %     end
+% % end
+% 
+% %% get information on input images or movies
+% nbfield=numel(i1_civ1);
+% nbslice=numel(j1_civ1);
+% % if strcmp(Param.Program,'civ_matlab')
+%     if Param.CheckCiv1
+%         [Param.Civ1.FileTypeA,ImageInfoA_civ1,Param.Civ1.ImageA]=get_file_type(filecell.ima1.civ1{1});
+%         [Param.Civ1.FileTypeB,ImageInfoB_civ1,Param.Civ1.ImageB]=get_file_type(filecell.ima2.civ1{1});
+%     end
+%     if Param.CheckCiv2
+%         [Param.Civ2.FileTypeA,ImageInfoA_civ2,Param.Civ2.ImageA]=get_file_type(filecell.ima1.civ2{1});
+%         [Param.Civ2.FileTypeB,ImageInfoB_civ2,Param.Civ2.ImageB]=get_file_type(filecell.ima2.civ2{1});
+%     end
+% % end
+% 
+% %% MAIN LOOP
+% time=get(handles.ImaDoc,'UserData'); %get the set of times
+% TimeUnit=get(handles.TimeUnit,'String');
+% checkframe=strcmp(TimeUnit,'frame');
+% batch_file_list=[];%should be renamed file_list, can be used for xml or bash files
+% NomTypeIma=get(handles.NomType,'String');
+% for ifile=1:nbfield
+%     for j=1:nbslice
+%             
+%         % define output file name
+%         if Param.CheckCiv2==1 || Param.CheckFix2==1 || Param.CheckPatch2==1
+%             Param.OutputFile=filecell.nc.civ2{ifile,j};
+%         else
+%             Param.OutputFile=filecell.nc.civ1{ifile,j};
+%         end
+%         Param.OutputFile=regexprep(Param.OutputFile,'.nc','');
+% 
+%         if Param.CheckCiv1
+%             % read image-dependent parameters          
+%             if ~checkframe% && size(time,1)>=i2_civ1(ifile) && size(time,2)>=j2_civ1(j)
+%                 Param.Civ1.Dt=(time(i2_civ1(ifile)+1,j2_civ1(j)+1)-time(i1_civ1(ifile)+1,j1_civ1(j)+1));
+%             else
+%                 Param.Civ1.Dt=1;
 %             end
-            fprintf(fid, 'exit\nEND_MATLAB\n');
-            fclose(fid);
-            filename_bat=filename_bat2;
-        end
-        
-        switch computer
-            case {'GLNX86','GLNXA64','MACI64'}
-                system(['chmod +x ' filename_bat]);
-        end
-        batch_file_list{length(batch_file_list)+1}=filename_bat; 
-    end
-end
-
-%% start calculation
-%computation on cluster
-%if batch ==3
-switch Param.RunMode,
-    case 'cluster'
-        switch batch_mode
-            case 'sge' %at the moment only psmn ENS Lyon uses it
-                for p=1:length(batch_file_list)
-                    %cmd=['!qsub -p ' pvalue ' -q civ_input.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
-                    cmd=['!qsub -q piv1,piv2,piv3 '...
-                        '-e ' regexprep(batch_file_list{p},'.bat','.errors') ' -o ' regexprep(batch_file_list{p},'.bat','.log ')...
-                        ' -v ' 'LD_LIBRARY_PATH=/home/sjoubaud/matlab_sylvain/civx/lib ' batch_file_list{p}];
-                    display(cmd);eval(cmd);
-                end
-            case 'oar_old' % to remove
-                for p=1:length(batch_file_list)
-                    oar_command=['!oarsub -n CIVX -q nicejob '...
-                        '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
-                        '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
-                    display(oar_command);eval(oar_command);
-                end
-            case 'oar'
-                max_walltime=3600*12; % 12h max
-                oar_modes={'oar-parexec','oar-dispatch','mpilauncher'};
-                text={'Batch processing on servcalcul3 LEGI';...
-                    'Please choose one of the followint modes';...
-                    '* oar-parexec : default and best choice';...
-                    '* oar-dispatch : jobs in a container of several cores';...
-                    '* mpilauncher : one single parallel mpi job using several cores';...
-                    '**********************************'...
-                    };
-                [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
-                    'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
-                switch oar_modes{S}
-                    case 'oar-parexec' %oar-dispatch.pl
-                        if strcmp(Param.Program,'civ_matlab')
-                            ncores=1;
-                            msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
-                        else
-                        answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
-                        ncores=str2double(answer{1});
-                        end
-
-                        extra_oar=answer{2};
-                        walltime_onejob=600;%seconds
-                        filename_joblist=fullfile(RootBat,'job_list.txt');
-                        fid=fopen(filename_joblist,'w');
-                        for p=1:length(batch_file_list)
-                            fprintf(fid,[batch_file_list{p} '\n']);
-                        end
-                        fclose(fid);
-                        oar_command=['oarsub -n CIVX '...
-                            '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
-                            '-l /core=' num2str(ncores) ','...
-                            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,max_walltime/86400),13) ' '...
-                            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
-                            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
-                            extra_oar ' '...
-                            '"oar-parexec -s -f ' filename_joblist ' '...
-                            '-l ' filename_joblist '.log"\n'];
-                        filename_oarcommand=fullfile(RootBat,'oar_command');
-                        fid=fopen(filename_oarcommand,'w');
-                        fprintf(fid,oar_command);
-                        fclose(fid);
-                        fprintf(oar_command);% display in command line
-                        system(oar_command);
-%                         eval(['! . ' filename
-%                             _oarcommand])
-                    case 'oar-dispatch' %oar-dispatch.pl
-                        ncores=str2double(...
-                            inputdlg('Number of cores (max 36)','oarsub parameter',1,{'6'})...
-                            );
-                        walltime_onejob=600;%seconds
-                        filename_joblist=fullfile(RootBat,'job_list.txt');
-                        fid=fopen(filename_joblist,'w');
-                        for p=1:length(batch_file_list)
-                            oar_command=['oarsub -n CIVX '...
-                                '-E ' regexprep(batch_file_list{p},'\.bat\>','.stderr') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.stdout ')...
-                                '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
-                            fprintf(fid,[oar_command '\n']);
-                        end
-                        fclose(fid);
-                        oar_command=['oarsub -t container -n civx-container '...
-                            '-l /core=' num2str(ncores)...
-                            ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13) ' '...
-                            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
-                            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
-                            '"oar-dispatch -f ' filename_joblist '"'];
-                        filename_oarcommand=fullfile(RootBat,'oar_command');
-                        fid=fopen(filename_oarcommand,'w');
-                        fprintf(fid,[oar_command '\n']);
-                        fclose(fid);
-                        display(oar_command);
-                        eval(['! . ' filename_oarcommand])
-                    case 'mpilauncher'
-                        filename_joblist=fullfile(RootBat,'job_list.txt');
-                        fid=fopen(filename_joblist,'w');
-                        
-                        for p=1:length(batch_file_list)
-                            fprintf(fid,[batch_file_list{p} '\n']);
-                        end
-                        fclose(fid)
-                        text_oarscript=[...
-                            '#!/bin/bash \n'...
-                            '#OAR -n Mylauncher \n'...
-                            '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
-                            '#OAR -E ' fullfile(RootBat,'stderrfile.log') ' \n'...
-                            '#OAR -O ' fullfile(RootBat,'stdoutfile.log') ' \n'...
-                            '# ========================================================= \n'...
-                            '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
-                            '# application for coriolis PIV post-processing. \n'...
-                            '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
-                            '# This wrapper assert that the user has the same environment on all the \n'...
-                            '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
-                            '# \n'...
-                            '# REQUIREMENT: \n'...
-                            '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
-                            '# If a different location is used, change the line following the comment "Bidouille" \n'...
-                            '# ========================================================= \n'...
-                            '#   USER should only modify these 2 lines  \n'...
-                            'WORKDIR=' pwd ' \n'...
-                            'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
-                            '# ========================================================= \n'...
-                            '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
-                            'echo "job starting on: "`hostname` \n'...
-                            'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
-                            'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
-                            '#========== Bidouille ============== \n'...
-                            'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
-                            'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
-                            'echo "I run: $CMD"  \n'...
-                            '$CMD \n'...
-                            'echo "job ending" \n'...
-                            ];
-                        %                 oarsub -S ./oar.sub
-                        filename_oarscript=fullfile(RootBat,'oar_command');
-                        fid=fopen(filename_oarscript,'w');
-                        fprintf(fid,[text_oarscript]);
-                        fclose(fid);
-                        eval(['!chmod +x  ' filename_oarscript]);
-                        eval(['!oarsub -S ' filename_oarscript]);
-                end
-        end
-    case {'background','local'}
-        switch Param.Program
-            case {'civ_matlab'}
-                switch Param.RunMode
-                    case 'background'
-                        switch computer
-                            case {'PCWIN','PCWIN64'}
-                                filename_superbat=fullfile(RootBat,'job_list.bat');
-                                fid=fopen(filename_superbat,'w');
-                                if fid==-1
-                                    msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
-                                    return
-                                end
-                                 fprintf(fid,['matlab -automation '...
-                                     '-r "addpath(''' regexprep(path_civ,'\\','\\\\') ''');']);
-                                for p=1:length(batch_file_list)
-                                    fprintf(fid,['run ' regexprep(batch_file_list{p},'\\','\\\\') ';']);
-                                end
-                                 fprintf(fid, 'exit"');
-                                fclose(fid);
-                                dos([filename_superbat ' &']);
-                            case {'GLNX86','GLNXA64','MACI64'} 
-                                filename_superbat=fullfile(RootBat,'job_list.sh');
-                                fid=fopen(filename_superbat,'w');
-                                if fid==-1
-                                    msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
-                                    return
-                                end
-                                fprintf(fid,['#!/bin/bash \n' ...
-                                    '/etc/sysprofile \n'...
-                                    'matlab -nodisplay -nosplash -nojvm -logfile  <<END_MATLAB \n'...
-                                    'addpath(''' path_civ ''');\n']);
-                                for p=1:length(batch_file_list)
-                                    fprintf(fid,['run ' batch_file_list{p} '\n']);
-                                end
-                                fprintf(fid, 'exit\nEND_MATLAB\n');
-                                fclose(fid);
-                                system(['chmod +x ' filename_superbat]);
-                                system([filename_superbat ' &']);
-                        end
-                    case 'local'
-                        for p=1:length(batch_file_list)
-                            fid=fopen(batch_file_list{p});
-                            eval(fscanf(fid,'%s'));
-                            fclose(fid);
-                        end
-                end
-            case {'CivX','CivAll','civ_matlab.sh'}
-                    switch computer
-                        case {'PCWIN','PCWIN64'}
-                            filename_superbat=fullfile(RootBat,'job_list.bat');
-                            fid=fopen(filename_superbat,'w');
-                            if fid==-1
-                                msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
-                                return
-                            end
-                            for p=1:length(batch_file_list)
-                                fprintf(fid,['@call "' regexprep(batch_file_list{p},'\\','\\\\') '"' '\n']);
-                            end
-                            fclose(fid);
-                            system(['chmod +x ' filename_superbat]);
-                        case {'GLNX86','GLNXA64','MACI64'}
-                            filename_superbat=fullfile(RootBat,'job_list.bat');
-                            fid=fopen(filename_superbat,'w');
-                            if fid==-1
-                                msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
-                                return
-                            end
-                            for p=1:length(batch_file_list)
-                                fprintf(fid,['sh ' batch_file_list{p} '\n']);
-                            end
-                            fclose(fid);
-                            system(['chmod +x ' filename_superbat]);
-                    end
-                switch Param.RunMode
-                    case 'background'
-                        system([filename_superbat ' &']);% execute main commmand see what it does in dos ?
-                    case 'local'
-                        system(filename_superbat);
-                end
-        end
-end
-
-
-%% save interface state
-if isfield(filecell,'nc')
-    if isfield(filecell.nc,'civ2')
-        fileresu=filecell.nc.civ2{1,1};
-    else
-        fileresu=filecell.nc.civ1{1,1};
-    end
-end
-[RootPath,SubDir,RootFile]=fileparts_uvmat(fileresu);
-namedoc=fullfile(RootPath,SubDir,RootFile);
-detect=1;
-while detect==1
-    namefigfull=[namedoc '.fig'];
-    hh=dir(namefigfull);
-    if ~isempty(hh)
-        detect=1;
-        namedoc=[namedoc '.0'];
-    else
-        detect=0;
-    end
-end
-Param=rmfield(Param,'status');
-Param=rmfield(Param,'xml');
-t=struct2xml(Param);
-t=set(t,1,'name','Civ');% set the head label
-save(t,[namedoc '.civ.xml']); %save GUI  parameters as xml file
-% saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
-
-%Save info in personal profile (initiate browser next time) TODO
-MenuFile={};
-dir_perso=prefdir;
-profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
-if exist(profil_perso,'file')
-    hh=load (profil_perso);
-      if isfield(hh,'MenuFile')
-          MenuFile=hh.MenuFile;
-      end
-      if isfield(filecell.nc,'civ2')
-          MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
-      else
-           MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
-      end
-      save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
-else
-    MenuFile=filecell.ima1.civ1(1,1);
-    save (profil_perso,'MenuFile')
-end
-
-%------------------------------------------------------------------------
-% --- determine the list of reference indices of processing file
-function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
-%------------------------------------------------------------------------
-errormsg=''; %default error message
-first_i=str2double(get(handles.first_i,'String'));%first index i
-last_i=str2double(get(handles.last_i,'String'));%last index i
-incr_i=str2double(get(handles.incr_i,'String'));% increment
-if isequal(get(handles.first_j,'Visible'),'on')
-    first_j=str2double(get(handles.first_j,'String'));%first index j
-    last_j=str2double(get(handles.last_j,'String'));%last index j
-    incr_j=str2double(get(handles.incr_j,'String'));% increment
-else
-    first_j=1;
-    last_j=1;
-    incr_j=1;
-end
-ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
-ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
-if isnan(first_i)||isnan(first_j)
-    errormsg='first field number not defined';
-elseif isnan(last_i)||isnan(last_j)
-    errormsg='last field number not defined';
-elseif isnan(incr_i)||isnan(incr_j)
-    errormsg='increment in field number not defined';
-elseif last_i < first_i || last_j < first_j 
-    errormsg='last field number must be larger than the first one';
-end
+%             Param.Civ1.Time=((time(i2_civ1(ifile)+1,j2_civ1(j)+1)+time(i1_civ1(ifile)+1,j1_civ1(j)+1))/2);
+%             if strcmp(Param.Program,'CivX')
+%                 Param.Civ1.term_a=num2stra(j1_civ1(j),nom_type_nc);%UTILITE?
+%                 Param.Civ1.term_b=num2stra(j2_civ1(j),nom_type_nc);%
+%             end
+%             Param.Civ1.ImageA=filecell.ima1.civ1{ifile,j};
+%             Param.Civ1.ImageB=filecell.ima2.civ1{ifile,j};
+%             Param.Civ1.ImageBitDepth=ImageInfoA_civ1.BitDepth;
+%             Param.Civ1.ImageWidth=ImageInfoA_civ1.Width;
+%             Param.Civ1.ImageHeight=ImageInfoA_civ1.Height;
+%             if strcmp(NomTypeIma,'*')
+%                 Param.Civ1.FrameIndexA=i1_civ1(ifile);
+%                 Param.Civ1.FrameIndexB=i2_civ1(ifile);
+%             else% case of movies indexed with i, the frame index is then in j
+%                 Param.Civ1.FrameIndexA=j1_civ1(j);
+%                 Param.Civ1.FrameIndexB=j2_civ1(j);
+%             end
+%             % read mask )parameters
+%             if Param.Civ1.CheckMask % the lines below should be changed with the new gui
+%                 if ~exist(Param.Civ1.Mask,'file')
+%                     maskbase=[filecell.filebase '_' Param.Civ1.Mask]; %
+%                     nbslice_mask=str2double(Param.Civ1.Mask(1:end-4)); %
+%                     i1_mask=mod(i1_civ1(ifile)-1,nbslice_mask)+1;
+%                     [RootPathMask,RootFileMask]=fileparts(maskbase);
+%                     Param.Civ1.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
+%                 end
+%             end
+%             % read grid parameters
+%             if Param.Civ1.CheckGrid
+%                 if numel(Param.Civ1.Grid)>=4 && isequal(Param.Civ1.Grid(end-3:end),'grid')
+%                     nbslice_grid=str2double(Param.Civ1.Grid(1:end-4)); %
+%                     if ~isnan(nbslice_grid)
+%                         i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
+%                         Param.Civ1.Grid=[filecell.filebase '_' fullfile_uvmat('','',Param.Civ1.Grid,'.grid','_1',i1_grid)];
+%                         if ~exist(Param.Civ1.GridName,'file')
+%                             errormsg='grid file absent for civ1';
+%                             return
+%                         end
+%                     elseif ~exist(Param.Civ1.Grid,'file')
+%                         errormsg='grid file absent for civ1';
+%                         return
+%                     end
+%                 end
+%             end
+%             
+%         end
+%         
+%         if Param.CheckCiv2==1
+%             Param.Civ2.ImageA=filecell.ima1.civ2{ifile,j};
+%             Param.Civ2.ImageB=filecell.ima2.civ2{ifile,j};          
+%             if ~checkframe %&& size(time,1)>=i2_civ2(ifile) && size(time,2)>=j2_civ2(j)
+%                 Param.Civ2.Dt=time(i2_civ2(ifile)+1,j2_civ2(j)+1)-time(i1_civ2(ifile)+1,j1_civ2(j)+1);
+%             else
+%                 Param.Civ2.Dt=1;
+%             end
+%             Param.Civ2.Time=(time(i2_civ2(ifile)+1,j2_civ2(j)+1)+time(i1_civ2(ifile)+1,j1_civ2(j)+1))/2;
+%             if strcmp(Param.Program,'CivX')
+%                 Param.Civ2.term_a=num2stra(j1_civ2(j),nom_type_nc);
+%                 Param.Civ2.term_b=num2stra(j2_civ2(j),nom_type_nc);
+%             end
+%             Param.Civ2.filename_nc1=filecell.nc.civ1{ifile,j};
+%             Param.Civ2.filename_nc1(end-2:end)=[]; % remove '.nc'
+%             
+%             % mask
+%             if Param.Civ2.CheckMask
+%                 if ~exist(Param.Civ2.Mask,'file')
+%                     maskbase=[filecell.filebase '_' Param.Civ2.Mask]; %
+%                     nbslice_mask=str2double(Param.Civ2.Mask(1:end-4)); %
+%                     i1_mask=mod(i1_civ2(ifile)-1,nbslice_mask)+1;
+%                     [RootPathMask,RootFileMask]=fileparts(maskbase);
+%                     Param.Civ2.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
+%                     %                     Param.Civ2.Mask=name_generator(maskbase,i1_mask,1,'.png','_i');
+%                 end
+%             end
+%             %grid
+%             if Param.Civ2.CheckGrid
+%                 if numel(Param.Civ2.Grid)>=4 && isequal(Param.Civ2.Grid(end-3:end),'grid')
+%                     nbslice_grid=str2double(Param.Civ2.Grid(1:end-4)); %
+%                     if ~isnan(nbslice_grid)
+%                         i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
+%                         Param.Civ2.Grid=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
+%                         %                         Param.Civ2.Grid=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
+%                     end
+%                 end
+%             end
+% 
+%             Param.Civ2.ImageBitDepth=ImageInfoA_civ2.BitDepth;
+%             Param.Civ2.ImageWidth=ImageInfoA_civ2.Width;
+%             Param.Civ2.ImageHeight=ImageInfoA_civ2.Height;
+%             if strcmp(NomTypeIma,'*')
+%                 Param.Civ2.FrameIndexA=i1_civ2(ifile);
+%                 Param.Civ2.FrameIndexB=i2_civ2(ifile);
+%             else% case of movies indexed with i, the frame index is then in j
+%                 Param.Civ2.FrameIndexA=j1_civ2(j);
+%                 Param.Civ2.FrameIndexB=j2_civ2(j);
+%             end
+%         end
+%        
+%         % write the command and eventually the cmx, xml or nml files
+%         cmd=write_cmd(Param);
+%         write_param(Param);
+%               
+%         % create the command file name .m, .bat or .sh depending on the ok option
+%         switch Param.Program
+%             case {'civ_matlab'}
+%                 filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.m');           
+%                 [BatRoot,BatFile]=fileparts(filename_bat);
+%                  BatFile=regexprep(BatFile,'-','__');%transform name to suppress'-' (not valid for .m files)
+%                  filename_bat=[fullfile(BatRoot,BatFile) '.m'];
+%             case {'CivX','CivAll','civ_matlab.sh'}
+%                 switch computer
+%                     case {'PCWIN','PCWIN64'}
+%                         filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.bat');
+%                     case {'GLNX86','GLNXA64','MACI64'}
+%                         filename_bat=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
+%                 end
+%         end
+%         
+%         % print the command in the bat file
+%         [fid,message]=fopen(filename_bat,'w');
+%         if isequal(fid,-1)
+%             errormsg=['creation of .bat file: ' message];
+%             return
+%         end
+%         fprintf(fid,cmd);
+%         fclose(fid);
+%         
+%         % special case for civ_matlab on cluster
+%         if strcmp(Param.Program,'civ_matlab') && strcmp(Param.RunMode,'cluster')
+%             filename_bat2=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_BAT$2$3.sh');
+%             [fid,message]=fopen(filename_bat2,'w');
+%             if isequal(fid,-1)
+%                 errormsg=['creation of .bat file: ' message];
+%                 return
+%             end
+%             fprintf(fid,['#!/bin/bash \n' ...
+%                 '/etc/sysprofile \n'...
+%                 'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
+%                 'addpath(''' path_civ ''');\n']);
+% %             for p=1:length(batch_file_list)
+%                 fprintf(fid,['run ' filename_bat '\n']);
+% %             end
+%             fprintf(fid, 'exit\nEND_MATLAB\n');
+%             fclose(fid);
+%             filename_bat=filename_bat2;
+%         end
+%         
+%         switch computer
+%             case {'GLNX86','GLNXA64','MACI64'}
+%                 system(['chmod +x ' filename_bat]);
+%         end
+%         batch_file_list{length(batch_file_list)+1}=filename_bat; 
+%     end
+% end
+% 
+% %% start calculation
+% %computation on cluster
+% %if batch ==3
+% switch Param.RunMode,
+%     case 'cluster'
+%         switch batch_mode
+%             case 'sge' %at the moment only psmn ENS Lyon uses it
+%                 for p=1:length(batch_file_list)
+%                     %cmd=['!qsub -p ' pvalue ' -q civ_input.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
+%                     cmd=['!qsub -q piv1,piv2,piv3 '...
+%                         '-e ' regexprep(batch_file_list{p},'.bat','.errors') ' -o ' regexprep(batch_file_list{p},'.bat','.log ')...
+%                         ' -v ' 'LD_LIBRARY_PATH=/home/sjoubaud/matlab_sylvain/civx/lib ' batch_file_list{p}];
+%                     display(cmd);eval(cmd);
+%                 end
+%             case 'oar_old' % to remove
+%                 for p=1:length(batch_file_list)
+%                     oar_command=['!oarsub -n CIVX -q nicejob '...
+%                         '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
+%                         '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
+%                     display(oar_command);eval(oar_command);
+%                 end
+%             case 'oar'
+%                 max_walltime=3600*12; % 12h max
+%                 oar_modes={'oar-parexec','oar-dispatch','mpilauncher'};
+%                 text={'Batch processing on servcalcul3 LEGI';...
+%                     'Please choose one of the followint modes';...
+%                     '* oar-parexec : default and best choice';...
+%                     '* oar-dispatch : jobs in a container of several cores';...
+%                     '* mpilauncher : one single parallel mpi job using several cores';...
+%                     '**********************************'...
+%                     };
+%                 [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
+%                     'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
+%                 switch oar_modes{S}
+%                     case 'oar-parexec' %oar-dispatch.pl
+%                         if strcmp(Param.Program,'civ_matlab')
+%                             ncores=1;
+%                             msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
+%                         else
+%                         answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
+%                         ncores=str2double(answer{1});
+%                         end
+% 
+%                         extra_oar=answer{2};
+%                         walltime_onejob=600;%seconds
+%                         filename_joblist=fullfile(RootBat,'job_list.txt');
+%                         fid=fopen(filename_joblist,'w');
+%                         for p=1:length(batch_file_list)
+%                             fprintf(fid,[batch_file_list{p} '\n']);
+%                         end
+%                         fclose(fid);
+%                         oar_command=['oarsub -n CIVX '...
+%                             '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
+%                             '-l /core=' num2str(ncores) ','...
+%                             'walltime=' datestr(min(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,max_walltime/86400),13) ' '...
+%                             '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
+%                             '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
+%                             extra_oar ' '...
+%                             '"oar-parexec -s -f ' filename_joblist ' '...
+%                             '-l ' filename_joblist '.log"\n'];
+%                         filename_oarcommand=fullfile(RootBat,'oar_command');
+%                         fid=fopen(filename_oarcommand,'w');
+%                         fprintf(fid,oar_command);
+%                         fclose(fid);
+%                         fprintf(oar_command);% display in command line
+%                         system(oar_command);
+% %                         eval(['! . ' filename
+% %                             _oarcommand])
+%                     case 'oar-dispatch' %oar-dispatch.pl
+%                         ncores=str2double(...
+%                             inputdlg('Number of cores (max 36)','oarsub parameter',1,{'6'})...
+%                             );
+%                         walltime_onejob=600;%seconds
+%                         filename_joblist=fullfile(RootBat,'job_list.txt');
+%                         fid=fopen(filename_joblist,'w');
+%                         for p=1:length(batch_file_list)
+%                             oar_command=['oarsub -n CIVX '...
+%                                 '-E ' regexprep(batch_file_list{p},'\.bat\>','.stderr') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.stdout ')...
+%                                 '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
+%                             fprintf(fid,[oar_command '\n']);
+%                         end
+%                         fclose(fid);
+%                         oar_command=['oarsub -t container -n civx-container '...
+%                             '-l /core=' num2str(ncores)...
+%                             ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13) ' '...
+%                             '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
+%                             '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
+%                             '"oar-dispatch -f ' filename_joblist '"'];
+%                         filename_oarcommand=fullfile(RootBat,'oar_command');
+%                         fid=fopen(filename_oarcommand,'w');
+%                         fprintf(fid,[oar_command '\n']);
+%                         fclose(fid);
+%                         display(oar_command);
+%                         eval(['! . ' filename_oarcommand])
+%                     case 'mpilauncher'
+%                         filename_joblist=fullfile(RootBat,'job_list.txt');
+%                         fid=fopen(filename_joblist,'w');
+%                         
+%                         for p=1:length(batch_file_list)
+%                             fprintf(fid,[batch_file_list{p} '\n']);
+%                         end
+%                         fclose(fid)
+%                         text_oarscript=[...
+%                             '#!/bin/bash \n'...
+%                             '#OAR -n Mylauncher \n'...
+%                             '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
+%                             '#OAR -E ' fullfile(RootBat,'stderrfile.log') ' \n'...
+%                             '#OAR -O ' fullfile(RootBat,'stdoutfile.log') ' \n'...
+%                             '# ========================================================= \n'...
+%                             '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
+%                             '# application for coriolis PIV post-processing. \n'...
+%                             '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
+%                             '# This wrapper assert that the user has the same environment on all the \n'...
+%                             '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
+%                             '# \n'...
+%                             '# REQUIREMENT: \n'...
+%                             '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
+%                             '# If a different location is used, change the line following the comment "Bidouille" \n'...
+%                             '# ========================================================= \n'...
+%                             '#   USER should only modify these 2 lines  \n'...
+%                             'WORKDIR=' pwd ' \n'...
+%                             'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
+%                             '# ========================================================= \n'...
+%                             '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
+%                             'echo "job starting on: "`hostname` \n'...
+%                             'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
+%                             'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
+%                             '#========== Bidouille ============== \n'...
+%                             'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
+%                             'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
+%                             'echo "I run: $CMD"  \n'...
+%                             '$CMD \n'...
+%                             'echo "job ending" \n'...
+%                             ];
+%                         %                 oarsub -S ./oar.sub
+%                         filename_oarscript=fullfile(RootBat,'oar_command');
+%                         fid=fopen(filename_oarscript,'w');
+%                         fprintf(fid,[text_oarscript]);
+%                         fclose(fid);
+%                         eval(['!chmod +x  ' filename_oarscript]);
+%                         eval(['!oarsub -S ' filename_oarscript]);
+%                 end
+%         end
+%     case {'background','local'}
+%         switch Param.Program
+%             case {'civ_matlab'}
+%                 switch Param.RunMode
+%                     case 'background'
+%                         switch computer
+%                             case {'PCWIN','PCWIN64'}
+%                                 filename_superbat=fullfile(RootBat,'job_list.bat');
+%                                 fid=fopen(filename_superbat,'w');
+%                                 if fid==-1
+%                                     msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
+%                                     return
+%                                 end
+%                                  fprintf(fid,['matlab -automation '...
+%                                      '-r "addpath(''' regexprep(path_civ,'\\','\\\\') ''');']);
+%                                 for p=1:length(batch_file_list)
+%                                     fprintf(fid,['run ' regexprep(batch_file_list{p},'\\','\\\\') ';']);
+%                                 end
+%                                  fprintf(fid, 'exit"');
+%                                 fclose(fid);
+%                                 dos([filename_superbat ' &']);
+%                             case {'GLNX86','GLNXA64','MACI64'} 
+%                                 filename_superbat=fullfile(RootBat,'job_list.sh');
+%                                 fid=fopen(filename_superbat,'w');
+%                                 if fid==-1
+%                                     msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
+%                                     return
+%                                 end
+%                                 fprintf(fid,['#!/bin/bash \n' ...
+%                                     '/etc/sysprofile \n'...
+%                                     'matlab -nodisplay -nosplash -nojvm -logfile  <<END_MATLAB \n'...
+%                                     'addpath(''' path_civ ''');\n']);
+%                                 for p=1:length(batch_file_list)
+%                                     fprintf(fid,['run ' batch_file_list{p} '\n']);
+%                                 end
+%                                 fprintf(fid, 'exit\nEND_MATLAB\n');
+%                                 fclose(fid);
+%                                 system(['chmod +x ' filename_superbat]);
+%                                 system([filename_superbat ' &']);
+%                         end
+%                     case 'local'
+%                         for p=1:length(batch_file_list)
+%                             fid=fopen(batch_file_list{p});
+%                             eval(fscanf(fid,'%s'));
+%                             fclose(fid);
+%                         end
+%                 end
+%             case {'CivX','CivAll','civ_matlab.sh'}
+%                     switch computer
+%                         case {'PCWIN','PCWIN64'}
+%                             filename_superbat=fullfile(RootBat,'job_list.bat');
+%                             fid=fopen(filename_superbat,'w');
+%                             if fid==-1
+%                                 msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
+%                                 return
+%                             end
+%                             for p=1:length(batch_file_list)
+%                                 fprintf(fid,['@call "' regexprep(batch_file_list{p},'\\','\\\\') '"' '\n']);
+%                             end
+%                             fclose(fid);
+%                             system(['chmod +x ' filename_superbat]);
+%                         case {'GLNX86','GLNXA64','MACI64'}
+%                             filename_superbat=fullfile(RootBat,'job_list.bat');
+%                             fid=fopen(filename_superbat,'w');
+%                             if fid==-1
+%                                 msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
+%                                 return
+%                             end
+%                             for p=1:length(batch_file_list)
+%                                 fprintf(fid,['sh ' batch_file_list{p} '\n']);
+%                             end
+%                             fclose(fid);
+%                             system(['chmod +x ' filename_superbat]);
+%                     end
+%                 switch Param.RunMode
+%                     case 'background'
+%                         system([filename_superbat ' &']);% execute main commmand see what it does in dos ?
+%                     case 'local'
+%                         system(filename_superbat);
+%                 end
+%         end
+% end
+% 
+% 
+% %% save interface state
+% if isfield(filecell,'nc')
+%     if isfield(filecell.nc,'civ2')
+%         fileresu=filecell.nc.civ2{1,1};
+%     else
+%         fileresu=filecell.nc.civ1{1,1};
+%     end
+% end
+% [RootPath,SubDir,RootFile]=fileparts_uvmat(fileresu);
+% namedoc=fullfile(RootPath,SubDir,RootFile);
+% detect=1;
+% while detect==1
+%     namefigfull=[namedoc '.fig'];
+%     hh=dir(namefigfull);
+%     if ~isempty(hh)
+%         detect=1;
+%         namedoc=[namedoc '.0'];
+%     else
+%         detect=0;
+%     end
+% end
+% Param=rmfield(Param,'status');
+% Param=rmfield(Param,'xml');
+% t=struct2xml(Param);
+% t=set(t,1,'name','Civ');% set the head label
+% save(t,[namedoc '.civ.xml']); %save GUI  parameters as xml file
+% % saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
+% 
+% %Save info in personal profile (initiate browser next time) TODO
+% MenuFile={};
+% dir_perso=prefdir;
+% profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
+% if exist(profil_perso,'file')
+%     hh=load (profil_perso);
+%       if isfield(hh,'MenuFile')
+%           MenuFile=hh.MenuFile;
+%       end
+%       if isfield(filecell.nc,'civ2')
+%           MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
+%       else
+%            MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
+%       end
+%       save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
+% else
+%     MenuFile=filecell.ima1.civ1(1,1);
+%     save (profil_perso,'MenuFile')
+% end
+
+% %------------------------------------------------------------------------
+% % --- determine the list of reference indices of processing file
+% function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
+% %------------------------------------------------------------------------
+% errormsg=''; %default error message
+% first_i=str2double(get(handles.first_i,'String'));%first index i
+% last_i=str2double(get(handles.last_i,'String'));%last index i
+% incr_i=str2double(get(handles.incr_i,'String'));% increment
+% if isequal(get(handles.first_j,'Visible'),'on')
+%     first_j=str2double(get(handles.first_j,'String'));%first index j
+%     last_j=str2double(get(handles.last_j,'String'));%last index j
+%     incr_j=str2double(get(handles.incr_j,'String'));% increment
+% else
+%     first_j=1;
+%     last_j=1;
+%     incr_j=1;
+% end
+% ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
+% ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
+% if isnan(first_i)||isnan(first_j)
+%     errormsg='first field number not defined';
+% elseif isnan(last_i)||isnan(last_j)
+%     errormsg='last field number not defined';
+% elseif isnan(incr_i)||isnan(incr_j)
+%     errormsg='increment in field number not defined';
+% elseif last_i < first_i || last_j < first_j 
+%     errormsg='last field number must be larger than the first one';
+% end
 
 %------------------------------------------------------------------------
@@ -3821,5 +3764,5 @@
     set(hview_field,'CurrentAxes',hhview_field.PlotAxes)
     ViewData=get(hview_field,'UserData');
-    ViewData.CivHandle=handles.civ_series;% indicate the handle of the civ GUI in view_field
+    ViewData.CivHandle=handles.civ_input;% indicate the handle of the civ GUI in view_field
     ViewData.PlotAxes.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
     ViewData.PlotAxes.X=Grid.Civ1_X; %keep the set of points in memeory
@@ -4009,599 +3952,2 @@
 % --- Executes on button press in TestCiv2.
 function TestCiv2_Callback(hObject, eventdata, handles)
-
-function RootFile_Callback(hObject, eventdata, handles)
-
-function SubDirImages_Callback(hObject, eventdata, handles)
-
-
-
-function errormsg=write_param(Param)
-%------------------------------------------------------------------------
-%pixels per cm and matrix of the image times, read from the .civ_input file by uvmat
-%changes : filename_cmx -> filename ( no extension )
-errormsg='';
-switch Param.Program
-    case 'CivX'
-        if Param.CheckCiv1
-            filename=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_CMX$2$3.civ1.cmx');
-            if isequal(Param.Civ1.Dt,0)
-                Param.Civ1.Dt=1 ;%case of 'displacement' mode
-            end
-            Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'.png','');
-            Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'.png','');
-            [fid,errormsg]=fopen(filename,'w');
-            if isequal(fid,-1)
-                errormsg=['cmd file ' filename ' cannot be created: ' errormsg];
-                return
-            end
-            fprintf(fid,['##############   CMX file' '\n' ]);
-            fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
-            fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
-            fprintf(fid,  ['XX' '\n' ]);
-            if isfield(Param.Civ1,'Mask')
-                fprintf(fid,  ['Mask ' 'y' '\n' ]);
-                fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.Mask,'\\','\\\\') '\n' ]);
-            else
-                fprintf(fid,  ['Mask ' 'n' '\n' ]);
-                fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
-            end
-            fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageWidth) ' ' num2str(Param.Civ1.ImageHeight) '\n' ]);   %VERIFIER CAS GENERAL ?
-            fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.CorrBoxSize(1)) ' ' num2str(Param.Civ1.CorrBoxSize(2)) '\n' ]);
-            fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.SearchBoxSize(1)) ' ' num2str(Param.Civ1.SearchBoxSize(2)) '\n' ]);
-            fprintf(fid,   ['RO ' num2str(Param.Civ1.CorrSmooth) '\n' ]);
-            if isfield(Param.Civ1,'Grid')
-                fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
-            else
-                fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
-            end
-            fprintf(fid,   ['XX 1.0' '\n' ]);
-            fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.Time) '\n' ]);
-            fprintf(fid,  ['PixCmXY ' '1' ' ' '1' '\n' ]);
-            fprintf(fid,  ['XX 1' '\n' ]);
-            fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.SearchBoxShift(1)) ' '  num2str(Param.Civ1.SearchBoxShift(2)) '\n' ]);
-            if isfield(Param.Civ1,'Grid')
-                fprintf(fid,  ['Grid ' 'y' '\n' ]);
-                fprintf(fid,   ['GridName ' regexprep(Param.Civ1.Grid,'\\','\\\\') '\n' ]);
-            else
-                fprintf(fid,  ['Grid ' 'n' '\n' ]);
-                fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
-            end
-            fprintf(fid,   ['XX 85' '\n' ]);
-            fprintf(fid,   ['XX 1.0' '\n' ]);
-            fprintf(fid,   ['XX 1.0' '\n' ]);
-            fprintf(fid,   ['Hart 1' '\n' ]);
-            fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
-            fprintf(fid,   ['Deformation 0' '\n' ]);
-            fprintf(fid,  ['CorrelationMin 0' '\n' ]);
-            fprintf(fid,   ['IntensityMin 0' '\n' ]);
-            if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
-                fprintf(fid,  ['SeuilImage n' '\n' ]);
-                fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
-            else% Image threshold  activated
-                if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
-                    Param.Civ1.MaxIma=2^Param.Civ1.ImageBitDepth;%take the max image value as upper bound by default
-                end
-                fprintf(fid,  ['SeuilImage y' '\n' ]);
-                fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
-            end
-            fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
-            fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
-            fclose(fid);
-        end
-        
-        if Param.CheckCiv2
-            filename=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_CMX$2$3.civ2.cmx');
-
-            if isequal(Param.Civ2.Dt,'0')
-                Param.Civ2.Dt='1' ;%case of 'displacement' mode
-            end
-            Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'.png','');
-            Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'.png','');% bug : .png appears two times ?
-            [fid,errormsg]=fopen(filename,'w');
-            if isequal(fid,-1)
-                return
-            end
-            fprintf(fid,['##############   CMX file' '\n' ]);
-            fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
-            fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
-            fprintf(fid,  ['XX' '\n' ]);
-            if isfield(Param.Civ2,'Mask')
-                fprintf(fid,  ['Mask ' 'y' '\n' ]);
-                fprintf(fid,  ['MaskName ' regexprep(Param.Civ2.Mask,'\\','\\\\') '\n' ]);
-            else
-                fprintf(fid,  ['Mask ' 'n' '\n' ]);
-                fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
-            end
-            % fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
-            % fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
-            fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageWidth) ' ' num2str(Param.Civ2.ImageHeight) '\n' ]);
-            % fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
-            fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n' ]);
-            fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n']);
-            fprintf(fid, ['RO ' num2str(Param.Civ2.CorrSmooth) '\n']);
-            if isfield(Param.Civ2,'Grid')
-                fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
-            else
-                fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
-            end
-            % fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
-            fprintf(fid, ['XX 1.0' '\n' ]);
-            fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.Time) '\n' ]);
-            fprintf(fid, ['PixCmXY ' '1' ' ' '1' '\n' ]);
-            fprintf(fid, ['XX 1' '\n' ]);
-            fprintf(fid, 'ShiftXY 0 0\n');
-            if isfield(Param.Civ2,'Grid')
-                fprintf(fid,  ['Grid ' 'y' '\n' ]);
-                fprintf(fid,   ['GridName ' regexprep(Param.Civ2.Grid,'\\','\\\\') '\n' ]);
-            else
-                fprintf(fid,  ['Grid ' 'n' '\n' ]);
-                fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
-            end
-            % fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
-            % fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
-            fprintf(fid, ['XX 85' '\n' ]);
-            fprintf(fid, ['XX 1.0' '\n' ]);
-            fprintf(fid, ['XX 1.0' '\n' ]);
-            fprintf(fid, ['Hart 1' '\n' ]);
-            fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
-            fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
-            fprintf(fid,  ['CorrelationMin 0' '\n' ]);
-            fprintf(fid,   ['IntensityMin 0' '\n' ]);
-            
-            if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
-                fprintf(fid,  ['SeuilImage n' '\n' ]);
-                fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
-            else% Image threshold  activated
-                if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
-                    Param.Civ2.MaxIma=2^Param.Civ2.ImageBitDepth;%take the max image value as upper bound by default
-                end
-                fprintf(fid,  ['SeuilImage y' '\n' ]);
-                fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
-            end
-            fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
-            fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
-            fclose(fid);
-        end
-    case {'civ_matlab','civ_matlab.sh'}
-        filename=regexprep(Param.OutputFile,'(.+)([/\\])(.+$)','$1$20_XML$2$3.xml');
-        fileattrib(fileparts(filename),'+w +x','o g');% set writting access
-        save(struct2xml(Param),filename);
-end
-
-
-function cmd=write_cmd(Param)
-
-% initiate system command
-cmd=[];
-
-switch Param.Program
-    case 'CivX'
-        if isunix % check: necessaire aussi en RUN?
-            cmd=[cmd '#!/bin/bash \n'...
-                '#$ -cwd \n'...
-                'hostname && date \n'...
-                'umask 002 \n'];%allow writting access to created files for user group
-        end
-    case 'CivAll'
-        if isunix % check: necessaire aussi en RUN?
-            cmd=[cmd '#!/bin/bash \n'...
-                '#$ -cwd \n'...
-                'hostname && date \n'...
-                'umask 002 \n'];%allow writting access to created files for user group
-        end
-end
-
-filename=regexprep(Param.OutputFile,'.nc','');
-
-if Param.CheckCiv1
-    switch Param.Program
-        case 'CivX'
-            if(isunix) %unix (or Mac) system
-                cmd=[cmd 'cp -f ' regexprep(filename,'(.+)/(.+$)','$1/0_CMX/$2.civ1.cmx ') regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')...% the cmx file gives the name to the nc file
-                    Param.xml.Civ1Bin ' -f ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx >') regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.civ1.log \n')... % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
-                    'rm ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')];
-            else %Windows system
-                filename=regexprep(filename,'\\','\\\\');
-                cmd=['copy /Y ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_CMX\\\\$2.civ1.cmx" ') regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')...
-                    '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\') '" -f ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" > ')...
-                    regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_LOG\\\\$2.civ1.log" \n')... % redirect standard output to the log file
-                    'del ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')];
-            end
-        case 'CivAll'
-            CivAllCmd=[CivAllCmd ' civ1 '];
-            str=CIV1_CMD_Unified(filecell.nc.civ1{ifile,j},'',Param.Civ1);
-            fieldnames=fields(str);
-            [CivAllxml,uid_civ1]=add(CivAllxml,1,'element','civ1');
-            for ilist=1:length(fieldnames)
-                val=eval(['str.' fieldnames{ilist}]);
-                if ischar(val)
-                    [CivAllxml,uid_t]=add(CivAllxml,uid_civ1,'element',fieldnames{ilist});
-                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
-                end
-            end
-    end
-end
-
-if Param.CheckFix1
-    switch Param.Program
-        case 'CivX'
-            cmd=[cmd...
-                cmd_fix(Param,'Fix1') '\n'];
-        case 'CivAll'%to abandon
-            fix1.inputFileName=filecell.nc.civ1{ifile,j} ;
-            fix1.fi1=num2str(param.fix1.flagindex1(1));
-            fix1.fi2=num2str(param.fix1.flagindex1(2));
-            fix1.fi3=num2str(param.fix1.flagindex1(3));
-            fix1.threshC=num2str(param.fix1.thresh_vecC1);
-            fix1.threshV=num2str(param.fix1.thresh_vel1);
-            fieldnames=fields(fix1);
-            [CivAllxml,uid_fix1]=add(CivAllxml,1,'element','fix1');
-            for ilist=1:length(fieldnames)
-                val=eval(['fix1.' fieldnames{ilist}]);
-                if ischar(val)
-                    [CivAllxml,uid_t]=add(CivAllxml,uid_fix1,'element',fieldnames{ilist});
-                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
-                end
-            end
-            CivAllCmd=[CivAllCmd ' fix1 '];
-    end
-end
-
-
-%CheckPatch1
-if Param.CheckPatch1
-    switch Param.Program
-        case 'CivX'
-            cmd=[cmd...
-                cmd_patch(Param,'Patch1') '\n'];
-        case 'CivAll'
-            patch1.inputFileName=filecell.nc.civ1{ifile,j} ;
-            patch1.nopt=subdomain_patch1;
-            patch1.maxdiff=thresh_patch1;
-            patch1.ro=rho_patch1;
-            test_grid=get(handles.get_gridpatch1,'Value');
-            if test_grid
-                patch1.gridflag='y';
-                gridname=get(handles.grid_patch1,'String');
-                if isequal(gridname(end-3:end),'grid')
-                    nbslice_grid=str2double(gridname(1:end-4)); %
-                    if ~isnan(nbslice_grid)
-                        i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
-                        patch1.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
-                        %                                 patch1.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
-                        if ~exist(patch1.gridPatch,'file')
-                            errormsg='grid file absent for patch1';
-                            return
-                        end
-                    elseif exist(gridname,'file')
-                        patch1.gridPatch=gridname;
-                    else
-                        errormsg='grid file absent for patch1';
-                        return
-                    end
-                end
-            else
-                patch1.gridPatch='none';
-                patch1.gridflag='n';
-                patch1.m=nx_patch1;
-                patch1.n=ny_patch1;
-            end
-            patch1.convectFlow='n';
-            fieldnames=fields(patch1);
-            [CivAllxml,uid_patch1]=add(CivAllxml,1,'element','patch1');
-            for ilist=1:length(fieldnames)
-                val=eval(['patch1.' fieldnames{ilist}]);
-                if ischar(val)
-                    [CivAllxml,uid_t]=add(CivAllxml,uid_patch1,'element',fieldnames{ilist});
-                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
-                end
-            end
-            CivAllCmd=[CivAllCmd ' patch1 '];
-    end
-end
-
-if Param.CheckCiv2
-    switch Param.Program
-        case 'CivX'
-            if(isunix)
-                cmd=[cmd 'cp -f '  regexprep(filename,'(.+)/(.+$)','$1/0_CMX/$2.civ2.cmx ') regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')...
-                    Param.xml.Civ2Bin ' -f ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx >') regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.civ2.log \n')...% redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
-                    'rm ' regexprep(filename,'(.+)/(.+$)','$1/$2.cmx \n')];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
-            else
-                filename=regexprep(Param.OutputFile,'.nc','');
-                filename=regexprep(filename,'\\','\\\\');
-                cmd=[cmd 'copy /Y ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_CMX\\\\$2.civ2.cmx" ') regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')...
-                    '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" > ')...
-                     regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\0_LOG\\\\$2.civ2.log" \n')... % redirect standard output to the log file
-                    'del ' regexprep(filename,'(.+)\\\\(.+$)','"$1\\\\$2.cmx" \n')];                       
-            end
-                 
-        case 'CivAll'
-            CivAllCmd=[CivAllCmd ' civ2 '];
-            str=CIV2_CMD_Unified(filecell.nc.civ2{ifile,j},'',Param.Civ2);
-            fieldnames=fields(str);
-            [CivAllxml,uid_civ2]=add(CivAllxml,1,'element','civ2');
-            for ilist=1:length(fieldnames)
-                val=eval(['str.' fieldnames{ilist}]);
-                if ischar(val)
-                    [CivAllxml,uid_t]=add(CivAllxml,uid_civ2,'element',fieldnames{ilist});
-                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
-                end
-            end
-    end
-end
-
-% CheckFix2
-if Param.CheckFix2==1
-    switch Param.Program
-        case 'CivX'
-            cmd=[cmd...
-                cmd_fix(Param,'Fix2') '\n'];
-        case 'CivAll'
-            fix2.inputFileName=filecell.nc.civ2{ifile,j} ;
-            fix2.fi1=num2str(flagindex2(1));
-            fix2.fi2=num2str(flagindex2(2));
-            fix2.fi3=num2str(flagindex2(3));
-            fix2.threshC=num2str(thresh_vec2C);
-            fix2.threshV=num2str(thresh_vel2);
-            fieldnames=fields(fix2);
-            [CivAllxml,uid_fix2]=add(CivAllxml,1,'element','fix2');
-            for ilist=1:length(fieldnames)
-                val=eval(['fix2.' fieldnames{ilist}]);
-                if ischar(val)
-                    [CivAllxml,uid_t]=add(CivAllxml,uid_fix2,'element',fieldnames{ilist});
-                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
-                end
-            end
-            CivAllCmd=[CivAllCmd ' fix2 '];
-    end
-end
-
-%CheckPatch2
-if Param.CheckPatch2==1
-    
-    switch Param.Program
-        
-        case 'CivX'
-            cmd=[cmd...
-                cmd_patch(Param,'Patch2') '\n'];
-        case 'CivAll'
-            patch2.inputFileName=filecell.nc.civ1{ifile,j} ;
-            patch2.nopt=subdomain_patch2;
-            patch2.maxdiff=thresh_patch2;
-            patch2.ro=rho_patch2;
-            test_grid=get(handles.get_gridpatch2,'Value');
-            if test_grid
-                patch2.gridflag='y';
-                gridname=get(handles.grid_patch2,'String');
-                if isequal(gridname(end-3:end),'grid')
-                    nbslice_grid=str2double(gridname(1:end-4)); %
-                    if ~isnan(nbslice_grid)
-                        i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
-                        patch2.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
-                        %                                 patch2.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
-                        if ~exist(patch2.gridPatch,'file')
-                            errormsg='grid file absent for patch2';
-                            return
-                        end
-                    elseif exist(gridname,'file')
-                        patch2.gridPatch=gridname;
-                    else
-                        errormsg='grid file absent for patch2';
-                        return
-                    end
-                end
-            else
-                patch2.gridPatch='none';
-                patch2.gridflag='n';
-                patch2.m=nx_patch2;
-                patch2.n=ny_patch2;
-            end
-            patch2.convectFlow='n';
-            fieldnames=fields(patch2);
-            [CivAllxml,uid_patch2]=add(CivAllxml,1,'element','patch2');
-            for ilist=1:length(fieldnames)
-                val=eval(['patch2.' fieldnames{ilist}]);
-                if ischar(val)
-                    [CivAllxml,uid_t]=add(CivAllxml,uid_patch2,'element',fieldnames{ilist});
-                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
-                end
-            end
-            CivAllCmd=[CivAllCmd ' patch2 '];
-    end
-end
-
-switch Param.Program
-    case 'CivAll'
-        save(CivAllxml,[Param.OutputFile '.xml']);
-        cmd=[cmd sparam.CivBin ' -f ' Param.OutputFile '.xml '  CivAllCmd ' >' Param.OutputFile '.log' '\n'];
-    case 'civ_matlab'
-                    switch computer
-                        case {'PCWIN','PCWIN64'}                     
-                            filename=regexprep(filename,'\\','\\\\');% add '\' so that '\' are left as characters
-                                    cmd=['civ_matlab(''' regexprep(filename,'(.+)([/\\])(.+$)','$1$20_XML\\$2$3.xml') ''','''...
-            filename '.nc'');'];
-                        case {'GLNX86','GLNXA64','MACI64'}
-                                    cmd=['civ_matlab(''' regexprep(filename,'(.+)([/\\])(.+$)','$1$20_XML$2$3.xml') ''','''...
-            filename '.nc'');'];
-                    end
-
-        
-    case 'civ_matlab.sh'
-        CivmBin=fullfile(fileparts(which('civ')),'civ_matlab.sh'); %path to the source directory of uvmat
-        switch computer
-            case {'PCWIN','PCWIN64'}
-                filename=regexprep(filename,'\\','\\\\');% add '\' so that '\' are left as characters
-                % TODO launch command in DOS
-            case {'GLNX86','GLNXA64','MACI64'}
-                cmd=['#!/bin/bash \n '...
-                    '#$ -cwd \n '...
-                    'hostname && date \n '...
-                    'umask 002 \n'...
-                    CivmBin ' ' Param.xml.RunTime ' ' regexprep(filename,'(.+)([/\\])(.+$)','$1$20_XML$2$3.xml') ' ' Param.OutputFile '.nc'];%allow writting access to created files for user group
-        end
-end    
-    
-
-function cmd=cmd_fix(Param,fixname)
-%%
-switch fixname
-    case 'Fix1'
-        fi2_value=num2str(Param.(fixname).CheckF2);
-        filename=regexprep(Param.OutputFile,'.nc','');
-    case 'Fix2'
-        fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
-        filename=regexprep(Param.OutputFile,'.nc','');        
-end
-
-% filename=regexprep(Param.(fixname).OutFileName,'.nc','');
-MaskName_string='';%default
-MaxVel_string='';%default
-if ~isempty(Param.(fixname).MinVel)
-    MaxVel_string=[' -threshV ' num2str(Param.(fixname).MinVel)];
-end
-if isunix
-    cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
-        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
-        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
-        ' >' regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.')  lower(fixname) '.log 2>&1'];
-else
-    cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
-        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
-        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
-        ' > "' regexprep(filename,'(\w+)\\(\w+$)','$1\\0_LOG\\$2.') lower(fixname) '.log"'];
-    cmd=regexprep(cmd,'\\','\\\\');
-end
-
-
-function cmd=cmd_patch(Param,patchname)
-%% ------------------------------------------------------------------------
-switch patchname
-    case 'Patch1'
-        filename=regexprep(Param.OutputFile,'.nc','');
-    case 'Patch2'
-        filename=regexprep(Param.OutputFile,'.nc','');        
-end
-% filename=regexprep(Param.(patchname).OutFileName,'.nc','');
-if isunix
-    cmd=[Param.xml.PatchBin...
-        ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
-        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
-        ' -nopt ' num2str(Param.(patchname).SubDomainSize) ...
-        '  > ' regexprep(filename,'(.+)/(.+$)','$1/0_LOG/$2.')  lower(patchname) '.log 2>&1']; % redirect standard output to the log file
-else
-    cmd=['"' Param.xml.PatchBin...
-        '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
-        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
-        ' -nopt ' num2str(Param.(patchname).SubDomainSize)...
-        '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
-    cmd=regexprep(cmd,'\\','\\\\');
-end
-
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-% USELESS FUNCTIONS BELOW HERE,  TO CLEAN
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-%------------------------------------------------------------------------
-% --- CheckCiv1  Unified: TO ABADON
-function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
-%------------------------------------------------------------------------
-%pixels per cm and matrix of the image times, read from the .civ_input file by uvmat
-%global CivBin%name of the executable for checkciv1 calculation
-
-civ1.image1=par.ImageA;
-civ1.image2=par.ImageB;
-civ1.imageSize_X=par.npx;
-civ1.imageSize_Y=par.npy;
-civ1.outputFileName=[filename '.nc'];
-civ1.correlationBoxesSize_X=par.ibx;
-civ1.correlationBoxesSize_Y=par.iby;
-civ1.searchBoxesSize_X=par.isx;
-civ1.searchBoxesSize_Y=par.isy;
-civ1.globalShift_X=par.shiftx;
-civ1.globalShift_Y=par.shifty;
-civ1.ro=par.rho;
-civ1.hart='y';
-if isequal(par.gridflag,'y')
-    civ1.grid=par.gridname;
-else
-    civ1.grid='n';
-    civ1.gridSpacing_X=par.dx;
-    civ1.gridSpacing_Y=par.dy;
-end
-if isequal(par.maskflag,'y')
-    civ1.mask=par.maskname;
-end
-civ1.dt=par.Dt;
-civ1.unit='pixel';
-civ1.absolut_time_T0=par.Time;
-civ1.pixcmx='1';
-civ1.pixcmy='1';
-civ1.convectFlow='n';
-
-xml_civ1_parameters=civ1;
-
-%------------------------------------------------------------------------
-% --- CheckCiv2  Unified: TO ABADON
-function civ2=CIV2_CMD_Unified(filename,namelog,par)
-%------------------------------------------------------------------------
-%pixels per cm and matrix of the image times, read from the .civ_input file by uvmat
-%global CivBin%name of the executable for checkciv1 calculation
-
-filename=regexprep(filename,'.nc','');
-
-civ2.image1=par.ImageA;
-civ2.image2=par.ImageB;
-civ2.imageSize_X=par.npx;
-civ2.imageSize_Y=par.npy;
-civ2.inputFileName=[par.filename_nc1 '.nc'];
-civ2.outputFileName=[filename '.nc'];
-civ2.correlationBoxesSize_X=par.ibx;
-civ2.correlationBoxesSize_Y=par.iby;
-civ2.ro=par.rho;
-%checkciv2.decimalShift=par.CheckDecimal;
-%checkciv2.CheckDeformation=par.CheckDeformation;
-if isequal(par.decimal,'1')
-    civ2.decimalShift='y';
-else
-    civ2.decimalShift='n';
-end
-if isequal(par.deformation,'1')
-    civ2.deformation='y';
-else
-    civ2.deformation='n';
-end
-if isequal(par.gridflag,'y')
-    civ2.grid=par.gridname;
-else
-    civ2.grid='n';
-    civ2.gridSpacing_X=par.dx;
-    civ2.gridSpacing_Y=par.dy;
-end
-civ2.gridSpacing_X='10';
-civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
-if isequal(par.maskflag,'y')
-    civ2.mask=par.maskname;
-else
-    civ2.mask='n';
-end
-civ2.dt=par.Dt;
-civ2.unit='pixel';
-civ2.absolut_time_T0=par.Time;
-civ2.pixcmx='1';
-civ2.pixcmy='1';
-civ2.convectFlow='n';
-
-
-% --- Executes on selection change in RunMode.
-function RunMode_Callback(hObject, eventdata, handles)
-
-
-function nb_field2_Callback(hObject, eventdata, handles)
-
-
-function last_j_Callback(hObject, eventdata, handles)
-
-
-function last_i_Callback(hObject, eventdata, handles)
Index: /trunk/src/series/civ_series.m
===================================================================
--- /trunk/src/series/civ_series.m	(revision 597)
+++ /trunk/src/series/civ_series.m	(revision 598)
@@ -1,56 +1,59 @@
-%'merge_proj': concatene several fields from series, can project them on a regular grid in phys coordinates
+%'civ_series': PIV function activated by the general GUI series
+% --- call the sub-functions:
+%   civ: PIV function itself
+%   fix: removes false vectors after detection by various criteria
+%   filter_tps: make interpolation-smoothing 
 %------------------------------------------------------------------------
-% function ParamOut=merge_proj(Param)
-%------------------------------------------------------------------------
-%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
 %
 %OUTPUT
-% ParamOut: sets options in the GUI series.fig needed for the function
+% Data=structure containing the PIV results and information on the processing parameters
+% errormsg=error message char string, default=''
+% resul_conv: image inter-correlation function for the last grid point (used for tests)
 %
 %INPUT:
-% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
-% In batch mode, Param is the name of the corresponding xml file containing the same information
-% when Param.Action.RUN=0 (as activated when the current Action is selected
-% in series), the function ouput paramOut set the activation of the needed GUI elements
+% Param: input images and processing parameters
+%     .Civ1: for civ1
+%     .Fix1: 
+%     .Patch1: 
+%     .Civ2: for civ2
+%     .Fix2: 
+%     .Patch2:
+% ncfile: name of a netcdf file to be created for the result (extension .nc)
 %
-% Param contains the elements:(use the menu bar command 'export/GUI config' in series to 
-% see the current structure Param)
-%    .InputTable: cell of input file names, (several lines for multiple input)
-%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
-%    .OutputSubDir: name of the subdirectory for data outputs
-%    .OutputDirExt: directory extension for data outputs
-%    .Action: .ActionName: name of the current activated function
-%             .ActionPath:   path of the current activated function
-%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
-%             .RUN =0 for GUI input, =1 for function activation
-%             .RunMode='local','background', 'cluster': type of function  use
-%             
-%    .IndexRange: set the file or frame indices on which the action must be performed
-%    .FieldTransform: .TransformName: name of the selected transform function
-%                     .TransformPath:   path  of the selected transform function
-%    .InputFields: sub structure describing the input fields withfields
-%              .FieldName: name(s) of the field
-%              .VelType: velocity type
-%              .FieldName_1: name of the second field in case of two input series
-%              .VelType_1: velocity type of the second field in case of two input series
-%              .Coord_y: name of y coordinate variable
-%              .Coord_x: name of x coordinate variable
-%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%civ_series
-
-function ParamOut=civ_series(Param)
-
+%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
+%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+%     This is part of the toolbox UVMAT.
+% 
+%     UVMAT is free software; you can redistribute it and/or modify
+%     it under the terms of the GNU General Public License as published by
+%     the Free Software Foundation; either version 2 of the License, or
+%     (at your option) any later version.
+% 
+%     UVMAT is distributed in the hope that it will be useful,
+%     but WITHOUT ANY WARRANTY; without even the implied warranty of
+%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
+%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+
+function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
+errormsg='';
+path_series=fileparts(which('series'));
+addpath(fullfile(path_series,'series'))
 %% set the input elements needed on the GUI series when the action is selected in the menu ActionName
 if isstruct(Param) && isequal(Param.Action.RUN,0)
-    ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
-    ParamOut.WholeIndexRange='off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
-    ParamOut.NbSlice='off'; ...%nbre of slices ('off' by default)
-    ParamOut.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
-    ParamOut.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
-    ParamOut.FieldTransform = 'off';...%can use a transform function
-    ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
-    ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
-    ParamOut.OutputDirExt='.civ';%set the output dir extension
-return
+    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
+    Data.Program=mfilename;
+    Data.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
+        Data.WholeIndexRange='off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
+        Data.NbSlice='off'; ...%nbre of slices ('off' by default)
+        Data.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
+        Data.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
+        Data.FieldTransform = 'off';...%can use a transform function
+        Data.ProjObject='off';...%can use projection object(option 'off'/'on',
+        Data.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
+        Data.OutputDirExt='.civ';%set the output dir extension
+    return
 end
 
@@ -63,342 +66,897 @@
     checkrun=0;
 end
-
-ParamOut=Param; %default output
-if ~isfield(Param,'InputFields')
-    Param.InputFields.FieldName='';
-end
-OutputSubDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
-
-%% root input file type
-RootPath=Param.InputTable(:,1);
-RootFile=Param.InputTable(:,3);
-SubDir=Param.InputTable(:,2);
-NomType=Param.InputTable(:,4);
-FileExt=Param.InputTable(:,5);
-[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
-%%%%%%%%%%%%
-% The cell array filecell is the list of input file names, while
-% filecell{iview,fileindex}:
-%        iview: line in the table corresponding to a given file series
-%        fileindex: file index within  the file series, 
-% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j 
-% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
-%%%%%%%%%%%%
-NbSlice=1;%default
-if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
-    NbSlice=Param.IndexRange.NbSlice;
-end
-nbview=numel(i1_series);%number of input file series (lines in InputTable)
-nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
-nbfield_i=size(i1_series{1},2); %nb of fields for the i index
-nbfield=nbfield_j*nbfield_i; %total number of fields
-nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices) 
-nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
-
-%determine the file type on each line from the first input file 
-ImageTypeOptions={'image','multimage','mmreader','video'};
-NcTypeOptions={'netcdf','civx','civdata'};
-for iview=1:nbview
-    if ~exist(filecell{iview,1}','file')
-        displ_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
-        return
-    end
-    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
-    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
-    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
-    if ~isempty(j1_series{iview})
-        frame_index{iview}=j1_series{iview};
+OutputDir=[Param.OutputSubDir Param.OutputDirExt];
+
+Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
+Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
+Data.Program='civ_series';
+Data.CivStage=0;%default
+ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
+ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
+mask='';
+maskname='';%default
+check_civx=0;%default
+check_civ1=0;%default
+check_patch1=0;%default
+
+% case of input Param set by an xml file (batch mode)
+if ischar(Param)
+    Param=xml2struct(Param); %if Param is the name of an xml file, read this file as a Matlab structure
+end
+
+RootPath=Param.InputTable{1,1};
+RootFile=Param.InputTable{1,3};
+SubDir=Param.InputTable{1,2};
+NomType=Param.InputTable{1,4};
+FileExt=Param.InputTable{1,5};
+PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
+PairCiv2='';
+if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
+    PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;
+end
+
+% option use with GUI series
+NbField=1;
+MovieObject_A=[];
+if isfield(Param,'InputTable')
+    MaxIndex=cell2mat(Param.IndexRange.MaxIndex);
+    MinIndex=cell2mat(Param.IndexRange.MinIndex);
+    [filecell,i_series,tild,j_series]=get_file_series(Param);
+    [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
+        find_pair_indices(PairCiv1,i_series{1},j_series{1},MinIndex,MaxIndex);
+    if ~isempty(PairCiv2)
+        [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
+            find_pair_indices(PairCiv2,i_series{1},j_series{1},MinIndex,MaxIndex);
+        check_bounds=check_bounds | check_bounds_Civ2;
+    end
+    i1_series_Civ1=i1_series_Civ1(~check_bounds);
+    i2_series_Civ1=i2_series_Civ1(~check_bounds);
+    j1_series_Civ1=j1_series_Civ1(~check_bounds);
+    j2_series_Civ1=j2_series_Civ1(~check_bounds);
+    if ~isempty(j1_series_Civ1)
+        FrameIndex_A_Civ1=j1_series_Civ1;
+        FrameIndex_B_Civ1=j2_series_Civ1;
     else
-        frame_index{iview}=i1_series{iview};
-    end
-end
-
-
-%% calibration data and timing: read the ImaDoc files
-[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
-if size(time,1)>1
-    diff_time=max(max(diff(time)));
-    if diff_time>0 
-        displ_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)],checkrun)
-    end   
-end
-
-%% coordinate transform or other user defined transform
-
-%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
- % EDIT FROM HERE
-
-%% check the validity of  input file types
-if CheckImage{1}
-    FileExtOut='.png'; % write result as .png images for image inputs
-elseif CheckNc{1}
-    FileExtOut='.nc';% write result as .nc files for netcdf inputs
-else
-    displ_uvmat('ERROR',['invalid file type input ' FileType{1}],checkrun)
-    return
-end
-for iview=1:nbview
-	if ~isequal(CheckImage{iview},CheckImage{1})||~isequal(CheckNc{iview},CheckNc{1})
-        displ_uvmat('ERROR','input set of input series: need  either netcdf either image series',checkrun)
-    return
-    end
-end
-NomTypeOut=NomType;% output file index will indicate the first and last ref index in the series
-% if checkrun==1
-%     ParamOut.Specific=[];%no specific parameter
-%     return %stop here for interactive input (option Param.Specific='?')
-% end
-
-%% Set field names and velocity types
-%use Param.InputFields for all views
-
-%% MAIN LOOP ON SLICES
-%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
-
-index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
-nbfiles=0;
-nbmissing=0;
-
-%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
-%TODO: call civ_matlab
-for index=index_slice
-    if checkrun
-        stopstate=get(Param.RUNHandle,'BusyAction');
-        update_waitbar(Param.WaitbarHandle,index/nbfield)
-    else
-        stopstate='queue';
-    end
-    if ~isequal(stopstate,'queue')% enable STOP command
-        return
-    end
-    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
-    Data=cell(1,nbview);%initiate the set Data
-    nbtime=0;
-    for iview=1:nbview
-        %% reading input file(s)
-        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
-        if ~isempty(errormsg)
-            errormsg=['merge_proj/read_field/' errormsg];
-            display(errormsg)
-            break
-        end
-        timeread(iview)=0;
-        if isfield(Data{iview},'Time')
-            timeread(iview)=Data{iview}.Time;
-            nbtime=nbtime+1;
-        end
-        if ~isempty(NbSlice_calib)
-            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
-        end
+        FrameIndex_A_Civ1=i1_series_Civ1;
+        FrameIndex_B_Civ1=i2_series_Civ1;
+    end
+    if ~isempty(PairCiv2)
+        i1_series_Civ2=i1_series_Civ2(~check_bounds);
+        i2_series_Civ2=i2_series_Civ2(~check_bounds);
+        j1_series_Civ2=j1_series_Civ2(~check_bounds);
+        j2_series_Civ2=j2_series_Civ2(~check_bounds);
+        if ~isempty(j1_series_Civ2)
+            FrameIndex_A_Civ2=j1_series_Civ2;
+            FrameIndex_B_Civ2=j2_series_Civ2;
+        else
+            FrameIndex_A_Civ2=i1_series_Civ2;
+            FrameIndex_B_Civ2=i2_series_Civ2;
+        end
+    end
+    
+    NbField=numel(i1_series_Civ1);
+    ImageTypeOptions={'image','multimage','mmreader','video'};
+    [FileType_A,FileInfo,MovieObject_A]=get_file_type(filecell{1,1});
+    FileType_B=FileType_A;
+    MovieObject_B=MovieObject_A;
+    if size(filecell,1)>=2 && ~strcmp(filecell{1,1},filecell{2,1})
+        [FileType_B,FileInfo,MovieObject_B]=get_file_type(filecell{2,1});
+        CheckImage_B=~isempty(find(strcmp(FileType,ImageTypeOptions)));% =1 for images
+    end
+end
+
+%%%%% MAIN LOOP %%%%%%
+
+MovieObject_A=[];
+for ifield=1:NbField
+    
+    %% Civ1
+    if isfield (Param.ActionInput,'Civ1')
+        par_civ1=Param.ActionInput.Civ1;
+        if isfield(par_civ1,'reverse_pair')% A REVOIR
+            if par_civ1.reverse_pair
+                if ischar(par_civ1.ImageB)
+                    temp=par_civ1.ImageA;
+                    par_civ1.ImageA=imread(par_civ1.ImageB);
+                end
+                if ischar(temp)
+                    par_civ1.ImageB=imread(temp);
+                end
+            end
+        else
+            %         if ~isfield(Param.Civ1,'ImageA')
+            ImageName_A=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
+            [par_civ1.ImageA,MovieObject_A] = read_image(ImageName_A,FileType_A,MovieObject_A,FrameIndex_A_Civ1);
+            %         elseif ischar(Param.Civ1.ImageA)
+            %             Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'''','\');
+            %             [par_civ1.ImageA,VideoObject] = read_image(Param.Civ1.ImageA,par_civ1.FileTypeA,MovieObject_A,par_civ1.FrameIndexA);
+            %         end
+            %         if ~isfield(Param.Civ1,'ImageB')
+            ImageName_B=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
+            [par_civ1.ImageB,MovieObject_B] = read_image(ImageName_B,FileType_B,MovieObject_B,FrameIndex_B_Civ1);
+            %         elseif isfield(Param.Civ1,'ImageB')&& ischar(Param.Civ1.ImageB)
+            %              Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'''','\');
+            %              if strcmp(Param.Civ1.ImageA,Param.Civ1.ImageB)% use the same movie object
+            %                  [par_civ1.ImageB,VideoObject] = read_image(Param.Civ1.ImageB,par_civ1.FileTypeB,VideoObject,par_civ1.FrameIndexB);
+            %              else
+            %             [par_civ1.ImageB,VideoObject] = read_image(Param.Civ1.ImageB,par_civ1.FileTypeB,par_civ1.ImageB,par_civ1.FrameIndexB);
+            %              end
+            %         end
+        end
+        ncfile=fullfile_uvmat(RootPath,OutputDir,RootFile,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
+            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
+        par_civ1.ImageWidth=FileInfo.Width;
+        par_civ1.ImageHeight=FileInfo.Height;
+        list_param=(fieldnames(Param.ActionInput.Civ1))';
+        Civ1_param=list_param;%default
         
-        %% transform the input field (e.g; phys) if requested
-        if ~isempty(transform_fct)
-            if nargin(transform_fct)>=2
-                Data{iview}=transform_fct(Data{iview},XmlData{iview});
-            else
-                Data{iview}=transform_fct(Data{iview});
+        %set the values of all the global attributes in list_param
+        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
+        for ilist=1:length(list_param)
+            Civ1_param{ilist}=['Civ1_' list_param{ilist}];
+            Data.(['Civ1_' list_param{ilist}])=Param.ActionInput.Civ1.(list_param{ilist});
+        end
+        Data.CivStage=1;
+        
+        % set the list of variables
+        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
+        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
+        Data.VarAttribute{1}.Role='coord_x';
+        Data.VarAttribute{2}.Role='coord_y';
+        Data.VarAttribute{3}.Role='vector_x';
+        Data.VarAttribute{4}.Role='vector_y';
+        Data.VarAttribute{5}.Role='warnflag';
+        
+        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
+            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
+            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
+            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
+            for ivol=1:NbSlice
+                % caluclate velocity data (y and v in indices, reverse to y component)
+                [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
+                if ~isempty(errormsg)
+                    return
+                end
+                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
+                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
+                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
+                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
+                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
+                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
+                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
             end
-        end
-        
-        %% check whether tps is needed, then calculate tps coefficients if needed
-        check_tps=0;
-        if isfield(Param.InputFields,'FieldName')
-            if ischar(Param.InputFields.FieldName)
-                Param.InputFields.FieldName={Param.InputFields.FieldName};
-            end
-        else
-            Param.InputFields.FieldName={};
-        end
-        for ilist=1:numel(Param.InputFields.FieldName)
-            switch Param.InputFields.FieldName{ilist}
-                case {'vort','div','strain'}
-                    check_tps=1;
-            end
-        end
-        
-        %% calculate tps coeff if needed
-        check_proj_tps= ~isempty(Param.ProjObject)&& strcmp(Param.ProjObject.ProjMode,'filter')&&~isfield(Data{iview},'Coord_tps');
-        Data{iview}=tps_coeff_field(Data{iview},check_proj_tps);
-        
-        %% projection on object (gridded plane)
-        if Param.CheckObject
-            [Data{iview},errormsg]=proj_field(Data{iview},Param.ProjObject);
+        else %usual PIV
+            % caluclate velocity data (y and v in indices, reverse to y component)
+            [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
             if ~isempty(errormsg)
-                displ_uvmat('ERROR',['error in merge_proge/proj_field: ' errormsg],checkrun)
                 return
             end
-        end
-    end
-    %----------END LOOP ON VIEWS----------------------
+            Data.Civ1_X=reshape(xtable,[],1);
+            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
+            Data.Civ1_U=reshape(utable,[],1);
+            Data.Civ1_V=reshape(-vtable,[],1);
+            Data.Civ1_C=reshape(ctable,[],1);
+            Data.Civ1_F=reshape(F,[],1);
+        end
+    else
+        if exist('ncfile','var')
+            CivFile=ncfile;
+        elseif isfield(Param.Patch1,'CivFile')
+            CivFile=Param.Patch1.CivFile;
+        end
+        Data=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
+        if isfield(Data,'Txt')
+            errormsg=Data.Txt;
+            return
+        end
+        if ~isempty(Data.absolut_time_T0')%read civx file
+            check_civx=1;% test for old civx data format
+            [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
+        else
+            Data=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
+        end
+    end
     
-    %% merge the nbview fields
-    MergeData=merge_field(Data);
-    if isfield(MergeData,'Txt')
-        displ_uvmat('ERROR',MergeData.Txt,checkrun)
+    %% Fix1
+    if isfield (Param.ActionInput,'Fix1')
+        ListFixParam=fieldnames(Param.ActionInput.Fix1);
+        for ilist=1:length(ListFixParam)
+            ParamName=ListFixParam{ilist};
+            ListName=['Fix1_' ParamName];
+            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
+            eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
+        end
+        if check_civx
+            if ~isfield(Data,'fix')
+                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
+                Data.fix=1;
+                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
+                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
+            end
+            Data.vec_FixFlag=fix(Param.ActionInput.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
+        else
+            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
+            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
+            nbvar=length(Data.ListVarName);
+            Data.VarAttribute{nbvar}.Role='errorflag';
+            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
+            Data.CivStage=2;
+        end
+    end
+    %% Patch1
+    if isfield (Param.ActionInput,'Patch1')
+        if check_civx
+            errormsg='Civ Matlab input needed for patch';
+            return
+        end
+        
+        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
+        Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
+        Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
+        Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
+        nbvar=length(Data.ListVarName);
+        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
+        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
+            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
+        Data.VarAttribute{nbvar+1}.Role='vector_x';
+        Data.VarAttribute{nbvar+2}.Role='vector_y';
+        Data.VarAttribute{nbvar+5}.Role='coord_tps';
+        Data.VarAttribute{nbvar+6}.Role='vector_x';
+        Data.VarAttribute{nbvar+7}.Role='vector_y';
+        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
+        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
+        if isfield(Data,'Civ1_FF')
+            ind_good=find(Data.Civ1_FF==0);
+        else
+            ind_good=1:numel(Data.Civ1_X);
+        end
+        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
+            filter_tps([Data.Civ1_X(ind_good) Data.Civ1_Y(ind_good)],Data.Civ1_U(ind_good),Data.Civ1_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
+        Data.Civ1_U_smooth(ind_good)=Ures;
+        Data.Civ1_V_smooth(ind_good)=Vres;
+        Data.Civ1_FF(ind_good)=FFres;
+        Data.CivStage=3;
+    end
+    
+    %% Civ2
+    if isfield (Param.ActionInput,'Civ2')
+        par_civ2=Param.ActionInput.Civ2;
+        par_civ2.ImageA=[];
+        par_civ2.ImageB=[];
+        %         if ~isfield(Param.Civ1,'ImageA')
+        ImageName_A_Civ2=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i1_series_Civ2(ifield),[],j1_series_Civ2(ifield));
+
+        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1,FrameIndex_A_Civ2)
+            par_civ2.ImageA=par_civ1.ImageA;
+        else
+            [par_civ2.ImageA,MovieObject_A] = read_image(ImageName_A,FileType_A,MovieObject_A,FrameIndex_A_Civ2);
+        end
+        ImageName_B_Civ2=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i2_series_Civ2(ifield),[],j2_series_Civ2(ifield));
+        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1,FrameIndex_B_Civ2)
+            par_civ2.ImageB=par_civ1.ImageB;
+        else
+            [par_civ2.ImageB,MovieObject_B] = read_image(ImageName_B,FileType_B,MovieObject_B,FrameIndex_B_Civ2);
+        end     
+        
+        ncfile=fullfile_uvmat(RootPath,OutputDir,RootFile,'.nc',NomTypeNc,i1_series_Civ2(ifield),i2_series_Civ2(ifield),...
+            j1_series_Civ2(ifield),j2_series_Civ2(ifield));
+        par_civ2.ImageWidth=FileInfo.Width;
+        par_civ2.ImageHeight=FileInfo.Height;
+        
+        if isfield(par_civ2,'Grid')% grid points set as input file
+            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
+                par_civ2.Grid=dlmread(par_civ2.Grid);
+                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
+            end
+        else% automatic grid
+            minix=floor(par_civ2.Dx/2)-0.5;
+            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
+            miniy=floor(par_civ2.Dy/2)-0.5;
+            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
+            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
+            par_civ2.Grid(:,1)=reshape(GridX,[],1);
+            par_civ2.Grid(:,2)=reshape(GridY,[],1);
+        end
+        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
+        Shifty=zeros(size(par_civ2.Grid,1),1);
+        nbval=zeros(size(par_civ2.Grid,1),1);
+        if par_civ2.CheckDeformation
+            DUDX=zeros(size(par_civ2.Grid,1),1);
+            DUDY=zeros(size(par_civ2.Grid,1),1);
+            DVDX=zeros(size(par_civ2.Grid,1),1);
+            DVDY=zeros(size(par_civ2.Grid,1),1);
+        end
+        NbSubDomain=size(Data.Civ1_SubRange,3);
+        % get the guess from patch1
+        for isub=1:NbSubDomain
+            nbvec_sub=Data.Civ1_NbCentres(isub);
+            ind_sel=find(GridX>=Data.Civ1_SubRange(1,1,isub) & GridX<=Data.Civ1_SubRange(1,2,isub) & GridY>=Data.Civ1_SubRange(2,1,isub) & GridY<=Data.Civ1_SubRange(2,2,isub));
+            epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
+            ctrs=Data.Civ1_Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
+            nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
+            EM = tps_eval(epoints,ctrs);
+            Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
+            Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
+            if par_civ2.CheckDeformation
+                [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
+                DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
+                DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
+                DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
+                DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
+            end
+        end
+        mask='';
+        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
+            mask=imread(par_civ2.Mask);
+        end
+        ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
+        iby2=ceil(par_civ2.CorrBoxSize(2)/2);
+        %     isx2=ibx2+4;% search ara +-4 pixels around the guess
+        %     isy2=iby2+4;
+        par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
+        par_civ2.SearchBoxSize(2)=2*iby2+9;
+        %par_civ2.SearchBoxSize(1)=2*isx2+1;
+        %par_civ2.SearchBoxSize(2)=2*isy2+1;
+        par_civ2.SearchBoxShift=[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
+        par_civ2.Grid=[GridX(nbval>=1)-par_civ2.SearchBoxShift(:,1)/2 GridY(nbval>=1)-par_civ2.SearchBoxShift(:,2)/2];% grid taken at the extrapolated origin of the displacement vectors
+        if par_civ2.CheckDeformation
+            par_civ2.DUDX=DUDX./nbval;
+            par_civ2.DUDY=DUDY./nbval;
+            par_civ2.DVDX=DVDX./nbval;
+            par_civ2.DVDY=DVDY./nbval;
+        end
+        % caluclate velocity data (y and v in indices, reverse to y component)
+        [xtable ytable utable vtable ctable F] = civ (par_civ2);
+
+        list_param=(fieldnames(Param.ActionInput.Civ2))';
+        list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
+        for ilist=1:length(list_remove)
+            index=strcmp(list_remove{ilist},list_param);
+            if ~isempty(find(index,1))
+                list_param(index)=[];
+            end
+        end
+        for ilist=1:length(list_param)
+            Civ2_param{ilist}=['Civ2_' list_param{ilist}];
+            eval(['Data.Civ2_' list_param{ilist} '=Param.ActionInput.Civ2.' list_param{ilist} ';'])
+        end
+        if isfield(Data,'Civ2_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
+            Data.Civ1_gridname='';
+        end
+        if isfield(Data,'Civ2_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
+            Data.Civ2_maskname='';
+        end
+        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param {'Civ2_Time','Civ2_Dt'}];
+        nbvar=numel(Data.ListVarName);
+        Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_F','Civ2_C'}];%  cell array containing the names of the fields to record
+        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
+        Data.VarAttribute{nbvar+1}.Role='coord_x';
+        Data.VarAttribute{nbvar+2}.Role='coord_y';
+        Data.VarAttribute{nbvar+3}.Role='vector_x';
+        Data.VarAttribute{nbvar+4}.Role='vector_y';
+        Data.VarAttribute{nbvar+5}.Role='warnflag';
+        Data.Civ2_X=reshape(xtable,[],1);
+        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
+        Data.Civ2_U=reshape(utable,[],1);
+        Data.Civ2_V=reshape(-vtable,[],1);
+        Data.Civ2_C=reshape(ctable,[],1);
+        Data.Civ2_F=reshape(F,[],1);
+        Data.CivStage=Data.CivStage+1;
+    end
+    
+    %% Fix2
+    if isfield (Param.ActionInput,'Fix2')
+        ListFixParam=fieldnames(Param.ActionInput.Fix2);
+        for ilist=1:length(ListFixParam)
+            ParamName=ListFixParam{ilist};
+            ListName=['Fix2_' ParamName];
+            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
+            eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
+        end
+        if check_civx
+            if ~isfield(Data,'fix2')
+                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
+                Data.fix2=1;
+                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
+                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
+            end
+            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
+        else
+            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
+            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
+            nbvar=length(Data.ListVarName);
+            Data.VarAttribute{nbvar}.Role='errorflag';
+            Data.Civ2_FF=fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
+            Data.CivStage=Data.CivStage+1;
+        end
+        
+    end
+    
+    %% Patch2
+    if isfield (Param.ActionInput,'Patch2')
+        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
+        Data.Patch2_FieldSmooth=Param.ActionInput.Patch2.FieldSmooth;
+        Data.Patch2_MaxDiff=Param.ActionInput.Patch2.MaxDiff;
+        Data.Patch2_SubDomainSize=Param.ActionInput.Patch2.SubDomainSize;
+        nbvar=length(Data.ListVarName);
+        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
+        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
+            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
+        
+        Data.VarAttribute{nbvar+1}.Role='vector_x';
+        Data.VarAttribute{nbvar+2}.Role='vector_y';
+        Data.VarAttribute{nbvar+5}.Role='coord_tps';
+        Data.VarAttribute{nbvar+6}.Role='vector_x';
+        Data.VarAttribute{nbvar+7}.Role='vector_y';
+        Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
+        Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
+        if isfield(Data,'Civ2_FF')
+            ind_good=find(Data.Civ2_FF==0);
+        else
+            ind_good=1:numel(Data.Civ2_X);
+        end
+        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
+            filter_tps([Data.Civ2_X(ind_good) Data.Civ2_Y(ind_good)],Data.Civ2_U(ind_good),Data.Civ2_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
+        Data.Civ2_U_smooth(ind_good)=Ures;
+        Data.Civ2_V_smooth(ind_good)=Vres;
+        Data.Civ2_FF(ind_good)=FFres;
+        Data.CivStage=Data.CivStage+1;
+    end
+    
+    %% write result in a netcdf file if requested
+    if exist('ncfile','var')
+        errormsg=struct2nc(ncfile,Data);
+        if isempty(errormsg)
+            disp([ncfile ' written'])
+        else
+            disp(errormsg)
+        end
+    end
+end
+
+% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
+%--------------------------------------------------------------------------
+% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
+%
+% OUTPUT:
+% xtable: set of x coordinates
+% ytable: set of y coordiantes
+% utable: set of u displacements (along x)
+% vtable: set of v displacements (along y)
+% ctable: max image correlation for each vector
+% typevector: set of flags, =1 for good, =0 for NaN vectors
+%
+%INPUT:
+% par_civ: structure of input parameters, with fields:
+%  .CorrBoxSize
+%  .SearchBoxSize
+%  .SearchBoxShift
+%  .ImageHeight
+%  .ImageWidth
+%  .Dx, Dy
+%  .Grid
+%  .Mask
+%  .MinIma
+%  .MaxIma
+%  .image1:first image (matrix)
+% image2: second image (matrix)
+% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
+% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
+% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
+% step: mesh of the measurement points (in px)
+% subpixfinder=1 or 2 controls the curve fitting of the image correlation
+% mask: =[] for no mask
+% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
+function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
+%this funtion performs the DCC PIV analysis. Recent window-deformation
+%methods perform better and will maybe be implemented in the future.
+
+%% prepare measurement grid
+if isfield(par_civ,'Grid')% grid points set as input 
+    if ischar(par_civ.Grid)%read the drid file if the input is a file name
+        par_civ.Grid=dlmread(par_civ.Grid);
+        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
+    end
+else% automatic grid
+    minix=floor(par_civ.Dx/2)-0.5;
+    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
+    miniy=floor(par_civ.Dy/2)-0.5;
+    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
+    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
+    par_civ.Grid(:,1)=reshape(GridX,[],1);
+    par_civ.Grid(:,2)=reshape(GridY,[],1);
+end
+nbvec=size(par_civ.Grid,1);
+
+%% prepare correlation and search boxes 
+ibx2=ceil(par_civ.CorrBoxSize(1)/2);
+iby2=ceil(par_civ.CorrBoxSize(2)/2);
+isx2=ceil(par_civ.SearchBoxSize(1)/2);
+isy2=ceil(par_civ.SearchBoxSize(2)/2);
+shiftx=round(par_civ.SearchBoxShift(:,1));
+shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
+if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
+    shiftx=shiftx*ones(nbvec,1);
+    shifty=shifty*ones(nbvec,1);
+end
+
+%% Default output
+xtable=par_civ.Grid(:,1);
+ytable=par_civ.Grid(:,2);
+utable=zeros(nbvec,1);
+vtable=zeros(nbvec,1);
+ctable=zeros(nbvec,1);
+F=zeros(nbvec,1);
+result_conv=[];
+errormsg='';
+
+%% prepare mask
+if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
+    if strcmp(par_civ.Mask,'all')
+        return    % get the grid only, no civ calculation
+    elseif ischar(par_civ.Mask)
+        par_civ.Mask=imread(par_civ.Mask);
+    end
+end
+check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
+check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
+
+% %% prepare images
+% if isfield(par_civ,'reverse_pair')
+%     if par_civ.reverse_pair
+%         if ischar(par_civ.ImageB)
+%             temp=par_civ.ImageA;
+%             par_civ.ImageA=imread(par_civ.ImageB);
+%         end
+%         if ischar(temp)
+%             par_civ.ImageB=imread(temp);
+%         end
+%     end
+% else
+%     if ischar(par_civ.ImageA)
+%         par_civ.ImageA=imread(par_civ.ImageA);
+%     end
+%     if ischar(par_civ.ImageB)
+%         par_civ.ImageB=imread(par_civ.ImageB);
+%     end
+% end
+par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
+par_civ.ImageB=sum(double(par_civ.ImageB),3);
+[npy_ima npx_ima]=size(par_civ.ImageA);
+if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
+    errormsg='image pair with unequal size';
+    return
+end
+
+%% Apply mask
+    % Convention for mask IDEAS TO IMPLEMENT ?
+    % mask >200 : velocity calculated
+    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
+    % 150>=mask >100: velocity not calculated, nor interpolated
+    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries) 
+    %  20>=mask: velocity=0
+checkmask=0;
+MinA=min(min(par_civ.ImageA));
+MinB=min(min(par_civ.ImageB));
+if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
+   checkmask=1;
+   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
+        errormsg='mask must be an image with the same size as the images';
         return
-    end
+   end
+  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
+    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
+    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
+    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
+end
+
+%% compute image correlations: MAINLOOP on velocity vectors
+corrmax=0;
+sum_square=1;% default
+mesh=1;% default
+CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
+if CheckDecimal
+    mesh=0.2;%mesh in pixels for subpixel image interpolation
+    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
+end
+% vector=[0 0];%default
+for ivec=1:nbvec
+    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
+    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
+    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
+    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
+    %               jref+shifty(ivec)-isy2<1||jref+shifty(ivec)+isy2>par_civ.ImageHeight|| iref+shiftx(ivec)-isx2<1 || iref+shiftx(ivec)+isx2>par_civ.ImageWidth  % we are outside the image
+    %             F(ivec)=3;
+    %         else
+    F(ivec)=0;
+    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
+    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
+    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
+    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
+    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
+    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
+    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
+    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
+    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
+    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
     
-    % time of the merged field:
-    if ~isempty(time)% time defined from ImaDoc
-        timeread=time(:,index);
-    end
-    timeread=mean(timeread);
-    
-    % generating the name of the merged field
-    i1=i1_series{iview}(index);
-    if ~isempty(i2_series{iview})
-        i2=i2_series{iview}(index);
+    image1_crop(check1_y,check1_x)=par_civ.ImageA(subrange1_y(check1_y),subrange1_x(check1_x));%extract a subimage (correlation box) from image A
+    image2_crop(check2_y,check2_x)=par_civ.ImageB(subrange2_y(check2_y),subrange2_x(check2_x));%extract a larger subimage (search box) from image B
+    image1_mean=mean(mean(image1_crop));
+    image2_mean=mean(mean(image2_crop));
+    %threshold on image minimum
+    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
+        F(ivec)=3;
+    end
+    %threshold on image maximum
+    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
+        F(ivec)=3;
+    end
+    %         end
+    if F(ivec)~=3
+        image1_crop=image1_crop-image1_mean;%substract the mean
+        image2_crop=image2_crop-image2_mean;
+        if CheckDecimal
+            xi=(1:mesh:size(image1_crop,2));
+            yi=(1:mesh:size(image1_crop,1))';
+            if CheckDeformation
+                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
+                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
+                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
+                image1_crop=interp2(image1_crop,XIant,YIant);
+            else
+                image1_crop=interp2(image1_crop,xi,yi);
+            end
+            xi=(1:mesh:size(image2_crop,2));
+            yi=(1:mesh:size(image2_crop,1))';
+            image2_crop=interp2(image2_crop,xi,yi);
+        end
+        sum_square=sum(sum(image1_crop.*image1_crop));
+        %reference: Oliver Pust, PIV: Direct Cross-Correlation
+        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
+        corrmax= max(max(result_conv));
+        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
+        %Find the correlation max, at 255
+        [y,x] = find(result_conv==255,1);
+        if ~isempty(y) && ~isempty(x)
+            try
+                if par_civ.CorrSmooth==1
+                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
+                elseif par_civ.CorrSmooth==2
+                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
+                end
+                utable(ivec)=vector(1)*mesh+shiftx(ivec);
+                vtable(ivec)=vector(2)*mesh+shifty(ivec);
+                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
+                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
+                iref=round(xtable(ivec));% image index for the middle of the vector
+                jref=round(ytable(ivec));
+                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
+                    utable(ivec)=0;
+                    vtable(ivec)=0;
+                    F(ivec)=3;
+                end
+                ctable(ivec)=corrmax/sum_square;% correlation value
+            catch ME
+                F(ivec)=3;
+            end
+        else
+            F(ivec)=3;
+        end
+    end
+end
+result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
+
+%------------------------------------------------------------------------
+% --- Find the maximum of the correlation function after interpolation
+function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
+%------------------------------------------------------------------------
+vector=[0 0]; %default
+F=0;
+[npy,npx]=size(result_conv);
+
+% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
+    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
+    %http://urapiv.wordpress.com
+    peaky = y;
+    if y <= npy-1 && y >= 1
+        f0 = log(result_conv(y,x));
+        f1 = real(log(result_conv(y-1,x)));
+        f2 = real(log(result_conv(y+1,x)));
+        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
     else
-        i2=i1;
-    end
-    j1=1;
-    j2=1;
-    if ~isempty(j1_series{iview})
-        j1=j1_series{iview}(index);
-        if ~isempty(j2_series{iview})
-            j2=j2_series{iview}(index);
-        else
-            j2=j1;
-        end
-    end
-    OutputFile=fullfile_uvmat(RootPath{1},OutputSubDir,RootFile{1},FileExtOut,NomType{1},i1,i2,j1,j2);
-    
-    % recording the merged field
-    if CheckImage{1}    %in case of input images an image is produced
-        if isa(MergeData.A,'uint8')
-            bitdepth=8;
-        elseif isa(MergeData.A,'uint16')
-            bitdepth=16;
-        end
-        imwrite(MergeData.A,OutputFile,'BitDepth',bitdepth);
-        %write xml calibration file
-        siz=size(MergeData.A);
-        npy=siz(1);
-        npx=siz(2);
-        if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
-            Rangx=MergeData.VarAttribute{1}.Coord_2;
-            Rangy=MergeData.VarAttribute{1}.Coord_1;
-        elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
-            Rangx=[MergeData.AX(1) MergeData.AX(end)];
-            Rangy=[MergeData.AY(1) MergeData.AY(end)];
-        else
-            Rangx=[0.5 npx-0.5];
-            Rangy=[npy-0.5 0.5];%default
-        end
-        pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
-        pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
-        T_x=-pxcmx*Rangx(1)+0.5;
-        T_y=-pxcmy*Rangy(2)+0.5;
-        GeometryCal.focal=1;
-        GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
-        GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
-        ImaDoc.GeometryCalib=GeometryCal;
-        %             t=struct2xml(ImaDoc);
-        %             t=set(t,1,'name','ImaDoc');
-        %             save(t,[filebase_merge '.xml'])
-        %             display([filebase_merge '.xml saved'])
+        F=-2; % warning flag for vector truncated by the limited search box
+    end
+    peakx=x;
+    if x <= npx-1 && x >= 1
+        f0 = log(result_conv(y,x));
+        f1 = real(log(result_conv(y,x-1)));
+        f2 = real(log(result_conv(y,x+1)));
+        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
     else
-        MergeData.ListGlobalAttribute={'Conventions','Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};
-        MergeData.Conventions='uvmat';
-        MergeData.nb_coord=2;
-        MergeData.nb_dim=2;
-        dt=[];
-        if isfield(Data{1},'dt')&& isnumeric(Data{1}.dt)
-            dt=Data{1}.dt;
-        end
-        for iview =2:numel(Data)
-            if ~(isfield(Data{iview},'dt')&& isequal(Data{iview}.dt,dt))
-                dt=[];%dt not the same for all fields
-            end
-        end
-        if isempty(dt)
-            MergeData.ListGlobalAttribute(6)=[];
-        else
-            MergeData.dt=dt;
-        end
-        MergeData.Time=timeread;
-        error=struct2nc(OutputFile,MergeData);%save result file
-        if isempty(error)
-            display(['output file ' OutputFile ' written'])
-        else
-            display(error)
-        end
-    end
-end
-
-%'merge_field': concatene fields
+        F=-2; % warning flag for vector truncated by the limited search box
+    end
+    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
+
 %------------------------------------------------------------------------
-function MergeData=merge_field(Data)
-%% default output
-if isempty(Data)||~iscell(Data)
-    MergeData=[];
-    return
-end
-MergeData=Data{1};%default
-error=0;
-nbview=length(Data);
-if nbview==1
-    return
-end
-
-%% group the variables (fields of 'Data') in cells of variables with the same dimensions
-[CellVarIndex,NbDim,VarTypeCell]=find_field_cells(Data{1});
-%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
-% CellVarIndex=cells of variable index arrays
-for icell=1:length(CellVarIndex)
-    if NbDim(icell)==1
-        continue
-    end
-    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
-    VarType=VarTypeCell{icell};
-    ivar_X=VarType.coord_x;
-    ivar_Y=VarType.coord_y;
-    ivar_FF=VarType.errorflag;
-    if isempty(ivar_X)
-        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
+% --- Find the maximum of the correlation function after interpolation
+function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
+%------------------------------------------------------------------------
+vector=[0 0]; %default
+F=-2;
+peaky=y;
+peakx=x;
+[npy,npx]=size(result_conv);
+if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
+    F=0;
+    for i=-1:1
+        for j=-1:1
+            %following 15 lines based on
+            %H. Nobach ï¿œ M. Honkanen (2005)
+            %Two-dimensional Gaussian regression for sub-pixel displacement
+            %estimation in particle image velocimetry or particle position
+            %estimation in particle tracking velocimetry
+            %Experiments in Fluids (2005) 38: 511ï¿œ515
+            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
+            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
+            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
+            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
+            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
+        end
+    end
+    c10=(1/6)*sum(sum(c10));
+    c01=(1/6)*sum(sum(c01));
+    c11=(1/4)*sum(sum(c11));
+    c20=(1/6)*sum(sum(c20));
+    c02=(1/6)*sum(sum(c02)); 
+    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
+    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
+    if abs(deltax)<1
+        peakx=x+deltax;
+    end
+    if abs(deltay)<1
+        peaky=y+deltay;
+    end
+end
+vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
+
+%'RUN_FIX': function for fixing velocity fields:
+%-----------------------------------------------
+% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
+%
+%filename: name of the netcdf file (used as input and output)
+%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
+    %.vel_type='civ1' or 'civ2';
+    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
+    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
+%flagindex: flag specifying which values of vec_f are removed: 
+        % if flagindex(1)=1: vec_f=-2 vectors are removed
+        % if flagindex(2)=1: vec_f=3 vectors are removed
+        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
+%iter=1 for civ1 fields and iter=2 for civ2 fields
+%thresh_vecC: threshold in the image correlation vec_C
+%flag_mask: =1 mask used to remove vectors (0 else)
+%maskname: name of the mask image file for fix
+%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
+%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
+%fileref: .nc file name for a reference velocity (='': refrence 0 used)
+%fieldref: 'civ1','filter1'...feld used in fileref
+
+function FF=fix(Param,F,C,U,V,X,Y)
+FF=zeros(size(F));%default
+
+%criterium on warn flags
+FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
+FlagVal=[-2 2 3 4];
+for iflag=1:numel(FlagName)
+    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
+        FF=(FF==1| F==FlagVal(iflag));
+    end
+end
+%criterium on correlation values
+if isfield (Param,'MinCorr')
+    FF=FF==1 | C<Param.MinCorr;
+end
+if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
+    Umod= U.*U+V.*V;
+    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
+        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
+    end
+    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
+        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
+    end
+end
+
+
+%------------------------------------------------------------------------
+% --- determine the list of index pairs of processing file
+function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
+    find_pair_indices(str_civ,i_series,j_series,MinIndex,MaxIndex)
+%------------------------------------------------------------------------
+i1_series=i_series;% set of first image numbers
+i2_series=i_series;
+j1_series=ones(size(i_series));% set of first image numbers
+j2_series=ones(size(i_series));
+check_bounds=false(size(i_series));
+r=regexp(str_civ,'^\D(?<ind>[i|j])= (?<num1>\d+)\|(?<num2>\d+)','names');
+if ~isempty(r)
+    mode=['D' r.ind];
+    ind1=str2num(r.num1);
+    ind2=str2num(r.num2);
+else
+    mode='burst';
+    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
+    if ~isempty(r)
+        NomTypeNc='_1ab';
     else
-        if length(ivar_Y)~=1
-                displ_uvmat('ERROR','y coordinate missing in proj_field.m',checkrun)
-                return
-        end
-        test_grid=0;
-    end
-    %case of input fields with unstructured coordinates
-    if ~test_grid
-        for ivar=VarIndex
-            VarName=MergeData.ListVarName{ivar};
-            for iview=1:nbview
-                MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
-            end
-        end
-    %case of fields defined on a structured  grid 
-    else  
-        testFF=0;
-        for iview=2:nbview
-            for ivar=VarIndex
-                VarName=MergeData.ListVarName{ivar};
-                if isfield(MergeData,'VarAttribute')
-                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
-                        testFF=1;
-                    end
-                end
-                MergeData.(VarName)=MergeData.(VarName) + Data{iview}.(VarName);
-            end
-        end
-        if testFF
-            nbaver=nbview-MergeData.FF;
-            indgood=find(nbaver>0);
-            for ivar=VarIndex
-                VarName=MergeData.ListVarName{ivar};
-                MergeData.(VarName)(indgood)=double(MergeData.(VarName)(indgood))./nbaver(indgood);
-            end 
-        else
-            for ivar=VarIndex
-                VarName=MergeData.ListVarName{ivar};
-                MergeData.(VarName)=double(MergeData.(VarName))./nbview;
-            end    
-        end
-    end
-end
-
-    
+        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
+        if ~isempty(r)
+            NomTypeNc='_1AB';
+        else
+            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
+            if ~isempty(r)
+                NomTypeNc='_1_1-2';
+            end            
+        end
+    end
+    if isempty(r)
+        display('wrong pair mode input option')
+    else
+    ind1=stra2num(r.num1);
+    ind2=stra2num(r.num2);
+    end
+end
+if strcmp (mode,'Di')
+    i1_series=i_series-ind1;% set of first image numbers
+    i2_series=i_series+ind2;
+    check_bounds=i1_series<MinIndex(1,1) | i2_series>MaxIndex(1,1);
+    if isempty(j_series)
+        NomTypeNc='_1-2';
+    else
+        NomTypeNc='_1-2_1';
+    end
+elseif strcmp (mode,'Dj')
+    j1_series=j_series-ind1;
+    j2_series=j_series+ind2;
+    check_bounds=j1_series<MinIndex(1,2) | j2_series>MaxIndex(1,2);
+    NomTypeNc='_1_1-2';
+else  %bursts
+    j1_series=ind1*ones(size(i_series));
+    j2_series=ind2*ones(size(i_series));
+end
+
+%     if length(indsel)>=1
+%         firstind=indsel(1);
+%         lastind=indsel(end);
+%         set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
+%         set(handles.last_j,'String',num2str(ref_j(lastind)))
+%         ref_j=ref_j(indsel);
+%         j1_civ1=j1_civ1(indsel);
+%         j2_civ1=j2_civ1(indsel);
+%         j1_civ2=j1_civ2(indsel);
+%         j2_civ2=j2_civ2(indsel);
+%     end
+% elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
+%     displ_num=get(handles.ListPairCiv1,'UserData');
+%     i1_civ1=ref_i;
+%     i2_civ1=ref_i;
+%     j1_civ1=displ_num(1,index_civ1);
+%     j2_civ1=displ_num(2,index_civ1);
+%     i1_civ2=ref_i;
+%     i2_civ2=ref_i;
+%     j1_civ2=displ_num(1,index_civ2);
+%     j2_civ2=displ_num(2,index_civ2);
+% elseif isequal(mode,'displacement')
+%     i1_civ1=ref_i;
+%     i2_civ1=ref_i;
+%     j1_civ1=ref_j;
+%     j2_civ1=ref_j;
+%     i1_civ2=ref_i;
+%     i2_civ2=ref_i;
+%     j1_civ2=ref_j;
+%     j2_civ2=ref_j;
+% end
+
+
+
+
Index: /trunk/src/struct2xml.m
===================================================================
--- /trunk/src/struct2xml.m	(revision 597)
+++ /trunk/src/struct2xml.m	(revision 598)
@@ -26,15 +26,17 @@
    val=Object.(fieldnames{ilist});
    if isstruct(val)
-      [t,uid]=add(t,root_uid,'element',fieldnames{ilist});
-      fieldnames_sub=fields(val);
-      for ilist_sub=1:length(fieldnames_sub)
-          if isstruct(fieldnames_sub{ilist_sub})
-                t=struct2xml(fieldnames_sub{ilist_sub},t,uid);
-%                 save(t)
-          else
-              val_sub=val.(fieldnames_sub{ilist_sub});
-              t=add_element(t,uid,fieldnames_sub{ilist_sub},val_sub);
-          end
-      end
+      [t,branch_uid]=add(t,root_uid,'element',fieldnames{ilist});
+       t=struct2xml(val,t,branch_uid);
+      
+%       fieldnames_sub=fields(val)
+%       for ilist_sub=1:length(fieldnames_sub)
+%           if isstruct(fieldnames_sub{ilist_sub})
+%                 t=struct2xml(fieldnames_sub{ilist_sub},t,uid);
+% %                 save(t)
+%           else
+%               val_sub=val.(fieldnames_sub{ilist_sub});
+%               t=add_element(t,uid,fieldnames_sub{ilist_sub},val_sub);
+%           end
+%       end
    else
        t=add_element(t,root_uid,fieldnames{ilist},val);
Index: /trunk/src/uvmat.m
===================================================================
--- /trunk/src/uvmat.m	(revision 597)
+++ /trunk/src/uvmat.m	(revision 598)
@@ -1852,6 +1852,6 @@
         end
         if exist(imaname_1,'file')
-            num_j2=num_j1+1;
-            set(handles.j2,'String',num2str(num_j2));
+            num_j2=num_j1+1;% look by default for the next j index as the second file
+            set(handles.j2,'String',num2stra(num_j2,NomType));
         else
             imaname_1=fullfile_uvmat(RootPath,SubDir,RootFile,Ext,NomType,num_i1+1,[],num_j1);
@@ -2602,6 +2602,11 @@
     set(handles.ListObject_1,'Visible','off')
     [PlotType,PlotParamOut]=plot_field(UvData.Field,handles.PlotAxes,read_GUI(handles.uvmat));
-    %errormsg=fill_GUI(PlotParamOut,handles.uvmat);
-    write_plot_param(handles,PlotParamOut) %update the auto plot parameters
+    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
+    for list={'Scalar','Vectors'}
+        if ~isfield(PlotParamOut,list{1})
+            set(handles.(list{1}),'Visible','off')
+        end
+    end
+    %write_plot_param(handles,PlotParamOut) %update the auto plot parameters
     
 %% 2D or 3D fieldname are generally projected
@@ -2711,9 +2716,13 @@
                 [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
                 if imap==1
-                errormsg=fill_GUI(PlotParamOut,handles.uvmat);
+                    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
                 else
                     errormsg=fill_GUI(PlotParamOut,view_field_handle);
                 end
-                %write_plot_param(plot_handles{imap},PlotParamOut) %update the auto plot parameters
+                for list={'Scalar','Vectors'}
+                    if ~isfield(PlotParamOut,list{1})
+                        set(plot_handles{imap}.(list{1}),'Visible','off')
+                    end
+                end
                 if isfield(Field,'CoordMesh')&&~isempty(Field.CoordMesh)
                     ObjectData.CoordMesh=Field.CoordMesh; % gives an estimated mesh size (useful for mouse action on the plot)
@@ -4377,4 +4386,9 @@
     [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the GUI view_field);
     errormsg=fill_GUI(PlotParam,hview_field);
+                    for list={'Scalar','Vectors'}
+                    if ~isfield(PlotParamOut,list{1})
+                        set(hhview_field.(list{1}),'Visible','off')
+                    end
+                end
     %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
     haxes=findobj(hview_field,'tag','axes3');
@@ -5173,2 +5187,107 @@
 % Hints: get(hObject,'String') returns contents of TransformPath as text
 %        str2double(get(hObject,'String')) returns contents of TransformPath as a double
+
+
+%TODO: use to modify fill_GUI
+%'write_plot_param': update the plotting parameters on the uvmat or view_field interface after a plotting operation
+function write_plot_param(handles,PlotParam)
+%% coordinates
+if isempty(PlotParam.Coordinates)
+    set(handles.Coordinates,'Visible','off')
+    set(handles.PlotAxes,'Visible','off')
+    set(handles.text_display,'Visible','off')
+    set(handles.TableDisplay,'Visible','on')
+else
+    set(handles.Coordinates,'Visible','on')
+    set(handles.PlotAxes,'Visible','on')
+    set(handles.text_display,'Visible','on')
+    if isfield(handles,'TableDisplay')
+    set(handles.TableDisplay,'Visible','off')
+    end
+    Coordinates=PlotParam.Coordinates;
+    if isfield(Coordinates,'CheckFixAspectRatio')
+        if Coordinates.CheckFixAspectRatio
+            set(handles.CheckFixAspectRatio,'Value',1)
+        else
+            set(handles.CheckFixAspectRatio,'Value',0)
+ 
+        end
+    end
+    if isfield(Coordinates,'AspectRatio')
+        set(handles.num_AspectRatio,'String',num2str(Coordinates.AspectRatio))
+    end
+    if isfield(Coordinates,'MinX')
+        set(handles.num_MinX,'String',num2str(Coordinates.MinX,4));
+        set(handles.num_MaxX,'String',num2str(Coordinates.MaxX,4));
+        set(handles.num_MinY,'String',num2str(Coordinates.MinY,4));
+        set(handles.num_MaxY,'String',num2str(Coordinates.MaxY,4));
+    else
+        set(handles.num_MinX,'String','');
+        set(handles.num_MaxX,'String','');
+        set(handles.num_MinY,'String','');
+        set(handles.num_MaxY,'String','');
+    end
+end
+
+%% scalar or image parameters
+if isfield(PlotParam,'Scalar')
+    set(handles.Scalar,'Visible','on')
+    if isfield(PlotParam.Scalar,'MaxA')
+        set(handles.num_MaxA,'String',num2str(PlotParam.Scalar.MaxA,3));
+    end
+    if isfield(PlotParam.Scalar,'MinA')
+        set(handles.num_MinA,'String',num2str(PlotParam.Scalar.MinA,3));
+    end   
+    if isfield(PlotParam.Scalar,'IncrA')
+        set(handles.num_IncrA,'String',num2str(PlotParam.Scalar.IncrA,3))
+    end
+    set(handles.CheckBW,'Value',PlotParam.Scalar.CheckBW)
+    if isfield(PlotParam.Scalar,'Opacity')&&isfield(handles,'num_Opacity')
+        set(handles.num_Opacity,'String',num2str(PlotParam.Scalar.Opacity)) 
+    end
+else
+    set(handles.Scalar,'Visible','off')
+end
+
+%% parameter for vector field
+if isfield(PlotParam,'Vectors')
+    set(handles.Vectors,'Visible','on')
+    if isfield(PlotParam.Vectors,'VecScale')
+        set(handles.num_VecScale,'String',num2str(PlotParam.Vectors.VecScale,3))
+    end
+    if isfield(PlotParam.Vectors,'MinC')&& isfield(PlotParam.Vectors,'MaxC')
+        MinC=PlotParam.Vectors.MinC;
+        MaxC=PlotParam.Vectors.MaxC;
+        set(handles.num_MinVec,'String', num2str(MinC,3));
+        set(handles.num_MaxVec,'String',num2str(MaxC,3));
+        list=get(handles.ColorCode,'String');
+        ichoice=get(handles.ColorCode,'Value');
+        color_option=list{ichoice};
+        test3color=strcmp(color_option,'rgb')||strcmp(color_option,'bgr');
+        if test3color% need to update color thresholds
+            set(handles.num_ColCode1,'Visible','on')
+            set(handles.num_ColCode2,'Visible','on')
+            set(handles.Slider1,'Visible','on')
+            set(handles.Slider2,'Visible','on')
+            %ColCode1=MinC+(MaxC-MinC)*PlotParam.Vectors.ColCode1;
+            %ColCode2=MinC+(MaxC-MinC)*PlotParam.Vectors.ColCode2;
+%             ColCode1=MinC+(MaxC-MinC)*PlotParam.Vectors.ColCode1;
+            %ColCode2=MinC+(MaxC-MinC)*PlotParam.Vectors.ColCode2;
+            set(handles.num_ColCode1,'String',num2str(PlotParam.Vectors.ColCode1,3))
+            set(handles.num_ColCode2,'String',num2str(PlotParam.Vectors.ColCode2,3))
+            set(handles.Slider1,'Value',(PlotParam.Vectors.ColCode1-MinC)/(MaxC-MinC))
+            set(handles.Slider2,'Value',(PlotParam.Vectors.ColCode2-MinC)/(MaxC-MinC))
+        else
+            set(handles.num_ColCode1,'Visible','off')
+            set(handles.num_ColCode2,'Visible','off')
+            set(handles.Slider1,'Visible','off')
+            set(handles.Slider2,'Visible','off')
+        end
+    end
+else
+    set(handles.Vectors,'Visible','off')
+    if isfield(handles,'edit_vect')
+        set(handles.edit_vect,'Visible','off')
+        set(handles.record,'Visible','off')
+    end
+end
