source: trunk/src/series.m @ 12

Last change on this file since 12 was 12, checked in by gostiaux, 11 years ago

The files from uvmat.2.2.beta that differed from the current version have been updated.
Now the /raid/soft/UVMAT/src should be operational

File size: 182.2 KB
Line 
1%'series': master function associated to the GUI series.m for analysis field series 
2%------------------------------------------------------------------------
3% function varargout = series(varargin)
4% associated with the GUI series.fig
5%
6%INPUT
7% param: structure with input parameters (link with the GUI uvmat)
8%      .menu_coord_str: string for the CoordType (menu for coordinate transforms)
9%      .menu_coord_val: value for CoordType (menu for coordinate transforms)
10%      .FileName: input file name
11%      .FileName_1: second input file name
12%      .list_field: menu of input fields
13%      .index_fields: chosen index
14%      .civ1=0 or 1, .interp1,  ... : input civ field type
15%
16%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
17%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
18%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
19%     This file is part of the toolbox UVMAT.
20%
21%     UVMAT is free software; you can redistribute it and/or modify
22%     it under the terms of the GNU General Public License as published by
23%     the Free Software Foundation; either version 2 of the License, or
24%     (at your option) any later version.
25%
26%     UVMAT is distributed in the hope that it will be useful,
27%     but WITHOUT ANY WARRANTY; without even the implied warranty of
28%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
30%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
31
32function varargout = series(varargin)
33
34% Begin initialization code - DO NOT EDIT
35gui_Singleton = 1;
36gui_State = struct('gui_Name',       mfilename, ...
37                   'gui_Singleton',  gui_Singleton, ...
38                   'gui_OpeningFcn', @series_OpeningFcn, ...
39                   'gui_OutputFcn',  @series_OutputFcn, ...
40                   'gui_LayoutFcn',  [] , ...
41                   'gui_Callback',   []);
42if nargin && ischar(varargin{1})
43    gui_State.gui_Callback = str2func(varargin{1});
44end
45
46if nargout
47    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
48else
49    gui_mainfcn(gui_State, varargin{:});
50end
51% End initialization code - DO NOT EDIT
52
53%--------------------------------------------------------------------------
54% --- Executes just before series is made visible.
55%--------------------------------------------------------------------------
56function series_OpeningFcn(hObject, eventdata, handles,param)
57
58% Choose default command line output for series
59handles.output = hObject;
60% Update handles structure
61guidata(hObject, handles);
62%default initial parameters
63
64%load the list of previously browsed files in menus Open and Open_1
65dir_perso=prefdir;
66profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
67if exist(profil_perso,'file')
68     h=load (profil_perso);
69     if isfield(h,'MenuFile_1')
70          set(handles.MenuFile_1,'Label',h.MenuFile_1);
71          set(handles.MenuFile_insert_1,'Label',h.MenuFile_1);
72     end
73     if isfield(h,'MenuFile_1')
74          set(handles.MenuFile_2,'Label',h.MenuFile_2);
75          set(handles.MenuFile_insert_2,'Label',h.MenuFile_2);
76     end
77     if isfield(h,'MenuFile_1')
78          set(handles.MenuFile_3,'Label',h.MenuFile_3);
79          set(handles.MenuFile_insert_3,'Label',h.MenuFile_3);
80     end
81     if isfield(h,'MenuFile_1')
82          set(handles.MenuFile_4,'Label',h.MenuFile_4);
83          set(handles.MenuFile_insert_4,'Label',h.MenuFile_4);
84     end
85     if isfield(h,'MenuFile_1')
86          set(handles.MenuFile_5,'Label',h.MenuFile_5);
87          set(handles.MenuFile_insert_5,'Label',h.MenuFile_5);
88     end
89end
90
91%check default input data
92if ~exist('param','var')
93    param=[]; %default
94end
95
96%file name and browser initialisation
97if isfield(param,'menu_coord_str')
98    set(handles.CoordType,'String',param.menu_coord_str)
99end
100if isfield(param,'menu_coord_val')
101    set(handles.CoordType,'Value',param.menu_coord_val);
102else
103     set(handles.CoordType,'Value',1);%default
104end
105
106if isfield(param,'FileName')
107    if isfield(param,'FileName_1')
108        update_file(hObject, eventdata, handles,param.FileName_1,0)
109        update_file(hObject, eventdata, handles,param.FileName,1)
110    else
111        update_file(hObject, eventdata, handles,param.FileName,0)
112    end
113end 
114
115%fields input initialisation
116if isfield(param,'list_fields')&& isfield(param,'index_fields') &&~isempty(param.list_fields) &&~isempty(param.index_fields)
117    set(handles.FieldMenu,'String',param.list_fields);% list menu fields
118    set(handles.FieldMenu,'Value',param.index_fields);% selected string index
119    FieldCell{1}=param.list_fields{param.index_fields};
120end
121if isfield(param,'civ1')&& islogical(param.civ1) && isfield(param,'civ2')&& islogical(param.civ2)&...
122        isfield(param,'interp1')&& islogical(param.interp1)&&isfield(param,'interp2')&& islogical(param.interp2)&...
123        isfield(param,'filter1')&& islogical(param.filter1)&&isfield(param,'filter2')&& islogical(param.filter2)
124    set(handles.civ1,'Value',param.civ1);
125    set(handles.civ2,'Value',param.civ1);
126    set(handles.interp1,'Value',param.interp1);
127    set(handles.interp2,'Value',param.interp2);
128    set(handles.filter1,'Value',param.filter1);
129    set(handles.filter2,'Value',param.filter2);
130end
131%set(hObject,'UserData', SeriesData)
132set(hObject,'WindowButtonUpFcn',{@mouse_up_gui,handles})
133NomType_Callback(hObject, eventdata, handles)
134%mode_Callback(hObject, eventdata, handles)
135
136%loads the information stored in prefdir to initiate the browser and the list of functions
137menu_str=get(handles.ACTION,'String');%list of functions included in 'series.m'
138menu_str(end)=[];%remove from the list the last option 'more...'
139path_series=which('series');%path of the function 'series'
140for ilist=1:length(menu_str)
141    fct_path{ilist,1}=path_series;%paths of the fuctions buil-in in 'series.m'
142end
143dir_perso=prefdir;
144profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
145if exist(profil_perso,'file')
146    h=load (profil_perso);
147    if isfield(h,'series_fct') && iscell(h.series_fct)
148         for ilist=1:length(h.series_fct)
149             [path,file]=fileparts(h.series_fct{ilist});
150             fct_path=[fct_path; {path}];%concatene the list of paths
151             menu_str=[menu_str; {file}];
152         end
153         menu_str=[menu_str;{'more...'}];
154         set(handles.ACTION,'String',menu_str)
155    end
156end
157set(handles.ACTION,'UserData',fct_path)% store the list of path in UserData of ACTION
158
159% display the GUI for the default action 'check_files'
160ACTION_Callback(hObject, eventdata, handles)
161
162%--------------------------------------------------------------
163% --- Outputs from this function are returned to the command line.
164%-----------------------------------------------------------------
165function varargout = series_OutputFcn(hObject, eventdata, handles)
166% varargout  cell array for returning output args (see VARARGOUT);
167% hObject    handle to figure
168% eventdata  reserved - to be defined in a future version of MATLAB
169% handles    structure with handles and user data (see GUIDATA)
170% Get default command line output from handles structure
171varargout{1} = handles.output;
172
173
174% --------------------------------------------------------------------
175function MenuBrowse_Callback(hObject, eventdata, handles)
176
177RootPathCell=get(handles.RootPath,'String');
178SubDirCell=get(handles.SubDir,'String'); 
179RootFileCell=get(handles.RootFile,'String');
180oldfile=''; %default
181if isempty(RootPathCell)|isequal(RootPathCell,{''})%loads the previously stored file name and set it as default in the file_input box
182     dir_perso=prefdir;
183     profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
184     if exist(profil_perso,'file')
185          h=load (profil_perso);
186         if isfield(h,'filebase')&ischar(h.filebase)
187                 oldfile=h.filebase;
188         end
189         if isfield(h,'RootPath')&ischar(h.RootPath)
190                 oldfile=h.RootPath;
191         end
192     end
193 else
194     oldfile=fullfile(RootPathCell{1},SubDirCell{1},RootFileCell{1});
195 end
196[FileName, PathName, filterindex] = uigetfile( ...
197       {'*.xml;*.xls;*.png;*.tif;*.avi;*.AVI;*.nc', ' (*.xml,*.xls, *.png,*.tif, *.avi,*.nc)';
198       '*.xml',  '.xml files '; ...
199        '*.xls',  '.xls files '; ...
200        '*.png','.png image files'; ...
201        '*.tif','.tif image files'; ...
202        '*.avi;*.AVI','.avi movie files'; ...
203        '*.nc','.netcdf files'; ...
204        '*.*',  'All Files (*.*)'}, ...
205        'Pick a file',oldfile);
206fileinput=[PathName FileName];%complete file name
207testblank=findstr(fileinput,' ');%look for blanks
208if ~isempty(testblank)
209    errordlg('forbidden input file name: contain blanks')
210    return
211end
212sizf=size(fileinput);
213if (~ischar(fileinput)|~isequal(sizf(1),1)),return;end
214[path,name,ext]=fileparts(fileinput);
215SeriesData=[];%dfault
216if isequal(ext,'.xml')
217    errordlg('input file type not implemented')%A Faire: ouvrir le fichier pour naviguer
218elseif isequal(ext,'.xls')
219    errordlg('input file type not implemented')%A Faire: ouvrir le fichier pour naviguer
220else
221    update_file(hObject, eventdata, handles,fileinput,0)
222     %update list of recent files in the menubar
223    MenuFile_1=fileinput;
224    MenuFile_2=get(handles.MenuFile_1,'Label');
225    MenuFile_3=get(handles.MenuFile_2,'Label');
226    MenuFile_4=get(handles.MenuFile_3,'Label');
227    MenuFile_5=get(handles.MenuFile_4,'Label');
228    set(handles.MenuFile_1,'Label',MenuFile_1)
229    set(handles.MenuFile_2,'Label',MenuFile_2)
230    set(handles.MenuFile_3,'Label',MenuFile_3)
231    set(handles.MenuFile_4,'Label',MenuFile_4)
232    set(handles.MenuFile_5,'Label',MenuFile_5)
233    set(handles.MenuFile_insert_1,'Label',MenuFile_1)
234    set(handles.MenuFile_insert_2,'Label',MenuFile_2)
235    set(handles.MenuFile_insert_3,'Label',MenuFile_3)
236    set(handles.MenuFile_insert_4,'Label',MenuFile_4)
237    set(handles.MenuFile_insert_5,'Label',MenuFile_5)
238    dir_perso=prefdir;
239    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
240    if exist(profil_perso,'file')
241        save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5','-append'); %store the file names for future opening of uvmat
242    else
243        txt=ver;
244        Release=txt(1).Release;
245        relnumb=str2num(Release(3:4));
246        if relnumb >= 14
247            save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5','-V6'); %store the file names for future opening of uvmat
248        else
249            save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5'); %store the file names for future opening of uvmat
250        end
251    end
252end
253% set(hseries,'UserData',SeriesData);
254% RootFile_Callback(hObject, eventdata, handles);
255% FileExt_Callback(hObject, eventdata, handles);
256% NomType_Callback(hObject, eventdata, handles)
257% mode_Callback(hObject, eventdata, handles)
258
259
260% --------------------------------------------------------------------
261function MenuFile_1_Callback(hObject, eventdata, handles)
262fileinput=get(handles.MenuFile_1,'Label');
263update_file(hObject, eventdata, handles,fileinput,0)
264
265% --------------------------------------------------------------------
266function MenuFile_2_Callback(hObject, eventdata, handles)
267fileinput=get(handles.MenuFile_2,'Label');
268update_file(hObject, eventdata, handles,fileinput,0)
269
270% --------------------------------------------------------------------
271function MenuFile_3_Callback(hObject, eventdata, handles)
272fileinput=get(handles.MenuFile_3,'Label');
273update_file(hObject, eventdata, handles,fileinput,0)
274
275% --------------------------------------------------------------------
276function MenuFile_4_Callback(hObject, eventdata, handles)
277fileinput=get(handles.MenuFile_4,'Label');
278update_file(hObject, eventdata, handles,fileinput,0)
279
280% --------------------------------------------------------------------
281function MenuFile_5_Callback(hObject, eventdata, handles)
282fileinput=get(handles.MenuFile_5,'Label');
283update_file(hObject, eventdata, handles,fileinput,0)
284
285% --------------------------------------------------------------------
286function MenuBrowse_insert_Callback(hObject, eventdata, handles)
287
288%hseries=get(handles.browse_root,'parent');
289RootPathCell=get(handles.RootPath,'String');
290% SubDirCell=get(handles.SubDir,'String'); 
291RootFileCell=get(handles.RootFile,'String');
292oldfile=''; %default
293if isempty(RootPathCell)|isequal(RootPathCell,{''})%loads the previously stored file name and set it as default in the file_input box
294     dir_perso=prefdir;
295     profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
296     if exist(profil_perso,'file')
297          h=load (profil_perso);
298         if isfield(h,'filebase')&ischar(h.filebase)
299                 oldfile=h.filebase;
300         end
301         if isfield(h,'RootPath')&ischar(h.RootPath)
302                 oldfile=h.RootPath;
303         end
304     end
305 else
306     oldfile=fullfile(RootPathCell{1},RootFileCell{1});
307 end
308[FileName, PathName, filterindex] = uigetfile( ...
309       {'*.xml;*.xls;*.png;*.avi;*.AVI;*.nc', ' (*.xml,*.xls, *.png, *.avi,*.nc)';
310       '*.xml',  '.xml files '; ...
311        '*.xls',  '.xls files '; ...
312        '*.png','.png image files'; ...
313        '*.avi;*.AVI','.avi movie files'; ...
314        '*.nc','.netcdf files'; ...
315        '*.*',  'All Files (*.*)'}, ...
316        'Pick a file',oldfile);
317fileinput=[PathName FileName];%complete file name
318testblank=findstr(fileinput,' ');%look for blanks
319if ~isempty(testblank)
320    errordlg('forbidden input file name: contain blanks')
321    return
322end
323sizf=size(fileinput);
324if (~ischar(fileinput)|~isequal(sizf(1),1)),return;end
325[path,name,ext]=fileparts(fileinput);
326SeriesData=[];%dfault
327if isequal(ext,'.xml')
328    errordlg('input file type not implemented')%A Faire: ouvrir le fichier pour naviguer
329elseif isequal(ext,'.xls')
330    errordlg('input file type not implemented')%A Faire: ouvrir le fichier pour naviguer
331else
332    update_file(hObject, eventdata, handles,fileinput,1)
333    %update list of recent files in the menubar
334    MenuFile_1=fileinput;
335    MenuFile_2=get(handles.MenuFile_1,'Label');
336    MenuFile_3=get(handles.MenuFile_2,'Label');
337    MenuFile_4=get(handles.MenuFile_3,'Label');
338    MenuFile_5=get(handles.MenuFile_4,'Label');
339    set(handles.MenuFile_1,'Label',MenuFile_1)
340    set(handles.MenuFile_2,'Label',MenuFile_2)
341    set(handles.MenuFile_3,'Label',MenuFile_3)
342    set(handles.MenuFile_4,'Label',MenuFile_4)
343    set(handles.MenuFile_5,'Label',MenuFile_5)
344    set(handles.MenuFile_insert_1,'Label',MenuFile_1)
345    set(handles.MenuFile_insert_2,'Label',MenuFile_2)
346    set(handles.MenuFile_insert_3,'Label',MenuFile_3)
347    set(handles.MenuFile_insert_4,'Label',MenuFile_4)
348    set(handles.MenuFile_insert_5,'Label',MenuFile_5)
349    dir_perso=prefdir;
350    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
351    if exist(profil_perso,'file')
352        save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5','-append'); %store the file names for future opening of uvmat
353    else
354        txt=ver;
355        Release=txt(1).Release;
356        relnumb=str2num(Release(3:4));
357        if relnumb >= 14
358            save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5','-V6'); %store the file names for future opening of uvmat
359        else
360            save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5'); %store the file names for future opening of uvmat
361        end
362    end
363end
364%------------------------------------------------
365
366% --------------------------------------------------------------------
367function MenuFile_insert_1_Callback(hObject, eventdata, handles)
368fileinput=get(handles.MenuFile_insert_1,'Label');
369update_file(hObject, eventdata, handles,fileinput,1)
370
371% --------------------------------------------------------------------
372function MenuFile_insert_2_Callback(hObject, eventdata, handles)
373fileinput=get(handles.MenuFile_insert_2,'Label');
374update_file(hObject, eventdata, handles,fileinput,1)
375
376% --------------------------------------------------------------------
377function MenuFile_insert_3_Callback(hObject, eventdata, handles)
378fileinput=get(handles.MenuFile_insert_3,'Label');
379update_file(hObject, eventdata, handles,fileinput,1)
380
381% --------------------------------------------------------------------
382function MenuFile_insert_4_Callback(hObject, eventdata, handles)
383fileinput=get(handles.MenuFile_insert_4,'Label');
384update_file(hObject, eventdata, handles,fileinput,1)
385
386% --------------------------------------------------------------------
387function MenuFile_insert_5_Callback(hObject, eventdata, handles)
388fileinput=get(handles.MenuFile_insert_5,'Label');
389update_file(hObject, eventdata, handles,fileinput,1)
390
391% --------------------------------------------------------------------
392% refresh the GUI data after introduction of a new file series
393function update_file(hObject, eventdata, handles,fileinput,addtest)
394hseries=get(handles.RootPath,'parent'); 
395% refresh input root name, indices, file extension and nomenclature
396[RootPath,RootFile,field_count,str2,str_a,str_b,FileExt,NomType,SubDir]=name2display(fileinput);
397%check for movie image files
398if ~isempty(imformats(FileExt(2:end)))
399    imainfo=imfinfo(fileinput);     
400    if length(imainfo) >1 %case of image with multiple frames
401        NomType='*';
402        [RootPath,RootFile]=fileparts(fileinput);
403    end
404end
405NcType='none';%default
406if isequal(FileExt,'.nc')
407   Data=nc2struct(fileinput,[]);
408   if isfield(Data,'absolut_time_T0')
409       NcType='civx'; % test for civx velocity fields
410   end
411end
412
413set(handles.RootPath,'Value',1)
414set(handles.SubDir,'Value',1)
415set(handles.RootFile,'Value',1)
416set(handles.NomType,'Value',1)
417set(handles.FileExt,'Value',1)
418set(handles.nb_field,'Value',1)
419set(handles.nb_field2,'Value',1)
420if addtest
421    SeriesData=get(hseries,'UserData');
422    SeriesData.displ_num=[0 0 0 0;SeriesData.displ_num];
423    SeriesData.CurrentInputFile_1=SeriesData.CurrentInputFile;
424    RootPathCell=[{RootPath}; get(handles.RootPath,'String')] ;
425    SubDirCell=[{SubDir}; get(handles.SubDir,'String')];
426    RootFileCell=[{RootFile}; get(handles.RootFile,'String')];
427    NomTypeCell=[{NomType}; SeriesData.NomType];
428    FileExtCell=[{FileExt}; get(handles.FileExt,'String')];
429    NcTypeCell=[{NcType};SeriesData.NcType];
430    set(handles.NomType,'String',[{};get(handles.NomType,'String')])
431else
432    SeriesData=[];%re-initialisation
433    SeriesData.displ_num=[0 0 0 0];
434    RootPathCell={RootPath};
435    SubDirCell={SubDir};
436    RootFileCell={RootFile};   
437    NomTypeCell={NomType};
438    FileExtCell={FileExt};   
439    NcTypeCell={NcType};
440end
441
442SeriesData.NomType=NomTypeCell;
443SeriesData.NcType=NcTypeCell;
444SeriesData.CurrentInputFile=fileinput;
445set(handles.RootPath,'String',RootPathCell);
446set(handles.SubDir,'String',SubDirCell);
447set(handles.RootFile,'String',RootFileCell);
448set(handles.NomType,'String',NomTypeCell);
449set(handles.FileExt,'String',FileExtCell); 
450
451%determine field indices
452ref_i=1; %default ref_i is a reference frame index used to find existing pairs from PIV
453if ~isempty(str2num(field_count))
454    ref_i=str2num(field_count);
455    if ~isempty(str2num(str2))
456        ref_i=floor((ref_i+str2num(str2))/2);% reference image number corresponding to the file
457        SeriesData.browse_Di=str2num(str2)-str2num(field_count);
458    end
459end
460set(handles.ref_i,'String',num2str(ref_i));
461set(handles.first_i,'String',num2str(ref_i));
462set(handles.last_i,'String',num2str(ref_i));
463ref_j=1; %default  ref_j is a reference frame index used to find existing pairs from PIV
464if ~isempty(str2num(str_a))
465    ref_j=str2num(str_a);
466    if ~isempty(str2num(str_b))
467        ref_j=floor((str2num(str_a)+str2num(str_b))/2);
468        SeriesData.browse_Dj=str2num(str_b)-str2num(str_a);
469    end         
470end
471set(handles.ref_j,'String',num2str(ref_j));
472set(handles.first_j,'String',num2str(ref_j))
473set(handles.last_j,'String',num2str(ref_j));
474%set(hseries,'UserData',SeriesData);
475
476%enable other menus and uicontrols
477set(handles.MenuOpen_insert,'Enable','on')
478set(handles.MenuFile_insert_1,'Enable','on')
479set(handles.MenuFile_insert_2,'Enable','on')
480set(handles.MenuFile_insert_3,'Enable','on')
481set(handles.MenuFile_insert_4,'Enable','on')
482set(handles.MenuFile_insert_5,'Enable','on')
483set(handles.RUN, 'Enable','On')
484set(handles.RUN,'BackgroundColor',[1 0 0])% set RUN button to red
485set(handles.RootPath,'BackgroundColor',[1 1 0]) % set RootPath edit box  to yellow
486drawnow
487
488% hseries=get(handles.RootFile,'parent');
489% SeriesData=get(hseries,'UserData');%read information set by the browser
490% ext_ima_read=[];
491% field_count=1;%default
492% pxcmx=1;
493% pxcmy=1;
494TimeUnit=''; %default
495% CoordUnit='';%default
496time=[];%default
497GeometryCalib=[];%default
498nb_field=[];%default
499nb_field2=[];%default
500% Heading=[];
501% [PD,Device]=fileparts(RootPathCell{1});
502SeriesData.PathCampaign=get(handles.PathCampaign,'String');
503
504% read timing and total frame number from the current file (movie files) !! may be overrid by xml file
505%icell=length(RootPathCell);
506FileBase=fullfile(RootPath,RootFile);
507
508% nb_field{icell,1}='?';%default
509% nb_field2{icell,1}='?';%default
510testima=0; %test for image input
511if isequal(lower(FileExt),'.avi') %.avi file
512    testima=1;
513    info=aviinfo([FileBase FileExt]);
514    time=[0:1/info.FramesPerSecond:(info.NumFrames-1)/info.FramesPerSecond]';
515    nb_field=info.NumFrames;
516    nb_field2=1;
517elseif ~isempty(imformats(FileExt(2:end)))
518    testima=1;
519    if isequal(NomType,'*')% multi-frame image
520        imainfo=imfinfo([FileBase FileExt]);     
521        if length(imainfo) >1 %case of image with multiple frames
522            nb_field=length(imainfo);
523            nb_field2=1;
524        end
525    end
526elseif isequal(FileExt,'.vol')
527     testima=1;
528end
529
530% enable field and veltype menus
531testfield=isequal(get(handles.FieldMenu,'enable'),'on');
532testfield_1=isequal(get(handles.FieldMenu_1,'enable'),'on');
533testveltype=isequal(get(handles.VelTypeMenu,'enable'),'on');
534testveltype_1=isequal(get(handles.VelTypeMenu_1,'enable'),'on');
535testtransform=isequal(get(handles.CoordType,'Enable'),'on');
536testnc=0;
537testnc_1=0;
538testcivx=0;
539testcivx_1=0;
540if length(FileExtCell)==1 || length(FileExtCell)>2
541    for iview=1:length(FileExtCell)
542        if isequal(FileExtCell{iview},'.nc')
543            testnc=1;
544        end
545        if isequal(NcTypeCell{iview},'civx')
546            testcivx=1;
547        end
548    end
549elseif length(FileExtCell)==2
550    testnc=isequal(FileExtCell{1},'.nc');
551    testnc_1=isequal(FileExtCell{2},'.nc');
552    testcivx=isequal(NcTypeCell{1},'civx');
553    testcivx_1=isequal(NcTypeCell{2},'civx');
554end
555if testfield && testnc
556    view_FieldMenu(handles,'on')
557    if testcivx
558        menustr=get(handles.FieldMenu,'String');
559        if isequal(menustr,{'get_field...'})
560            set(handles.FieldMenu,'String',{'get_field...';'velocity';'vort';'div';'more...'})
561        end
562    else
563        set(handles.FieldMenu,'Value',1)
564        set(handles.FieldMenu,'String',{'get_field...'})
565    end
566else
567    view_FieldMenu(handles,'off')
568end
569if testfield_1 && testnc_1
570    view_FieldMenu_1(handles,'on')
571    if testcivx_1
572        menustr=get(handles.FieldMenu_1,'String');
573        if isequal(menustr,{'get_field...'})
574            set(handles.FieldMenu_1,'String',{'get_field...';'velocity';'vort';'div';'more...'})
575        end
576    else
577        set(handles.FieldMenu_1,'Value',1)
578        set(handles.FieldMenu_1,'String',{'get_field...'})
579    end
580else
581    view_FieldMenu_1(handles,'off')
582end
583if testveltype && testcivx
584    set(handles.VelTypeMenu,'Visible','on')
585    set(handles.VelType_text,'Visible','on');
586else
587    set(handles.VelTypeMenu,'Visible','off')
588    set(handles.VelType_text,'Visible','off');
589end
590if testveltype_1 && testcivx_1
591    set(handles.VelTypeMenu_1,'Visible','on')
592    set(handles.VelType_text_1,'Visible','on');
593else
594    set(handles.VelTypeMenu_1,'Visible','off')
595    set(handles.VelType_text_1,'Visible','off');
596end
597if testtransform && (testcivx || testima)
598     view_TRANSFORM(handles,'on')
599else
600    view_TRANSFORM(handles,'off')
601end
602if ~isequal(FileExt,'.nc') && ~isequal(FileExt,'.cdf') && ~testima
603    msgbox_uvmat('ERROR',['invalid input file extension ' FileExt])
604    return
605end 
606
607%%%%%%%%   read image documentation file  if found%%%%%%%%%%%%%%%%%%%%%%%%%%%
608      %look for the file existence
609ext_imadoc='';
610if isequal(FileExt,'.xml')||isequal(FileExt,'.civ')
611    ext_imadoc=FileExt;
612elseif exist([FileBase '.xml'],'file')
613    ext_imadoc='.xml';
614elseif exist([FileBase '.civ'],'file')
615    ext_imadoc='.civ';
616end
617      %read the ImaDoc file
618% mode=''; %default
619% testheading=0; 
620XmlData=[];
621NbSlice_calib={};
622if isequal(ext_imadoc,'.xml')
623        [XmlData,warntext]=imadoc2struct([FileBase '.xml']);
624        if isfield(XmlData,'Heading') && isfield(XmlData.Heading,'ImageName')
625            [PP,FF,ext_ima_read]=fileparts(XmlData.Heading.ImageName);
626        end
627        if isfield(XmlData,'Time')
628            time=XmlData.Time;
629        end
630        if isfield(XmlData,'Camera')
631            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
632                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
633                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
634                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
635                end
636            end
637            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
638                TimeUnit=XmlData.Camera.TimeUnit;
639            end
640        end
641        if ~isempty(warntext)
642            msgbox_uvmat('WARNING',warntext)
643        end 
644elseif isequal(ext_imadoc,'.civ')
645    [error,XmlData.Time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([FileBase '.civ']);
646    time=XmlData.Time;
647    size(time)
648    GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
649    GeometryCalib.Tx=0;
650    GeometryCalib.Ty=0;
651    GeometryCalib.Tz=1;
652    GeometryCalib.dpx=1;
653    GeometryCalib.dpy=1;
654    GeometryCalib.sx=1;
655    GeometryCalib.Cx=0;
656    GeometryCalib.Cy=0;
657    GeometryCalib.f=1;
658    GeometryCalib.kappa1=0;
659    GeometryCalib.CoordUnit='cm';
660    XmlData.GeometryCalib=GeometryCalib;
661    if error==2, warntext=['no file ' FileBase '.civ'];
662    elseif error==1, warntext='inconsistent number of fields in the .civ file';
663    end 
664%     set(handles.npx,'String',num2str(npx));%fills nbre of pixels x box
665%     set(handles.npy,'String',num2str(npy));%fills nbre of pixels y box
666%     set(handles.pxcm,'String',num2str(pxcmx));%fills scale x (pixel/cm) box
667%     set(handles.pycm,'String',num2str(pxcmy));%fills scale y (pixel/cm) box
668%     set(handles.pxcm,'Visible','on');%fills scale x (pixel/cm) box
669%     set(handles.pycm,'Visible','on');%fills scale y (pixel/cm) box
670%     set(handles.view_xml,'Visible','on')
671%     set(handles.view_xml,'String','view .civ')
672end 
673if addtest
674    SeriesData.Time=[{time} SeriesData.Time];
675else
676   SeriesData.Time={time};
677end
678
679if ~isempty(time)
680    siztime=size(time);
681    nb_field=siztime(1);
682    nb_field2=siztime(2);
683end   
684set(handles.TimeUnit,'String',TimeUnit)
685if isempty(nb_field)
686    nb_field_str='?';
687    nb_field_str2='?';
688else
689    nb_field_str=num2str(nb_field);
690    nb_field_str2=num2str(nb_field2);
691end
692if addtest
693    nb_field_cell=[{nb_field_str} ;get(handles.nb_field,'String')];
694    nb_field2_cell=[{nb_field_str2} ;get(handles.nb_field2,'String')];
695else
696    nb_field_cell={nb_field_str};
697    nb_field2_cell={nb_field_str2};
698end
699set(handles.nb_field,'String',nb_field_cell);
700set(handles.nb_field2,'String',nb_field2_cell);
701set(hseries,'UserData',SeriesData);
702
703%number of slices
704if isfield(XmlData,'GeometryCalib') && isfield(XmlData.GeometryCalib,'SliceCoord')
705       siz=size(XmlData.GeometryCalib.SliceCoord);
706       if siz(1)>1
707           NbSlice=siz(1);
708       else
709           NbSlice=1;
710       end
711       set(handles.NbSlice,'String',num2str(NbSlice))
712end
713
714% set menus of index pairs
715NomType_Callback(hObject, eventdata, handles)
716
717dir_perso=prefdir;
718profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
719% save(profil_perso, 'FileBase'); %store the root name for future opening of uvmat
720if exist(profil_perso,'file')
721    save (profil_perso,'RootPath','SubDir','RootFile','NomType', '-append'); %store the root name for future opening of uvmat
722else
723    txt=ver;
724    Release=txt(1).Release;
725    relnumb=str2num(Release(3:4));
726    if relnumb >= 14
727        save (profil_perso,'RootPath','SubDir','RootFile','NomType','-V6') %store the root name for future opening of uvmat
728    else
729        save(profil_perso,'RootPath','SubDir','RootFile','NomType')
730    end         
731end
732set(handles.RootPath,'BackgroundColor',[1 1 1])
733set(handles.PathCampaign,'String',SeriesData.PathCampaign)
734last_j_Callback(hObject, eventdata, handles)
735last_i_Callback(hObject, eventdata, handles)
736
737%------------------------------------------------------------
738function RootPath_Callback(hObject, eventdata, handles)
739Val=get(handles.RootPath,'Value');
740synchronise_view(handles,Val)
741NomType_Callback(hObject, eventdata, handles)
742%------------------------------------------------------------
743
744function synchronise_view(handles,Val)
745set(handles.RootPath,'Value',Val)
746set(handles.SubDir,'Value',Val)
747set(handles.RootFile,'Value',Val)
748set(handles.NomType,'Value',Val)
749set(handles.FileExt,'Value',Val)
750set(handles.nb_field,'Value',Val)
751set(handles.nb_field2,'Value',Val)
752set(handles.time_first,'Value',Val)
753set(handles.time_last,'Value',Val)
754
755
756%---------------------------------------------------------
757% Executes on carriage return on the subdir civ1 edit window
758%--------------------------------------------------------
759function SubDir_Callback(hObject, eventdata, handles)
760
761Val=get(handles.SubDir,'Value');
762synchronise_view(handles,Val)
763NomType_Callback(hObject, eventdata, handles)
764
765%--------------------------------------------------------------
766%function activated when a new filebase (image series) is introduced
767%------------------------------------------------------------
768function RootFile_Callback(hObject, eventdata, handles)
769Val=get(handles.RootFile,'Value');
770synchronise_view(handles,Val)
771NomType_Callback(hObject, eventdata, handles)
772
773%--------------------------------------------------------------
774%function activated when a new filebase (image series) is introduced
775%------------------------------------------------------------
776function FileExt_Callback(hObject, eventdata, handles)
777Val=get(handles.FileExt,'Value');
778synchronise_view(handles,Val)
779
780%--------------------------------------------------------------
781%function activated when a new filebase (image series) is introduced
782%------------------------------------------------------------
783function nb_field_Callback(hObject, eventdata, handles)
784Val=get(handles.nb_field,'Value');
785synchronise_view(handles,Val)
786
787%--------------------------------------------------------------
788%function activated when a new filebase (image series) is introduced
789%------------------------------------------------------------
790function nb_field2_Callback(hObject, eventdata, handles)
791Val=get(handles.nb_field2,'Value');
792synchronise_view(handles,Val)
793
794%--------------------------------------------------------------
795%function activated when a new filebase (image series) is introduced
796%------------------------------------------------------------
797function time_first_Callback(hObject, eventdata, handles)
798Val=get(handles.time_first,'Value');
799synchronise_view(handles,Val)
800
801%--------------------------------------------------------------
802%function activated when a new filebase (image series) is introduced
803%------------------------------------------------------------
804function time_last_Callback(hObject, eventdata, handles)
805Val=get(handles.time_last,'Value');
806synchronise_view(handles,Val)
807
808%--------------------------------------------------------------
809%function activated by NomType
810%------------------------------------------------------------
811NomType_Callback(hObject, eventdata, handles)
812
813function NomType_Callback(hObject, eventdata, handles)
814hseries=get(handles.ProjObject,'Parent');
815SeriesData=get(hseries,'UserData');
816if isfield(SeriesData,'NomType')
817    NomTypeCell=SeriesData.NomType;
818else
819    NomTypeCell={};
820end
821nbfield2_cell=get(handles.nb_field2,'String');
822val=get(handles.nb_field2,'Value');
823if iscell(nbfield2_cell)
824    nbfield2=str2num(nbfield2_cell{val});
825else
826    nbfield2=str2num(nbfield2_cell);
827end
828nbfield_cell=get(handles.nb_field,'String');
829if iscell(nbfield_cell)
830    nbfield=str2num(nbfield_cell{val});
831else
832   nbfield=str2num(nbfield_cell);
833end
834
835set(handles.mode,'Visible','off') % do not show index pairs by default
836set(handles.list_pair_civ,'Visible','off')
837set(handles.ref_i,'Visible','off')
838set(handles.ref_i_text,'Visible','off')
839testpair=0;
840state_j='off';
841%set the menus of image pairs and default selection for series
842%list pairs if relevant
843Val=get(handles.NomType,'Value');
844synchronise_view(handles,Val)
845if ~isempty(NomTypeCell)
846    NomType=NomTypeCell{Val};
847    switch NomType 
848            case {'_i1-i2_j', '_i1-i2'}
849                set(handles.mode,'String',{'series(Di)'})
850                set(handles.mode,'Value',1);
851                set(handles.mode,'Visible','on')
852                testpair=1;
853            case {'#_ab'}
854                set(handles.mode,'String',{'bursts'})
855                set(handles.mode,'Value',1);
856                testpair=1;
857            case '_i_j1-j2'
858                set(handles.mode,'String',{'bursts';'series(Dj)'})%multiple choice
859                if ~isempty(nbfield) && ~isempty(nbfield2) && ((nbfield2>10) || (nbfield==1))
860                    set(handles.mode,'Value',2);
861                else
862                    set(handles.mode,'Value',1);% advice 'bursts' for small bursts
863                end
864                set(handles.mode,'Visible','on')
865                testpair=1;
866    end
867    switch NomType   
868            case {'_i_j','_i_j1-j2','_i1-i2_j','#_ab'},% two navigation indices
869                state_j='on';
870    end
871end   
872if testpair
873    mode_Callback(hObject, eventdata, handles) 
874else
875    set(handles.NomType,'String',NomTypeCell)
876end
877set(handles.first_j,'Visible',state_j)
878set(handles.incr_j,'Visible',state_j)
879set(handles.last_j,'Visible',state_j)
880set(handles.nb_field2,'Visible',state_j)
881
882%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%????????????
883% --- Executes on button press in mode.
884%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
885function mode_Callback(hObject, eventdata, handles)
886hseries=get(handles.mode,'parent');
887SeriesData=get(hseries,'UserData');
888mode_list=get(handles.mode,'String');
889mode_value=get(handles.mode,'Value');
890mode=mode_list{mode_value};
891NomType=[];
892test_find_pair=0;
893if isfield(SeriesData,'NomType')
894    NomTypeCell=SeriesData.NomType;
895    Val=get(handles.NomType,'Value');
896    NomType=NomTypeCell{Val};
897    test_find_pair=isequal(NomType,'_i_j1-j2')|| isequal(NomType,'_i1-i2_j')|| isequal(NomType,'_i1-i2')|| isequal(NomType,'#_ab');
898end
899% displ_num=[];%default
900% first_i=str2num(get(handles.first_i,'String'));
901% last_i=str2num(get(handles.last_i,'String'));
902time=[];
903if isfield(SeriesData,'Time')
904time=SeriesData.Time{1}; %get the set of times
905end
906siztime=size(time);
907nbfield=siztime(1);
908nbfield2=siztime(2);
909indchosen=1;  %%first pair selected by default
910if isequal(mode,'bursts')
911    enable_i(handles,'On')
912    enable_j(handles,'Off')   
913elseif  isequal(NomType,'_i_j1-j2')|| isequal(NomType,'_i1-i2_j')
914    enable_i(handles,'On')
915    enable_j(handles,'On')
916else
917    enable_i(handles,'On')
918    enable_j(handles,'Off')
919end   
920   
921   
922% elseif isequal(mode,'series(Dj)')       
923%     enable_j(handles,'On')     
924%     if nbfield==1
925%         enable_i(handles,'Off')
926%     else
927%         enable_i(handles,'On')
928%     end
929% elseif isequal(mode,'series(Di)')
930%     if nbfield2 > 1
931%          enable_j(handles,'On')
932%     else
933%          enable_j(handles,'Off')
934%     end
935% end 
936set(handles.list_pair_civ,'Value',indchosen);%set the default choice of image pairs for civ1
937% SetSeries.displ_num=displ_num;
938set(hseries,'UserData',SeriesData)
939
940%list pairs if relevant
941if test_find_pair
942     find_netcpair_civ(hObject, eventdata, handles,Val)
943end
944
945%-------------------------------------
946function enable_i(handles,state)
947set(handles.i_txt,'Visible',state)
948set(handles.first_i,'Visible',state)
949set(handles.last_i,'Visible',state)
950set(handles.incr_i,'Visible',state)
951set(handles.nb_field,'Visible',state)
952set(handles.ref_i,'Visible',state)
953set(handles.ref_i_text,'Visible',state)
954
955%-----------------------------------
956function enable_j(handles,state)
957set(handles.j_txt,'Visible',state)
958set(handles.first_j,'Visible',state)
959set(handles.last_j,'Visible',state)
960set(handles.incr_j,'Visible',state)
961set(handles.nb_field2,'Visible',state)
962set(handles.ref_j,'Visible',state)
963set(handles.ref_j_text,'Visible',state)
964
965%-----------------------------------
966function view_FieldMenu(handles,state)
967set(handles.FieldMenu,'Visible',state)
968set(handles.Field_text,'Visible',state)
969set(handles.Field_frame,'Visible',state)
970
971%-----------------------------------
972function view_FieldMenu_1(handles,state)
973set(handles.FieldMenu_1,'Visible',state)
974set(handles.Field_text_1,'Visible',state)
975
976%-----------------------------------
977function view_TRANSFORM(handles,state)
978set(handles.TRANSFORM_frame,'Visible',state)
979set(handles.CoordType,'Visible',state);
980set(handles.TRANSFORM_title,'Visible',state)
981
982%--------------------------------------------------------------
983% determine the menu for civ1 pairs depending on existing netcdf file at the middle of
984% the field series set by first_i, incr, last_i
985%----------------------------------------------------------------
986function find_netcpair_civ(hObject, eventdata, handles,Val)
987hseries=get(handles.list_pair_civ,'parent');
988SeriesData=get(hseries,'UserData');
989% NomTypeCell=get(handles.NomType,'String');
990NomTypeCell=SeriesData.NomType;
991NomType=NomTypeCell{Val};
992  set(handles.list_pair_civ,'Visible','on')
993%nomenclature types
994RootPathCell=get(handles.RootPath,'String');
995filepath=RootPathCell{Val};
996RootFileCell=get(handles.RootFile,'String');
997filename=RootFileCell{Val};
998filebase=fullfile(filepath,filename);
999SubDirCell=get(handles.SubDir,'String');
1000subdir=SubDirCell{Val};
1001if ~exist(fullfile(filepath,subdir),'dir')
1002         msgbox_uvmat('ERROR',['no civ file available: subdirectory ' subdir ' does not exist'])
1003         set(handles.list_pair_civ,'String',{''});
1004         return
1005end
1006mode_list=get(handles.mode,'String');
1007mode_value=get(handles.mode,'Value');
1008mode=mode_list{mode_value};
1009
1010%reads image numbers from the interface
1011ref_i=str2num(get(handles.ref_i,'String'));
1012ref_j=str2num(get(handles.ref_j,'String'));
1013% time=[];
1014% ref_time=[];
1015 ref_time=0;
1016if isfield(SeriesData,'Time')&~isempty(SeriesData.Time{Val})&~isequal(SeriesData.Time{Val},0)
1017    time=SeriesData.Time{Val}; %get the set of times
1018    siztime=size(time);
1019    nbfield=siztime(1);
1020    nbfield2=siztime(2);
1021%     test_imadoc=1;
1022else
1023%     test_imadoc=0;%no image documentation file
1024    nbfield=50;
1025    nbfield2=50;%default max number of pairs
1026end
1027%look for existing processed pairs involving the field at the middle of the series if civ1 will not
1028% be performed, while the result is needed for next steps.
1029displ_pair={''};
1030displ_num=[];
1031ind_exist=0;
1032TimeUnit=get(handles.TimeUnit,'String');
1033if length(TimeUnit)>=1
1034    dtunit=['m' TimeUnit];
1035else
1036    dtunit='e-03';
1037end
1038if isequal(mode,'series(Di)')
1039     for index=1:min(nbfield-1,50)
1040         filename=name_generator(filebase,ref_i-floor(index/2),ref_j,'.nc',NomType,1,ref_i+ceil(index/2),ref_j,subdir);
1041         select=(exist(filename,'file')==2);
1042         if select==1
1043               ind_exist=ind_exist+1;
1044                displ_num(1,ind_exist)=0;
1045                displ_num(2,ind_exist)=0;
1046                displ_num(3,ind_exist)=-floor(index/2);
1047                displ_num(4,ind_exist)=ceil(index/2);
1048                %[cte_detect,vdt,cte_read]=read_netcdf(filename,{'dt','dt2','absolut_time_T0','absolute_time_TO_2'});
1049                [Cte,var_detect,ichoice]=nc2struct(filename,{});
1050                if isfield(Cte,'dt2')
1051                    dt=Cte.dt2;
1052                elseif isfield(Cte,'dt')
1053                    dt=Cte.dt;
1054                end
1055                if isfield(Cte,'absolut_time_TO_2')
1056                    ref_time(ind_exist)=Cte.absolut_time_TO_2;%civ2 data used in priority
1057                elseif isfield(Cte,'absolut_time_TO')
1058                    ref_time(ind_exist)=Cte.absolut_time_TO;%civ2 data used in priorit
1059                elseif isfield(Cte,'Time')
1060                    ref_time(ind_exist)=Cte.Time;
1061                end
1062                displ_pair{ind_exist}=['Di= ' num2str(-floor(index/2)) '|' num2str(ceil(index/2)) ' :dt= ' num2str(dt*1000) dtunit];
1063         end
1064     end
1065     set(handles.list_pair_civ,'String',[displ_pair';{'Di=*|*'}]);   
1066elseif isequal(mode,'series(Dj)')% series on the j index
1067       for index=1:min(nbfield2-1,50)
1068           filename=name_generator(filebase,ref_i,ref_j-floor(index/2),'.nc',NomType,1,ref_i,ref_j+ceil(index/2),subdir);
1069           select=(exist(filename,'file')==2);
1070           if select==1
1071               ind_exist=ind_exist+1;
1072                displ_num(1,ind_exist)=-floor(index/2);
1073                displ_num(2,ind_exist)=ceil(index/2);
1074                displ_num(3,ind_exist)=0;
1075                displ_num(4,ind_exist)=0;
1076                %[cte_detect,vdt,cte_read]=read_netcdf(filename,{'dt','dt2','absolut_time_T0','absolute_time_TO_2'});
1077                [Cte,var_detect,ichoice]=nc2struct(nc,{});
1078                if isfield(Cte,'dt2')
1079                    dt=Cte.dt2;
1080                elseif isfield(Cte,'dt')
1081                    dt=Cte.dt;
1082                end
1083                if isfield(Cte,'absolut_time_TO_2')
1084                    ref_time(ind_exist)=Cte.absolut_time_TO_2;%civ2 data used in priority
1085                elseif isfield(Cte,'absolut_time_TO')
1086                    ref_time(ind_exist)=Cte.absolut_time_TO;%civ2 data used in priorit
1087                elseif isfield(Cte,'Time')
1088                    ref_time(ind_exist)=Cte.Time;
1089                end
1090%                 if cte_detect(2)==1;
1091%                     dt=cte_read(2);
1092%                     ref_time(ind_exist)=cte_read(4);%civ2 data used in priority
1093%                 else
1094%                     dt=cte_read(1);
1095%                     ref_time(ind_exist)=cte_read(3);
1096%                 end
1097                displ_pair{ind_exist}=['Dj= ' num2str(-floor(index/2)) '|' num2str(ceil(index/2)) ' :dt= ' num2str(dt*1000) dtunit];
1098           end
1099       end
1100       set(handles.list_pair_civ,'String',[displ_pair';{'Dj=*|*'}]);
1101elseif isequal(mode,'bursts') %case of bursts
1102    for numod_a=1:nbfield2-1 %nbfield2 always >=2 for 'bursts' mode
1103        for numod_b=(numod_a+1):nbfield2
1104            [filename]=name_generator(filebase,ref_i,numod_a,'.nc',NomType,1,ref_i,numod_b,subdir);
1105            select=(exist(filename,'file')==2);
1106            if select==1
1107                ind_exist=ind_exist+1;
1108                numlist_a(ind_exist)=numod_a;
1109                numlist_b(ind_exist)=numod_b;
1110                Attr=nc2struct(filename,[]);
1111                isfield(Attr,'absolut_time_T0_2')
1112                if isfield(Attr,'dt2')
1113                   dt(ind_exist)=Attr.dt2;
1114                   ref_time(ind_exist)=Attr.absolut_time_T0_2;
1115                elseif isfield(Attr,'dt')& isfield(Attr,'absolut_time_T0')
1116                   dt(ind_exist)=Attr.dt;
1117                   ref_time(ind_exist)=Attr.absolut_time_T0;
1118                else
1119                   dt(ind_exist)=NaN;%no information on dt
1120                end
1121                %determine nom_type_ima for pair display (used in num2stra.m)
1122                switch NomType
1123                    case {'#ab'}
1124                        nom_type_ima='#a';
1125                    case {'#AB'}
1126                        nom_type_ima='#A';
1127                    otherwise
1128                         nom_type_ima='_i_j';
1129                end
1130               displ_pair{ind_exist}=['j= ' num2stra(numod_a,nom_type_ima,2) '-' num2stra(numod_b,nom_type_ima,2) ...
1131                        ' :dt= ' num2str(dt(ind_exist)*1000)];
1132            end
1133         end
1134         set(handles.list_pair_civ,'String',[displ_pair';{'j=*-*'}]);
1135     end
1136     if exist('dt','var') & ~isempty(dt)
1137         [dtsort,indsort]=sort(dt);
1138         displ_num(1,:)=numlist_a(indsort);
1139         displ_num(2,:)=numlist_b(indsort);
1140         displ_num(3,:)=0;
1141         displ_num(4,:)=0;
1142         displ_pair=displ_pair(indsort);
1143         ref_time=ref_time(indsort);
1144     end
1145end
1146if ind_exist==0
1147         if  isequal(mode,'series(Dj)') | isequal(mode,'st_series(Dj)')
1148            msgbox_uvmat('ERROR',['no .nc file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir])
1149        else
1150            msgbox_uvmat('ERROR',['no .nc file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir])
1151        end
1152        if isequal(mode,'bursts') %case of bursts
1153            set(handles.list_pair_civ,'String',{'j=*-*'});
1154        elseif isequal(mode,'series(Di)') %case of bursts
1155            set(handles.list_pair_civ,'String',{'Di=*|*'});
1156        elseif isequal(mode,'series(Dj)') %case of bursts
1157            set(handles.list_pair_civ,'String',{'Dj=*|*'});
1158        end
1159end
1160
1161val=get(handles.list_pair_civ,'Value');
1162if val > length(displ_pair)
1163    set(handles.list_pair_civ,'Value',1);% first pair proposed by default in the menu
1164    val=1;
1165end
1166iview=get(handles.NomType,'Value');
1167SeriesData.displ_num(iview,:)=(displ_num(:,val))';
1168SeriesData.ref_time=ref_time;
1169set(hseries,'UserData',SeriesData)
1170list_pair_civ_Callback(hObject, eventdata, handles)
1171
1172%-------------------------------------------------------------
1173% --- Executes on selection in list_pair_civ.
1174function list_pair_civ_Callback(hObject, eventdata, handles)
1175%------------------------------------------------------------
1176
1177%update first_i and last_i according to the chosen image pairs
1178testupdate=0;
1179Val=get(handles.RootPath,'Value');
1180IndexCell=get(handles.NomType,'String');
1181hseries=get(handles.list_pair_civ,'parent');
1182SeriesData=get(hseries,'UserData');
1183NomType=SeriesData.NomType{Val};
1184list_pair=get(handles.list_pair_civ,'String');%get the menu of image pairs
1185index_pair=get(handles.list_pair_civ,'Value');
1186str_pair=list_pair{index_pair};
1187ind_equ=strfind(str_pair,'=');%find '='
1188ind_sep=strfind(str_pair,'|');%find pair separator '|'
1189ind_com=strfind(str_pair,':');%find ':'
1190test_bursts=0;
1191if isempty(ind_sep)
1192    ind_sep=strfind(str_pair,'-');%find pair separator if it is not '|'
1193    test_bursts=1;% we are in the case of bursts
1194end
1195displ_num=[0 0 0 0]; %default
1196if ~isempty(ind_sep)&& ~strcmp(str_pair(ind_sep-1),'*')% if there is a pair separator ('|' or '-')
1197    num1_str=str_pair(ind_equ(1)+1:ind_sep-1);
1198    num2_str=str_pair(ind_sep+1:ind_com-1);
1199    num1=str2double(num1_str);
1200    num2=str2double(num2_str);
1201    if isequal(num1_str(1),' ')
1202        num1_str(1)=[];
1203    end   
1204    if isequal(num2_str(end),' ')
1205        num2_str(end)=[];
1206    end
1207    switch NomType
1208       case {'_i1-i2_j'}
1209           if isequal(num1_str(1),'0')
1210               IndexCell{Val}=['_(i-(i+' num2_str ')_j'];
1211           else
1212               IndexCell{Val}=['_(i' num1_str ')-(i+' num2_str ')_j'];
1213           end
1214           displ_num(3)=num1;
1215           displ_num(4)=num2;
1216       case {'_i1-i2'}
1217           if isequal(num1_str(1),'0')
1218               IndexCell{Val}=['_(i' num1_str ')-(i+' num2_str ')'];
1219           else
1220               IndexCell{Val}=['_(i' num1_str ')-(i+' num2_str ')'];
1221           end
1222           displ_num(3)=num1;
1223           displ_num(4)=num2;
1224       case '_i_j1-j2'
1225          if test_bursts
1226              IndexCell{Val}=['_i_' num1_str '-' num2_str ];
1227          else
1228              if isequal(num1_str(1),'0')
1229                 IndexCell{Val}=['_i_j-(j+' num2_str ')'];
1230              else
1231                 IndexCell{Val}=['_i_(j' num1_str ')-(j+' num2_str ')'];
1232              end
1233          end
1234          displ_num(1)=num1;
1235          displ_num(2)=num2;
1236       case {'#_ab'} %TO COMPLETE
1237           IndexCell{Val}=['_i_' num1_str '-' num2_str ];
1238
1239    end
1240end
1241set(handles.NomType,'String',IndexCell)
1242SeriesData.displ_num(Val,:)=displ_num;
1243set(hseries,'UserData',SeriesData)
1244% set(handles.NomType,'Value',Val)
1245
1246if ~isequal(str_pair,'Dj=*|*')&~isequal(str_pair,'Di=*|*')
1247        mode_list=get(handles.mode,'String');
1248    mode_value=get(handles.mode,'Value');
1249    mode=mode_list{mode_value};
1250        if isequal(mode,'series(Di)')
1251        first_i=str2num(get(handles.first_i,'String'));
1252        last_i=str2num(get(handles.last_i,'String'));
1253        incr_i=str2num(get(handles.incr_i,'String'));
1254        num1=first_i:incr_i:last_i;
1255        lastfieldCell=get(handles.nb_field,'String');
1256        lastfield=str2num(lastfieldCell{1});
1257        if ~isempty(lastfield)
1258            ind=find((num1-floor(index_pair/2)*ones(size(num1))>0)& (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield));
1259            num1=num1(ind);       
1260        end
1261        set(handles.first_i,'String',num2str(num1(1)));
1262        set(handles.last_i,'String',num2str(num1(end)));
1263        testupdate=1;
1264        elseif isequal(mode,'series(Dj)')
1265        first_j=str2num(get(handles.first_j,'String'));
1266        last_j=str2num(get(handles.last_j,'String'));
1267        incr_j=str2num(get(handles.incr_j,'String'));
1268        num_j=first_j:incr_j:last_j;
1269        lastfieldCell=get(handles.nb_field2,'String');
1270        if ~isempty(lastfieldCell)
1271            lastfield2=lastfieldCell{1};
1272            ind=find((num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
1273                 (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2));
1274        end
1275        testupdate=1;
1276        end
1277       
1278        %update the first and last times of the series
1279        if testupdate & isfield(SeriesData,'Time')
1280        if ~isempty(SeriesData.Time{1})
1281            displ_time(handles,SeriesData.Time{1});
1282        end
1283        end
1284end
1285%---------------------------------------------------
1286% --- Executes on button press in RUN.
1287%------------------------------------------------------
1288function RUN_Callback(hObject, eventdata, handles)
1289
1290%read root name and field type
1291set(handles.RUN,'BusyAction','queue');
1292hseries=get(handles.RUN,'parent');
1293set(0,'CurrentFigure',hseries)
1294if isequal(get(handles.GetObject,'Value'),1)
1295    Series.GetObject=1;
1296    GetObject_Callback(hObject, eventdata, handles)
1297else
1298    Series.GetObject=0;
1299end
1300SeriesData=get(hseries,'UserData');
1301if isfield(SeriesData,'sethandles')
1302    if iscell(SeriesData.sethandles)
1303        Series.sethandles=SeriesData.sethandles{1};
1304    else
1305        Series.sethandles=SeriesData.sethandles;%retrieve the handles of the set_object interface (to define projection objects)
1306    end
1307end
1308
1309%reinitiate waitbar position
1310Series.WaitbarPos=get(handles.waitbar_frame,'Position');%TO SUPPRESS
1311waitbarpos=Series.WaitbarPos;
1312waitbarpos(4)=0.005;%reinitialize waitbar to zero height
1313waitbarpos(2)=Series.WaitbarPos(2)+Series.WaitbarPos(4)-0.005;
1314set(handles.waitbar,'Position',waitbarpos)
1315
1316% read input file parameters and set menus
1317Series.PathProject=get(handles.PathCampaign,'String');
1318RootPath=get(handles.RootPath,'String');% path of the root name of the first field series
1319RootFile=get(handles.RootFile,'String');% root name of the first field series
1320SubDir=get(handles.SubDir,'String');% subdirectory for netcdf files
1321FileExt=get(handles.FileExt,'String');%file extension
1322if isempty(SeriesData)
1323    msgbox_uvmat('ERROR','no input file series')
1324    return
1325end
1326NomType=SeriesData.NomType;
1327if length(RootPath)==1 %string character input for user fct
1328    Series.RootPath=RootPath{1};
1329    Series.RootFile=RootFile{1};
1330    Series.SubDir=SubDir{1};
1331    Series.FileExt=FileExt{1};
1332    Series.NomType=NomType{1};
1333else %cell input for user fct
1334    Series.RootPath=RootPath;
1335    Series.RootFile=RootFile;
1336    Series.SubDir=SubDir;
1337    Series.FileExt=FileExt;
1338    Series.NomType=NomType;
1339end
1340if isequal(get(handles.FieldMenu,'Visible'),'on')
1341    FieldMenu=get(handles.FieldMenu,'String');
1342    FieldValue=get(handles.FieldMenu,'Value');
1343    Series.Field=FieldMenu(FieldValue);
1344end
1345menu_coord_state=get(handles.CoordType,'Visible');
1346Series.CoordType='';%default
1347if isequal(menu_coord_state,'on')
1348    menu_coord=get(handles.CoordType,'String');
1349    menu_index=get(handles.CoordType,'Value');
1350    Series.CoordType=menu_coord{menu_index};
1351end
1352Series.hseries=get(hObject,'Parent');
1353if isequal(get(handles.ParamVal,'Visible'),'on')
1354    ParamKey=get(handles.ParamKey,'String');
1355    if ischar(ParamKey)
1356        ParamKey{1}=ParamKey;
1357    end
1358    ParamString=get(handles.ParamVal,'String');
1359    if ischar(ParamString)
1360        for ilist=1:size(ParamString,1)
1361            ParamVal{ilist}=ParamString(ilist,:);
1362        end
1363    else
1364        ParamVal=ParamString;
1365    end   
1366end
1367
1368%read the set of field numbers
1369first_i=str2num(get(handles.first_i,'String'));
1370last_i=str2num(get(handles.last_i,'String'));
1371incr_i=str2num(get(handles.incr_i,'String'));
1372first_j=str2num(get(handles.first_j,'String'));
1373last_j=str2num(get(handles.last_j,'String'));
1374incr_j=str2num(get(handles.incr_j,'String'));
1375if ~isequal(get(handles.first_i,'Visible'),'on')
1376   first_i=1;
1377   last_i=1;
1378   incr_i=1;
1379end
1380if ~isequal(get(handles.first_j,'Visible'),'on')
1381    first_j=1;
1382    last_j=1;
1383    incr_j=1;
1384end
1385Series.NbSlice=str2num(get(handles.NbSlice,'String'));
1386if isequal(first_i,[])|isequal(first_j,[]), msgbox_uvmat('ERROR','first field number not defined'),...
1387    set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
1388if isequal(last_i,[])| isequal(last_j,[]),msgbox_uvmat('ERROR','last field number not defined'),...
1389    set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
1390if isequal(incr_i,[])| isequal(incr_j,[]),msgbox_uvmat('ERROR','increment in field number not defined'),...
1391    set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
1392if last_i < first_i | last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
1393    set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
1394num_i=[first_i:incr_i:last_i];
1395num_j=[first_j:incr_j:last_j];
1396nbfield_cell=get(handles.nb_field,'String');
1397nbfield=[]; %default
1398for iview=1:length(nbfield_cell)
1399    nb=str2num(nbfield_cell{iview});
1400    if ~isempty(nb)
1401        nbfield=[nbfield nb];
1402    end
1403end
1404nbfield=min(nbfield);
1405nbfield2_cell=get(handles.nb_field2,'String');
1406nbfield2=[]; %default
1407for iview=1:length(nbfield2_cell)
1408    nb=str2num(nbfield2_cell{iview});
1409    if ~isempty(nb)
1410        nbfield2=[nbfield2 nb];
1411    end
1412end
1413nbfield2=min(nbfield2);
1414
1415%get complementary information from the 'series' interface
1416list_action=get(handles.ACTION,'String');% list menu action
1417index_action=get(handles.ACTION,'Value');% selected string index
1418action= list_action{index_action}; % selected string
1419mode_list=get(handles.mode,'String');
1420index_mode=get(handles.mode,'Value');
1421mode=mode_list{index_mode};
1422ind_shift=0;%default
1423
1424%determine the list of input file names
1425nbmissing=0;
1426for iview=1:length(RootPath)
1427    %case of pairs (.nc files)
1428   
1429    if isequal(NomType{iview},'_i_j1-j2')| isequal(NomType{iview},'_i1-i2_j')| isequal(NomType{iview},'_i1-i2')| isequal(NomType{iview},'#_ab')
1430        ind_shift=SeriesData.displ_num(iview,:);
1431        if isequal(ind_shift,[0 0 0 0]) % undefined pairs
1432            if isequal(NomType{iview},'#_ab')
1433                mode='#_ab';
1434            end
1435            [num_i1,num_i2,num_j1,num_j2,nbmissing]=netseries_generator(fullfile(RootPath{iview},RootFile{iview}),SubDir{iview},mode,first_i,incr_i,last_i,first_j,incr_j,last_j);
1436        else   
1437            [num_i1,num_i2,num_j1,num_j2,num_i,num_j]=find_file_indices(num_i,num_j,ind_shift,NomType{iview},mode);
1438            if isempty(num_i)
1439                msgbox_uvmat('ERROR','ERROR: empty set of input files chosen')
1440                return
1441            end
1442            if num_i(1)>first_i
1443               set(handles.first_i,'String',num2str(num_i(1)))%update the display of first field
1444               last_i_Callback(hObject, eventdata, handles)
1445            end
1446            if num_i(end)<last_i
1447               set(handles.last_i,'String',num2str(num_i(end)))%update the display of last field
1448               last_i_Callback(hObject, eventdata, handles)
1449            end
1450            if num_j(1)>first_j
1451               set(handles.first_j,'String',num2str(num_j(1)))%update the display of first field
1452               last_j_Callback(hObject, eventdata, handles)
1453            end
1454            if num_j(end)<last_j
1455               set(handles.last_j,'String',num2str(num_j(end)))%update the display of last field
1456               last_j_Callback(hObject, eventdata, handles)
1457            end
1458        end
1459    else%case of images
1460        [num_i1,num_j1]=meshgrid(num_i,num_j);
1461        num_i2=num_i1;
1462        num_j2=num_j1;
1463    end
1464    if length(RootPath)>1
1465        num_i1_cell{iview}=num_i1;
1466        num_i2_cell{iview}=num_i2;
1467        num_j1_cell{iview}=num_j1;
1468        num_j2_cell{iview}=num_j2;
1469    end
1470end
1471
1472% RUN RUN'
1473path_series=which('series');
1474list_path=get(handles.ACTION,'UserData');
1475index=get(handles.ACTION,'Value');
1476fct_path=list_path{index}; %path stored for the function ACTION
1477if ~isequal(fct_path,path_series)
1478    eval(['spath=which(''' action ''');']) %spath = current path of the selected function ACTION
1479    if ~isequal(spath,fct_path)& exist(fct_path,'dir')
1480        addpath(fct_path)% add the prescribed path if not the current one
1481    end
1482end
1483Series.Action=action;%name of the processing programme
1484set(handles.RUN,'BackgroundColor',[0.831 0.816 0.784])
1485drawnow
1486if length(RootPath)>1
1487    feval(action,num_i1_cell,num_i2_cell,num_j1_cell,num_j2_cell,Series);
1488else
1489    feval(action,num_i1,num_i2,num_j1,num_j2,Series);
1490end
1491set(handles.RUN,'BackgroundColor',[1 0 0])
1492
1493% %save the current interface setting as figure namefig, append .0 to the name if it already exists
1494% detect=1;
1495% while detect==1
1496%     namefigfull=[namedoc '.fig'];
1497%     hh=dir(namefigfull);
1498%     if ~isempty(hh)
1499%         detect=1;
1500%         namedoc=[namedoc '.0'];
1501%     else
1502%         detect=0;
1503%     end
1504% end
1505% saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
1506
1507%----------------------------------------------------
1508function STOP_Callback(hObject, eventdata, handles)
1509set(handles.RUN, 'BusyAction','cancel')
1510set(handles.RUN,'BackgroundColor',[1 0 0])
1511
1512%----------------------------------------------
1513
1514%----------------------------------------------------
1515function first_i_Callback(hObject, eventdata, handles)
1516last_i_Callback(hObject, eventdata, handles)
1517
1518%----------------------------------------------
1519function last_i_Callback(hObject, eventdata, handles)
1520    hseries=get(handles.last_i,'parent');
1521first_i=str2num(get(handles.first_i,'String'));
1522last_i=str2num(get(handles.last_i,'String'));
1523ref_i=ceil((first_i+last_i)/2);
1524set(handles.ref_i,'String', num2str(ref_i))
1525ref_i_Callback(hObject, eventdata, handles)
1526SeriesData=get(hseries,'UserData');
1527if ~isfield(SeriesData,'Time')
1528    SeriesData.Time{1}=[];
1529end
1530displ_time(handles,SeriesData.Time{1});
1531
1532%-------------------------------------------------------
1533function first_j_Callback(hObject, eventdata, handles)
1534 last_j_Callback(hObject, eventdata, handles)
1535
1536%-------------------------------------------------------
1537function last_j_Callback(hObject, eventdata, handles)
1538    hseries=get(handles.last_i,'parent');
1539first_j=str2num(get(handles.first_j,'String'));
1540last_j=str2num(get(handles.last_j,'String'));
1541ref_j=ceil((first_j+last_j)/2);
1542set(handles.ref_j,'String', num2str(ref_j))
1543
1544ref_j_Callback(hObject, eventdata, handles)
1545SeriesData=get(hseries,'UserData');
1546if ~isfield(SeriesData,'Time')
1547    SeriesData.Time{1}=[];
1548end
1549displ_time(handles,SeriesData.Time{1});
1550
1551
1552
1553
1554%-------------------------------------------------------
1555function ref_i_Callback(hObject, eventdata, handles)
1556mode_list=get(handles.mode,'String');
1557mode_value=get(handles.mode,'Value');
1558mode=mode_list{mode_value};
1559hseries=get(handles.ref_i,'parent');
1560SeriesData=get(hseries,'UserData');
1561%NomTypeCell=get(handles.NomType,'String');
1562NomTypeCell=SeriesData.NomType;
1563if ~isempty(NomTypeCell)
1564Val=get(handles.NomType,'Value');
1565NomType=NomTypeCell{Val};
1566% for ilist=1:length(NomType)
1567    if isequal(NomType,'_i_j1-j2')|| isequal(NomType,'_i1-i2_j')|| isequal(NomType,'_i1-i2')
1568        if isequal(mode,'series(Di)')
1569            find_netcpair_civ(hObject, eventdata, handles,Val);% update the menu of pairs depending on the available netcdf files
1570%             break
1571        end
1572    end
1573end
1574
1575%----------------------------------------------------
1576function ref_j_Callback(hObject, eventdata, handles)
1577mode_list=get(handles.mode,'String');
1578mode_value=get(handles.mode,'Value');
1579mode=mode_list{mode_value};
1580hseries=get(handles.ref_i,'parent');
1581SeriesData=get(hseries,'UserData');
1582%NomTypeCell=get(handles.NomType,'String');
1583NomTypeCell=SeriesData.NomType;
1584if ~isempty(NomTypeCell)
1585Val=get(handles.NomType,'Value');
1586NomType=NomTypeCell{Val};
1587% NomType=get(handles.NomType,'String');
1588    if isequal(NomType,'_i_j1-j2')|| isequal(NomType,'_i1-i2_j')|| isequal(NomType,'_i1-i2')
1589        if isequal(mode,'series(Dj)')
1590            find_netcpair_civ(hObject, eventdata, handles,Val);% update the menu of pairs depending on the available netcdf files
1591%             break
1592        end
1593    end
1594end
1595
1596%----------------------------------------------------
1597% --- Executes on selection change in ACTION.
1598function ACTION_Callback(hObject, eventdata, handles)
1599list_ACTION=get(handles.ACTION,'String');% list menu fields
1600index_ACTION=get(handles.ACTION,'Value');% selected string index
1601ACTION= list_ACTION{index_ACTION}; % selected function name
1602path_series=which('series');%path to series.m
1603list_path=get(handles.ACTION,'UserData');%list of recorded paths to functions of the list ACTION
1604nb_builtin=0;
1605for ilist=1:length(list_path)
1606    if isequal(list_path{ilist},path_series)
1607        nb_builtin=nb_builtin+1;
1608    else
1609        break
1610    end
1611end
1612if nb_builtin==0% the path of series has been changed, reinitialize
1613    series_OpeningFcn(hObject, eventdata, handles)
1614    return
1615end
1616
1617% add a new function to the menu
1618if isequal(ACTION,'more...')
1619    pathfct=fileparts(path_series);
1620    browse_name=fullfile(path_series,'SERIES_FCT');%go to UVMAT/SERIES_FCT by default
1621    if length(list_path)>nb_builtin
1622        browse_name=list_path{end};% initialize browser with  the path of the last introduced function
1623     end
1624    [FileName, PathName, filterindex] = uigetfile( ...
1625       {'*.m', ' (*.m)';
1626        '*.m',  '.m files '; ...
1627        '*.*', 'All Files (*.*)'}, ...
1628        'Pick a file',browse_name);
1629    if length(FileName)<2
1630        return
1631    end
1632    ext_fct=FileName(end-1:end);
1633    if ~isequal(ext_fct,'.m')
1634        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
1635        return
1636    end
1637    ACTION=FileName(1:end-2);% ACTION choice updated by the selected item
1638   
1639   % insert the choice in the action menu
1640   menu_str=update_menu(handles.ACTION,ACTION);%new action menu in which the new item has been appended if needed
1641   index_ACTION=get(handles.ACTION,'Value');% currently selected index in the list
1642   list_path{index_ACTION}=PathName;
1643   if length(menu_str)>nb_builtin+5;
1644       nbremove=length(menu_str)-nb_builtin-5;
1645       menu_str(nb_builtin+1:end-5)=[];
1646       list_path(nb_builtin+1:end-4)=[];
1647       index_ACTION=index_ACTION-nbremove;
1648       set(handles.ACTION,'Value',index_ACTION)
1649       set(handles.ACTION,'String',menu_str)
1650   end
1651   list_path{index_ACTION}=PathName;
1652   set(handles.ACTION,'UserData',list_path);
1653   set(handles.path,'enable','inactive')% indicate that the current path is accessible (not 'off')
1654   
1655   %record the current menu in personal file profil_perso
1656   dir_perso=prefdir;
1657   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1658   for ilist=nb_builtin+1:length(menu_str)-1
1659       series_fct{ilist-nb_builtin}=fullfile(list_path{ilist},[menu_str{ilist} '.m']);
1660   end
1661   if exist(profil_perso,'file')
1662        save(profil_perso,'series_fct','-append')
1663   else
1664        txt=ver;
1665        Release=txt(1).Release;
1666        relnumb=str2num(Release(3:4));
1667        if relnumb >= 14
1668            save(profil_perso,'series_fct','-V6')
1669        else
1670            save(profil_perso, 'series_fct')
1671        end
1672   end
1673end
1674
1675%check the current path to the selected function
1676PathName=list_path{index_ACTION};%current recorded path
1677if ~isequal(path_series,PathName)
1678    CurrentPath=fileparts(which(ACTION));
1679    if ~isequal(PathName,CurrentPath)
1680        addpath(PathName)
1681        errormsg=check_functions;
1682        msgbox_uvmat('CONFIRMATION',[['path ' PathName ' added to the current Matlab pathes'];errormsg])
1683    end
1684end
1685set(handles.path,'String',PathName); %show the path to the senlected function
1686
1687%default setting for the visibility of the GUI elements
1688%set( handles.Field,'Visible','off')%default
1689set(handles.RootPath,'UserData','many')
1690set(handles.SubDir,'Visible','on')
1691set(handles.RootFile,'Visible','on')
1692set(handles.NomType,'Visible','on')
1693set(handles.FileExt,'Visible','on')
1694set(handles.NbSlice,'Visible','off')
1695set(handles.NbSlice_title,'Visible','off')
1696set(handles.VelTypeMenu,'Visible','off');
1697set(handles.VelType_text,'Visible','off');
1698set(handles.VelTypeMenu_1,'Visible','off');
1699set(handles.VelType_text_1,'Visible','off');
1700view_FieldMenu(handles,'off')
1701view_FieldMenu_1(handles,'off')
1702view_TRANSFORM(handles,'off')
1703set(handles.ProjObject_frame,'Visible','off');
1704set(handles.GetMask,'Visible','off')
1705set(handles.Mask,'Visible','off')
1706set(handles.GetObject,'Visible','off');
1707set(handles.ProjObject,'Visible','off');
1708set(handles.OutputDir,'Visible','off');
1709set(handles.PARAMETERS_frame,'Visible','off');
1710set(handles.PARAMETERS_title,'Visible','off');
1711set(handles.ParamKey,'Visible','off')
1712set(handles.ParamVal,'Visible','off')
1713ParamKey={};
1714set(handles.FieldMenu,'Enable','off')
1715set(handles.VelTypeMenu,'Enable','off')
1716set(handles.FieldMenu_1,'Enable','off')
1717set(handles.VelTypeMenu_1,'Enable','off')
1718set(handles.CoordType,'Enable','off')
1719%set the displayed GUI item needed for input parameters
1720%list_input=feval(ACTION);% input list asked by the selected function
1721varargout=feval(ACTION);% input list asked by the selected function
1722Param_list={};
1723% RootPath=get(handles.RootPath,'String');
1724% RootFile=get(handles.RootFile,'String');
1725
1726%nb_series=length(RootFile);
1727FileExt=get(handles.FileExt,'String');
1728nb_series=length(FileExt);
1729testima_series=1; %test for a list of images only
1730testima=1;
1731testima_1=1;
1732testciv_series=1;
1733for iview=1:nb_series
1734    ext=FileExt{iview};
1735    if length(ext)<2
1736        ext='.none';
1737    end
1738    testimaview=~isempty(imformats(ext(2:end))) || isequal(lower(ext),'.avi');
1739    if ~testimaview
1740        if iview==1
1741            testima=0;
1742        end
1743        if iview==2
1744            testima_1=0;
1745        end
1746        testima_series=0;
1747    end
1748end
1749for ilist=1:length(varargout)-1
1750    switch varargout{ilist}
1751                       %RootFile always visible
1752         case 'RootPath'   %visible by default
1753            value=lower(varargout{ilist+1});
1754            if isequal(value,'one')||isequal(value,'two')||isequal(value,'many')
1755                set(handles.RootFile,'UserData',value)% for use in menu Open_insert
1756            end
1757        case 'SubDir' %visible by default
1758            if isequal(lower(varargout{ilist+1}),'off')
1759                set(handles.SubDir,'Visible','off')
1760            end
1761        case 'RootFile'   %visible by default
1762            value=lower(varargout{ilist+1});
1763            if isequal(value,'off')
1764                set(handles.RootFile,'Visible','off')
1765            elseif isequal(value,'one')||isequal(value,'two')||isequal(value,'many')
1766                set(handles.RootFile,'Visible','on')
1767                set(handles.RootFile,'UserData',value)% for use in menu Open_insert
1768            end
1769        case 'NomType'   %visible by default
1770            if isequal(lower(varargout{ilist+1}),'off')
1771                set(handles.NomType,'Visible','off')
1772            end
1773        case 'FileExt'   %visible by default
1774            if isequal(lower(varargout{ilist+1}),'off')
1775                set(handles.FileExt,'Visible','off')
1776            end
1777        case 'NbSlice'   %hidden by default
1778            if isequal(lower(varargout{ilist+1}),'on')
1779                set(handles.NbSlice,'Visible','on')
1780                set(handles.NbSlice_title,'Visible','on')
1781            end
1782        case 'VelTypeMenu'   %hidden by default
1783            if isequal(lower(varargout{ilist+1}),'one') || isequal(lower(varargout{ilist+1}),'two')
1784                set(handles.VelTypeMenu,'Enable','on')
1785                if nb_series >=1 && ~testima_series
1786                    set(handles.VelTypeMenu,'Visible','on')
1787                    set(handles.VelType_text,'Visible','on');
1788                    set(handles.Field_frame,'Visible','on')
1789                end
1790            end
1791            if isequal(lower(varargout{ilist+1}),'two')
1792                set(handles.VelTypeMenu_1,'Enable','on')
1793                if nb_series >=2 && ~testima_series
1794                    set(handles.VelTypeMenu_1,'Visible','on')
1795                    set(handles.VelType_text_1,'Visible','on');
1796                end
1797            end
1798        case 'FieldMenu'   %hidden by default
1799            if isequal(lower(varargout{ilist+1}),'one')||isequal(lower(varargout{ilist+1}),'two')
1800                set(handles.FieldMenu,'Enable','on') % test for MenuBorser
1801                if nb_series >=1 && ~testima_series
1802                    view_FieldMenu(handles,'on')
1803                end
1804            end
1805            if isequal(lower(varargout{ilist+1}),'two')
1806                set(handles.FieldMenu_1,'Enable','on')
1807                if nb_series >=2 && ~testima_1
1808                    view_FieldMenu_1(handles,'on')
1809                end
1810            end
1811        case 'CoordType'   %hidden by default
1812            if isequal(lower(varargout{ilist+1}),'on')
1813                set(handles.CoordType,'Enable','on')
1814                view_TRANSFORM(handles,'on')
1815            end
1816        case 'GetObject'   %hidden by default
1817            if isequal(lower(varargout{ilist+1}),'on')   
1818                set(handles.ProjObject_frame,'Visible','on')
1819                set(handles.GetObject,'Visible','on');
1820            end
1821        case 'Mask'   %hidden by default
1822            if isequal(lower(varargout{ilist+1}),'on')   
1823                set(handles.ProjObject_frame,'Visible','on')
1824                set(handles.GetMask,'Visible','on');
1825            end
1826        case 'PARAMETER' 
1827            set(handles.PARAMETERS_frame,'Visible','on')
1828            set(handles.PARAMETERS_title,'Visible','on')
1829            set(handles.ParamKey,'Visible','on')
1830            %set(handles.ParamVal,'Visible','on')
1831            Param_str=varargout{ilist+1};
1832            Param_list=[Param_list; {Param_str}];         
1833    end
1834end
1835if ~isempty(Param_list)
1836    set(handles.ParamKey,'String',Param_list)
1837    set(handles.ParamVal,'Visible','on')
1838end
1839
1840%-------------------------------------------------------------------
1841% --- Executes on selection change in FieldMenu.
1842%-------------------------------------------------------------------
1843function FieldMenu_Callback(hObject, eventdata, handles)
1844
1845field_str=get(handles.FieldMenu,'String');
1846field_index=get(handles.FieldMenu,'Value');
1847field=field_str{field_index(1)};
1848if isequal(field,'get_field...')   
1849     hget_field=findobj(allchild(0),'name','get_field');
1850     if ~isempty(hget_field)
1851         delete(hget_field)%delete opened versions of get_field
1852     end
1853     hseries=get(handles.FieldMenu,'parent');
1854     SeriesData=get(hseries,'UserData');
1855     filename=SeriesData.CurrentInputFile;
1856     if exist(filename,'file')
1857        get_field(filename)
1858     end
1859elseif isequal(field,'more...')
1860    str=calc_field;
1861    [ind_answer,v] = listdlg('PromptString','Select a file:',...
1862                'SelectionMode','single',...
1863                'ListString',str);
1864       % edit the choice in the fields and action menu
1865     scalar=cell2mat(str(ind_answer));
1866     update_menu(handles.FieldMenu,scalar)
1867end
1868
1869%------------------------------------------------------
1870% --- Executes on selection change in FieldMenu_1.
1871%-----------------------------------------------------
1872function FieldMenu_1_Callback(hObject, eventdata, handles)
1873field_str=get(handles.FieldMenu_1,'String');
1874field_index=get(handles.FieldMenu_1,'Value');
1875field=field_str{field_index};
1876if isequal(field,'get_field...')   
1877     hget_field=findobj(allchild(0),'name','get_field_1');
1878     if ~isempty(hget_field)
1879         delete(hget_field)
1880     end
1881     hseries=get(handles.FieldMenu,'parent');
1882     SeriesData=get(hseries,'UserData');
1883     filename=SeriesData.CurrentInputFile_1;
1884     if exist(filename,'file')
1885        hget_field=get_field(filename);
1886        set(hget_field,'name','get_field_1')
1887     end
1888elseif isequal(field,'more...')
1889    str=calc_field;
1890    [ind_answer,v] = listdlg('PromptString','Select a file:',...
1891                'SelectionMode','single',...
1892                'ListString',str);
1893       % edit the choice in the fields and action menu
1894     scalar=cell2mat(str(ind_answer));
1895     update_menu(handles.FieldMenu_1,scalar)
1896end   
1897
1898
1899%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1900 %detect the chosen series of files and check their date of modification:
1901%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1902%INPUT:
1903%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
1904%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
1905%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
1906%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
1907%OTHER INPUTS given by the structure Series
1908function GUI_input=check_files(num_i1_cell,num_i2_cell,num_j1_cell,num_j2_cell,Series) %(filecell,filecell_1,num_i,num_j,vel_type,field,param);
1909
1910%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
1911if ~exist('num_i1_cell','var')
1912    GUI_input={'RootPath';'many';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
1913        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
1914        'RootFile';'on';... %root input file name ('on' by default)
1915        'FileExt';'on';... %input file extension ('on' by default)
1916        'NomType';'on';...%type of file indexing ('on' by default)
1917        'NbSlice';'on'; ...%nbre of slices ('off' by default)
1918        %'VelTypeMenu';'on';...% menu for selecting the velocity type (civ1,..) 'off' by default)
1919        %'FieldMenu';'on';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
1920        %'CoordType';'on'...%can use a transform function 'off' by default
1921        %'GetObject';'on'...%can use projection object ,'off' by default
1922        %'GetMask';'on'...%can use mask option   ,'off' by default
1923        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
1924               ''};
1925    return %exit the function
1926end
1927
1928%standard parameters for waitbar and STOP action (do not modify)
1929hseries=guidata(Series.hseries);%handles of the GUI series
1930WaitbarPos=get(hseries.waitbar_frame,'Position');
1931
1932%%%%%%%%%%%%%%%%%%%%%%%%
1933
1934% number of slices
1935NbSlice=str2num(get(hseries.NbSlice,'String'));
1936if isempty(NbSlice)
1937    NbSlice=1;
1938end
1939NbSlice_name=num2str(NbSlice);
1940if isequal(NbSlice,[]),NbSlice=1; end; %default
1941
1942% number of views
1943count=0;
1944testcell=iscell(Series.RootFile);
1945if ~testcell
1946    Series.RootPath={Series.RootPath};
1947    Series.RootFile={Series.RootFile};
1948    Series.SubDir={Series.SubDir};
1949    Series.FileExt={Series.FileExt};
1950    Series.NomType={Series.NomType};
1951end   
1952nbview=length(Series.RootFile);
1953for iview=1:nbview
1954    filebase=fullfile(Series.RootPath{iview},Series.RootFile{iview});%root file name
1955    if testcell
1956        num_i1=num_i1_cell{iview}; num_i2=num_i2_cell{iview}; num_j1=num_j1_cell{iview}; num_j2=num_j2_cell{iview};
1957    else
1958        num_i1=num_i1_cell; num_i2=num_i2_cell; num_j1=num_j1_cell; num_j2=num_j2_cell;
1959    end
1960    siz=size(num_i1);
1961    nbfield2=siz(1); %nb of consecutive fields at each level(burst
1962    nbfield=siz(1)*siz(2);
1963    nbfield=floor(nbfield/(nbfield2*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
1964    if isequal(lower(Series.FileExt{iview}),'.avi')
1965        info=aviinfo([filebase Series.FileExt{iview}]);
1966        message{1}=info.Filename;
1967        message{2}=info.FileModDate;
1968        message{3}=[num2str(info.FramesPerSecond) ' frames/s '];
1969        message{4}=info.ImageType;
1970        message{5}=['  compression' info.VideoCompression];
1971        message{6}=[ 'quality ' num2str(info.Quality)];   
1972        Tabchar=message;
1973    else
1974        datnum=[];
1975        Tabchar={};
1976        %LOOP ON SLICES
1977        for i_slice=1:NbSlice
1978            for ifield=1:nbfield
1979                indselect(:,ifield)=((ifield-1)*NbSlice+(i_slice-1))*nbfield2+[1:nbfield2]';%selected indices on the list of files of a slice
1980            end
1981            for index=1:nbfield*nbfield2
1982                stopstate=get(hseries.RUN,'BusyAction');
1983                if isequal(stopstate,'queue')% enable STOP command
1984                    update_waitbar(hseries.waitbar,WaitbarPos,index/(nbfield*nbfield2))
1985                    ifile=indselect(index);               
1986                    file=...
1987                       name_generator(filebase,num_i1(ifile),num_j1(ifile),Series.FileExt{iview},Series.NomType{iview},1,num_i2(ifile),num_j2(ifile),Series.SubDir{iview});               
1988                    [Path,Name,ext]=fileparts(file);
1989                    detect=exist(file,'file'); % check the existence of the file
1990                    if detect==0
1991                        count=count+1;
1992                        lastfield='not found';
1993                    else
1994                        datfile=dir(file);
1995                        datnum(ifile)=datenum(datfile.date);
1996                        filefound(ifile)={datfile.name};
1997                        lastfield='';
1998                        if isequal(Series.FileExt{iview},'.nc') || isequal(Series.FileExt{iview},'.cdf')
1999                            % check the content  netcdf file
2000                            Data=nc2struct(file,'ListGlobalAttribute','patch2','fix2','civ2','patch','fix','absolut_time_T0','hart');
2001                            if ~isempty(Data.patch2) && isequal(Data.patch2,1)
2002                                lastfield='patch2';
2003                            elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
2004                                lastfield='fix2';
2005                            elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
2006                                lastfield='civ2';
2007                            elseif ~isempty(Data.patch) && isequal(Data.patch,1);
2008                                lastfield='patch1';
2009                            elseif ~isempty(Data.fix) && isequal(Data.fix,1);
2010                                lastfield='fix1';
2011                            elseif ~isempty(Data.absolut_time_T0) && ~isempty(Data.hart)
2012                                lastfield='civ1';
2013                            end                         
2014                        end
2015                    end
2016                    Tabchar(1,i_slice)={['slice #' num2str(i_slice)]};
2017                    Tabchar(index+1,i_slice)={[file '   ' lastfield]};
2018                end
2019            end
2020        end
2021        if isempty(datnum)
2022            if NbSlice>1
2023                message=['no set of ' num2str(NbSlice) ' (NbSlices) files found'];
2024            else
2025                 message='no file found';
2026            end
2027        else
2028            datnum=datnum(find(datnum));%keep the non zero values corresponding to existing files
2029            [first,ind]=min(datnum);
2030            [last,indlast]=max(datnum);
2031            message={['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
2032                ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
2033        end
2034        if ~isempty(Tabchar)
2035          Tabchar=reshape(Tabchar,NbSlice*(nbfield*nbfield2+1),1);
2036        end
2037    end
2038    hfig=figure(iview);
2039    clf
2040    if iview>1
2041        pos=get(iview-1,'Position');
2042        pos(1)=pos(1)+(iview-1)*pos(1)/nbview;
2043        set(hfig,'Position',pos)
2044    end
2045    set(hfig,'name',['view= ' num2str(iview)])
2046   
2047    h=uicontrol('Style','listbox', 'Position', [20 20 500 300], 'String', Tabchar, 'Callback', @ncbrowser_uvmat);
2048    hh=uicontrol('Style','listbox', 'Position', [20 340 500 40], 'String', message);
2049end
2050%----------------------------------------------------
2051%  determine the list of index pairs of processing file
2052%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2053function [num_i1,num_i2,num_j1,num_j2,num_i_out,num_j_out]=find_file_indices(num_i,num_j,ind_shift,NomType,mode)
2054num_i1=num_i;% set of first image numbers by default
2055num_i2=num_i;
2056num_j1=num_j;
2057num_j2=num_j;
2058num_i_out=num_i;
2059num_j_out=num_j;
2060if isequal (NomType,'_i1-i2_j') |isequal (NomType,'_i1-i2')
2061    num_i1_line=num_i+ind_shift(3);% set of first image numbers
2062    num_i2_line=num_i+ind_shift(4);
2063    % adjust the first and last field number
2064        indsel=find(num_i1_line >= 1);
2065    num_i_out=num_i(indsel);
2066    num_i1_line=num_i1_line(indsel);
2067    num_i2_line=num_i2_line(indsel);
2068    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2069    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2070    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2071    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2072elseif isequal (NomType,'_i_j1-j2') || isequal (NomType,'#_ab')
2073    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2074        num_j1=ind_shift(1)*ones(size(num_i));
2075        num_j2=ind_shift(2)*ones(size(num_i));
2076    else
2077        num_j1_col=num_j+ind_shift(1);% set of first image numbers
2078        num_j2_col=num_j+ind_shift(2);
2079        % adjust the first field number
2080        indsel=find((num_j1_col >= 1));   
2081        num_j_out=num_j(indsel);
2082        num_j1_col=num_j1_col(indsel);
2083        num_j2_col=num_j2_col(indsel);
2084        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
2085        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
2086    end   
2087end
2088
2089
2090%----------------------------------------------------------------------
2091% --- make average on a series of files
2092%----------------------------------------------------------------------
2093%INPUT:
2094%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2095%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2096%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
2097%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
2098%OTHER INPUTS given by the structure Series
2099%  Series.Time:
2100%  Series.GeometryCalib:
2101function GUI_input=aver_stat(num_i1,num_i2,num_j1,num_j2,Series)
2102%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
2103if ~exist('num_i1','var')
2104    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
2105        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
2106        'RootFile';'on';... %root input file name ('on' by default)
2107        'FileExt';'on';... %input file extension ('on' by default)
2108        'NomType';'on';...%type of file indexing ('on' by default)
2109        'NbSlice';'on'; ...%nbre of slices ('off' by default)
2110        'VelTypeMenu';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
2111        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
2112        'CoordType'; 'on';...%can use a transform function
2113        'GetObject';'on';...%can use projection object(option 'off'/'one'/'two',
2114        %'GetMask';'on'...%can use mask option   
2115        %'PARAMETER'; %options: name of the user defined parameter',repeat a line for each parameter
2116               ''};
2117        return
2118end
2119
2120%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2121hseries=guidata(Series.hseries);%handles of the GUI series
2122WaitbarPos=get(hseries.waitbar_frame,'Position');
2123%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2124
2125%root input file and type
2126if ~iscell(Series.RootPath)% case of a single input field series
2127    num_i1={num_i1};num_j1={num_j1};num_i2={num_i2};num_j2={num_j2};
2128    RootPath={Series.RootPath};
2129    RootFile={Series.RootFile};
2130    SubDir={Series.SubDir};
2131    FileExt={Series.FileExt};
2132    NomType={Series.NomType};
2133else
2134    RootPath=Series.RootPath;
2135    RootFile=Series.RootFile;
2136    SubDir=Series.SubDir;
2137    NomType=Series.NomType;
2138    FileExt=Series.FileExt;
2139end   
2140ext=FileExt{1};
2141form=imformats(ext([2:end]));%test valid Matlab image formats
2142testima=0;
2143if ~isempty(form)||isequal(lower(ext),'.avi')||isequal(lower(ext),'.vol')
2144    testima(1)=1;
2145end
2146if length(FileExt)>=2
2147    ext_1=FileExt{2};
2148    form=imformats(ext_1([2:end]));%test valid Matlab image formats
2149    if ~isempty(form)||isequal(lower(ext_1),'.avi')||isequal(lower(ext_1),'.vol')
2150        testima(2)=1;
2151    end
2152    if testima(2)~=testima(1)
2153        msgbox_uvmat('ERROR','images and netcdf files cannot be compared')
2154        return
2155    end
2156end
2157
2158%Number of input series: this function  accepts two input file series at most (then it operates on the difference of fields)
2159nbview=length(RootPath);
2160if nbview>2 
2161    RootPath=RootPath(1:2);
2162    set(hseries.RootPath,'String',RootPath)
2163    SubDir=SubDir(1:2);
2164    set(hseries.SubDir,'String',SubDir)
2165    RootFile=RootFile(1:2);
2166    set(hseries.RootFile,'String',RootFile)
2167    NomType=NomType(1:2);
2168    FileExt=FileExt(1:2);
2169    set(hseries.FileExt,'String',FileExt)
2170    nbview=2;
2171end
2172hhh=which('mmreader');
2173for iview=1:nbview
2174    test_movie(iview)=0;
2175    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
2176        if isequal(lower(FileExt{iview}),'.avi')
2177            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
2178            test_movie(iview)=1;
2179        end
2180    end
2181end
2182
2183% number of slices
2184NbSlice=str2num(get(hseries.NbSlice,'String'));
2185if isempty(NbSlice)
2186    NbSlice=1;
2187end
2188NbSlice_name=num2str(NbSlice);
2189
2190% Field and velocity type (the same for the two views)
2191Field_str=get(hseries.FieldMenu,'String');
2192FieldName=[]; %default
2193testfield=get(hseries.FieldMenu,'Visible');
2194if isequal(testfield,'on')
2195    val=get(hseries.FieldMenu,'Value');
2196    FieldName=Field_str(val);%the same set of fields for all views
2197    if isequal(FieldName,{'get_field...'})
2198        hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
2199        if length(hget_field)>1
2200            delete(hget_field(2:end))
2201        elseif isempty(hget_field)
2202           filename=...
2203                 name_generator(fullfile(RootPath{1},RootFile{1}),num_i1{1}(1),num_j1{1}(1),FileExt{1},NomType{1},1,num_i2{1}(1),num_j2{1}(1),SubDir{1});
2204           get_field(filename);
2205           return
2206        end
2207        %hhget_field=guidata(hget_field);%handles of GUI elements in get_field
2208        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
2209    end
2210end
2211%detect whether the two files are 'images' or 'netcdf'
2212testima=0;
2213testvol=0;
2214testcivx=0;
2215testnc=0;
2216FileExt=get(hseries.FileExt,'String');
2217% test_movie=0;
2218for iview=1:nbview
2219     ext=FileExt{iview};
2220     form=imformats(ext([2:end]));
2221     if isequal(lower(ext),'.vol')
2222         testvol=testvol+1;
2223     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
2224         testima=testima+1;
2225     elseif isequal(ext,'.nc')
2226         testnc=testnc+1;
2227     end
2228end
2229if testvol
2230    msgbox_uvmat('ERROR','volume images not implemented yet')
2231    return
2232end
2233if testnc~=nbview && testima~=nbview && testvol~=nbview
2234    msgbox_uvmat('ERROR','compare two image series or two netcdf files with the same fields as input')
2235    return
2236end
2237if ~isequal(FieldName,{'get_field...'})
2238    testcivx=testnc;
2239end
2240
2241if testcivx
2242    VelType_str=get(hseries.VelTypeMenu,'String');
2243    VelType_val=get(hseries.VelTypeMenu,'Value');
2244    VelType{1}=VelType_str{VelType_val};
2245    if nbview==2
2246        VelType_str=get(hseries.VelTypeMenu_1,'String');
2247        VelType_val=get(hseries.VelTypeMenu_1,'Value');
2248        VelType{2}=VelType_str{VelType_val};
2249    end
2250end
2251
2252%Calibration data and timing: read the ImaDoc files
2253mode=''; %default
2254timecell={};
2255itime=0;
2256NbSlice_calib={};
2257for iview=1:nbview%Loop on views
2258    XmlData{iview}=[];%default
2259    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
2260    if exist([filebase{iview} '.xml'],'file')
2261        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
2262        if isfield(XmlData{iview},'Time')
2263            itime=itime+1;
2264            timecell{itime}=XmlData{iview}.Time;
2265        end
2266        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
2267            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
2268            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
2269                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
2270            end
2271        end
2272    elseif exist([filebase{iview} '.civ'],'file')
2273        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
2274        itime=itime+1;
2275        timecell{itime}=time;
2276        XmlData{iview}.Time=time;
2277        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
2278        GeometryCalib.Tx=0;
2279        GeometryCalib.Ty=0;
2280        GeometryCalib.Tz=1;
2281        GeometryCalib.dpx=1;
2282        GeometryCalib.dpy=1;
2283        GeometryCalib.sx=1;
2284        GeometryCalib.Cx=0;
2285        GeometryCalib.Cy=0;
2286        GeometryCalib.f=1;
2287        GeometryCalib.kappa1=0;
2288        GeometryCalib.CoordUnit='cm';
2289        XmlData{iview}.GeometryCalib=GeometryCalib;
2290        if error==1
2291            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
2292        end
2293    end
2294end
2295
2296%check coincidence in time
2297multitime=0;
2298if length(timecell)==0
2299    time=[];
2300elseif length(timecell)==1
2301    time=timecell{1};
2302elseif length(timecell)>1
2303    multitime=1;
2304    for icell=1:length(timecell)
2305        if ~isequal(size(timecell{icell}),size(timecell{1}))
2306            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
2307            time=timecell{1};
2308            multitime=0;
2309            break
2310        end
2311    end
2312end
2313if multitime
2314    for icell=1:length(timecell)
2315        time(icell,:,:)=timecell{icell};
2316    end
2317    diff_time=max(max(diff(time)));
2318    if diff_time>0
2319        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
2320    end   
2321end
2322if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
2323    time=[];
2324end
2325
2326% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
2327filebasesub=fullfile(RootPath{1},SubDir{1},RootFile{1});
2328if isempty(SubDir{1}) % create a subdirectory '/mean'
2329    subdir_result='mean';
2330%     filebasemean=fullfile(RootPath{1},subdir_result);
2331    if ~exist(fullfile(RootPath{1},subdir_result),'dir')
2332        dircur=pwd; %record current working directory
2333        cd(RootPath{1})% goes to the iamge directory
2334        [m1,m2,m3]=mkdir(subdir_result);
2335        if ~isequal(m2,'')
2336             msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
2337        end
2338        cd(dircur) %back to the initial working directory
2339    end
2340    filebase_out=filebase{1};
2341else
2342   subdir_result=SubDir{1};
2343   filebase_out=[filebase{1} '_mean'];% output root name obtained by adding the suffix _mean to the input
2344end
2345%output nomtype (to generalise)
2346NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
2347   
2348if NbSlice==1 
2349    filebase_out=[filebasesub '_mean'];
2350else
2351    filebase_out=[filebasesub '_' NbSlice_name 'mean'];
2352    answeryes=questdlg({['will make average in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_out ' ...']});
2353    if ~isequal(answeryes,'Yes')
2354        return
2355    end
2356end
2357
2358% coordinate transform or other user defined transform
2359Coord_menu=get(hseries.CoordType,'String');
2360menu_val=get(hseries.CoordType,'Value');
2361usrfct=Coord_menu{menu_val};
2362testfct=~isequal(usrfct,'');
2363
2364%slice loop
2365siz=size(num_i1{1});
2366lengthtot=siz(1)*siz(2);
2367nbfield=floor(lengthtot/(siz(1)*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
2368nbfield_slice=nbfield*siz(1);% number of fields per slice
2369
2370for i_slice=1:NbSlice
2371   S=0; %initiate the image sum S
2372   nbfiles=0;
2373   nbmissing=0;
2374    %averaging loop
2375   for ifile=i_slice:NbSlice:lengthtot
2376        stopstate=get(hseries.RUN,'BusyAction');
2377        if isequal(stopstate,'queue') % enable STOP command
2378             update_waitbar(hseries.waitbar,WaitbarPos,ifile/lengthtot)
2379             for iview=1:nbview
2380                [filename]=...
2381                           name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),FileExt{iview},NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile),SubDir{iview});
2382                if testima
2383                    Data{iview}.ListVarName={'A'};
2384                    Data{iview}.AName='image';
2385                    if test_movie(iview)
2386                        Data{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
2387                    else
2388                        Data{iview}.A=read_image(filename,NomType{iview},num_i1{iview}(ifile));% read the image, num2 is the counter for avi files
2389                    end
2390                    Atype{iview}=class(Data{iview}.A);
2391                    Data{iview}.A=double(Data{iview}.A);
2392                elseif testcivx
2393                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
2394                else
2395                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
2396                    Data{iview}.VarAttribute=SubField.VarAttribute;
2397                end
2398                if isfield(Data{iview},'Txt')
2399                    msgbox_uvmat('ERROR',['error of input reading: ' Data{iview}.Txt])
2400                    return
2401                end
2402             end   
2403             % coordinate transform (or other user defined transform)
2404             if ~isequal(Series.CoordType,'')
2405                 % z index
2406                if ~isempty(NbSlice_calib)
2407                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;%Zindex for phys transform
2408                end
2409                if nbview==2
2410                    [Data{1},Data{2}]=feval(Series.CoordType,Data{1},XmlData{1},Data{2},XmlData{2});
2411                    if isempty(Data{2})
2412                        Data(2)=[];
2413                    end
2414                else
2415                    Data{1}=feval(Series.CoordType,Data{1},XmlData);
2416                end
2417             end     
2418            if testcivx
2419                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
2420            end
2421            if length(Data)==2
2422                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
2423                if ~isempty(errormsg)
2424                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
2425                    return
2426                end
2427            else
2428                Field=Data{1};
2429            end
2430            if isfield(Series,'ProjObject')
2431                [Field,errormsg]=proj_field(Field,Series.ProjObject);
2432                 if ~isempty(errormsg)
2433                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
2434                    return
2435                end
2436             end                                                       
2437                nbfiles=nbfiles+1;
2438                if nbfiles==1 %first field
2439                    time_1=[];
2440                    if isfield(Field,'Time')
2441                        time_1=Field.Time(1);
2442                    end
2443                    DataMean=Field;%default
2444                else
2445                    for ivar=1:length(Field.ListVarName)
2446                        VarName=Field.ListVarName{ivar};
2447                        eval(['sizmean=size(DataMean.' VarName ');']);
2448                        eval(['siz=size(Field.' VarName ');']);
2449                        if ~isequal(siz,sizmean)
2450                            warndlg_uvmat(['unequal size of input field ' VarName ', need to interpolate on a grid'],'WARNING')
2451                            nbmissing=nbmissing+1;
2452                            break
2453                        else
2454                            eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
2455                        end
2456                    end
2457                end
2458%             else
2459%                 nbmissing=nbmissing+1;
2460%             end
2461        end
2462    end %end averaging loop
2463    for ivar=1:length(Field.ListVarName)
2464        VarName=Field.ListVarName{ivar};
2465        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
2466    end
2467    if nbmissing~=0
2468        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
2469    end
2470    if isempty(time) % time read from files  prevails
2471        time_end=[];
2472        if isfield(Field,'Time')
2473            time_end=Field.Time(1);%last time read
2474            if ~isempty(time_1)
2475                DataMean.Time=time_1;
2476                DataMean.Time_end=time_end;
2477            end
2478        end
2479    else  % time from ImaDoc prevails
2480        DataMean.Time=time(1,num_i1{1}(1),num_j1{1}(1));
2481        DataMean.Time_end=time(end,num_i1{end}(end),num_j1{end}(end));
2482    end
2483   
2484    %writing the result file
2485   if testima   
2486       if NbSlice==1
2487        [filemean]=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.png',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end));
2488       else % label the file number by the slice # for simplicity
2489          [filemean]=name_generator(filebase_out,i_slice,1,'.png','_i');
2490       end
2491        if exist(filemean,'file')
2492            backupfile=filemean;
2493            testexist=2;
2494            while testexist==2
2495                backupfile=[backupfile(1:end-4) '~.png'];
2496                testexist=exist(backupfile,'file');
2497            end
2498            [success,message]=copyfile(filemean,backupfile);%make backup
2499            if ~isequal(success,1)
2500                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
2501                return
2502            end
2503        end
2504        if isequal(Atype{1},'uint16')
2505            imwrite(uint16(DataMean.A),filemean,'BitDepth',16);
2506        else
2507            imwrite(uint8(DataMean.A),filemean,'BitDepth',8);
2508        end
2509        display([filemean ' written']);
2510    else %determine global attributes
2511        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Series.Action}];
2512        ActionKey='Action';
2513        while isfield(DataMean,ActionKey)
2514            ActionKey=[ActionKey '_1'];
2515        end
2516        eval(['DataMean.' ActionKey '=Series.Action;'])
2517        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
2518        if isfield(DataMean,'Time')
2519            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
2520        end 
2521        if NbSlice==1
2522          filemean=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.nc',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end));
2523        else % label the file number by the slice # for simplicity
2524          [filemean]=name_generator(filebase_out,i_slice,1,'.nc','_i');
2525        end
2526        if exist(filemean,'file')
2527            backupfile=filemean;
2528            testexist=2;
2529            while testexist==2
2530                backupfile=[backupfile(1:end-3) '~.nc'];
2531                testexist=exist(backupfile,'file');
2532            end
2533            [success,message]=copyfile(filemean,backupfile);%make backup
2534            if ~isequal(success,1)
2535                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
2536                display(['previous file result ' filemean ' already exists, problem in backup'])
2537                return
2538            end
2539        end
2540        errormsg=struct2nc(filemean,DataMean); %save result file
2541        if isempty(errormsg)
2542            display([filemean ' written']);
2543        else
2544            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
2545            display(errormsg)
2546        end
2547   end
2548end
2549hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
2550delete(hget_field)
2551'TEST'
2552uvmat(filemean)
2553
2554
2555% %----------------------------------------------------------------------
2556% % --makes a time averaged velocity field
2557% %----------------------------------------------------------------------
2558% function aver_vel(num_i1,num_i2,num_j1,num_j2,Series)
2559%                           %handles of the GUI series
2560%   
2561% hseries=guidata(Series.hseries);%handles of the GUI series
2562% WaitbarPos=get(hseries.waitbar_frame,'Position');
2563% Field_list=get(hseries.FieldMenu,'String');
2564% val=get(hseries.FieldMenu,'Value');
2565% FieldName=Field_list{val(1)};
2566% set(hseries.FieldMenu,'Value',val(1))% select only one input field
2567% if isequal(FieldName,'get_field...')
2568%     hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
2569% end
2570% %root input file and type
2571% RootPath=get(hseries.RootPath,'String');
2572% SubDir=get(hseries.SubDir,'String');
2573% RootFile=get(hseries.RootFile,'String');
2574% %NomType=get(hseries.NomType,'String');
2575% NomType=Series.NomType;
2576% FileExt=get(hseries.FileExt,'String');
2577% ext=FileExt{1};     
2578% VelType_str=get(hseries.VelTypeMenu,'String');
2579% VelType_val=get(hseries.VelTypeMenu,'Value');
2580% VelType{1}=VelType_str{VelType_val};
2581%
2582% time=0; %default
2583% % number of slices
2584% NbSlice=str2num(get(hseries.NbSlice,'String'));
2585% if isempty(NbSlice)
2586%     NbSlice=1;
2587% end
2588% NbSlice_name=num2str(NbSlice);
2589% filebase=fullfile(RootPath{1},RootFile{1});
2590% Calib=[];
2591% if exist([filebase '.xml'],'file')
2592%     %[error,Heading,nom_type_read,ext_ima_read,time_imadoc,TimeUnit,mode,NbSlice,npx,npy,Calib]=read_imadoc([filebase '.xml']);
2593%     [XmlData,warntext]=imadoc2struct([filebase '.xml']);
2594% end
2595% if NbSlice==1
2596%    filebase_mean=[filebase '_mean']; %root name for the result
2597% else
2598%    filebase_mean=[filebase '_' NbSlice_name 'mean']; %root name for the results
2599%    answeryes=questdlg({['will make average in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_mean ' ...']});
2600%     if ~isequal(answeryes,'Yes')
2601%     return
2602%     end
2603% end
2604% siz=size(num_i1);
2605% nbfield2=siz(1); %nb of consecutive fields at each level(burst)
2606% lengthtot=siz(1)*siz(2);
2607% nbfield=floor(lengthtot/(nbfield2*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
2608% nbfield_slice=nbfield*nbfield2;% number of fields per slice
2609% %projection object
2610% GridX=[];
2611% GridY=[];
2612% if isfield(Series,'sethandles')
2613%         Series.ProjObject=read_set_object(Series.sethandles);
2614%         if isfield(Series.ProjObject,'Style')
2615%             answeryes=questdlg({['statistics on field series projected on ' Series.ProjObject.Style]});
2616%             if ~isequal(answeryes,'Yes')
2617%                 return
2618%             end
2619%         end
2620% end
2621%
2622% %LOOP ON SLICES
2623% for i_slice=1:NbSlice
2624%     %select the series of image indices at the level islice
2625%     for ifield=1:nbfield
2626%         indselect(:,ifield)=((ifield-1)*NbSlice+(i_slice-1))*nbfield2+[1:nbfield2]';%selected indices on the list of files of a slice
2627%     end 
2628%     %name of result file
2629%     [filemean,idetect]=...
2630%                name_generator(filebase_mean,num_i1(i_slice),num_j1(1),Series.FileExt{1},'_i1-i2_j1-j2',1,num_i2(i_slice+nbfield_slice*NbSlice-1),num_j2(end),Series.SubDir{1});
2631%
2632%     % field=get(handles.civ1,'UserData');%read current selected field type (civ1,civ2...)
2633%     itime=0;
2634%      dt=[];
2635%      %LOOP ON FIELDS IN  A SLICE
2636%      test_interpolate=0;%default
2637%     for index=1:nbfield*nbfield2
2638%             ifile=indselect(index);
2639%         stopstate=get(hseries.RUN,'BusyAction');
2640%         if isequal(stopstate,'queue')% enable STOP command
2641%             update_waitbar(hseries.waitbar,WaitbarPos,ifile/(nbfield*nbfield2))
2642%             %name of the current file
2643%             [filename,idetect]=name_generator(filebase,num_i1(ifile),num_j1(ifile),Series.FileExt{1},Series.NomType{1},1,num_i2(ifile),num_j2(ifile),Series.SubDir{1});
2644%             %read input file
2645%             itime=itime+1;
2646%             if isequal(FieldName,'get_field...')
2647%                 hhget_field=guidata(hget_field);%handles of GUI elements in get_field
2648%                 hObject=0;
2649%                 eventdata=0;
2650%                 SubField=get_field('read_var_names',hObject,eventdata,hhget_field); %read the names of the variables to plot in the get_field GUI
2651%                 [Data,var_detect]=nc2struct(filename,SubField.ListVarName); %read input data   
2652%                 time(itime)=itime;
2653%                 dt=1;
2654%                 Calib_read=[];
2655%             else
2656%                 [nb_coord,nb_dim,Civ,CivStage,timeread,Data,VelTypeOut,Calib_read]=read_ncfield(filename,VelType{1});%reading the first file
2657%                  time(itime)=timeread;
2658%                 if isequal(Civ,1)
2659%                     Data.CoordType='px';%test for pixel coordinates
2660%                     if isequal(itime,1)
2661%                         dt=Data.dt;
2662%                     elseif ~isequal(Data.dt,dt)
2663%                         warndlg_uvmat('series with non constant dt, need phys coordinates','ERROR')
2664%                         return
2665%                     end
2666%                 end
2667%             end
2668%             %increment the detected fields, skip the others
2669%             if idetect==0
2670%                 warndlg_uvmat(['input file ' filename ' not found'],'ERROR')
2671%                 %A FAIRE STOCKER LE RESULT ACTUEL S'IL EXISTE
2672%             end
2673% %             itime=itime+1;
2674% %             time(itime)=timeread;
2675%       
2676%             %coordinate transform
2677%             if isempty(Calib)
2678%                 Calib=Calib_read;%use Calib from xml file in priority, then Calib from the current file
2679%             end
2680%             if ~isequal(Series.CoordType,'')
2681%                 Data=feval(Series.CoordType,Data,Calib);
2682%             end
2683%             %projection on object if defined
2684%             if isfield(Series,'ProjObject');
2685%                 Data=proj_field(Data,Series.ProjObject);
2686%                 if isequal(itime,1)%use the positions on the first field for the whole series, ou utiliser grille
2687%                     if isfield(Data,'Txt')%display error message
2688%                         warndlg(Data.Txt,'ERROR')
2689%                         return
2690%                     end
2691%                 end
2692%             else%remove false vectors and interpolate on the positions of the first field
2693%                 Data=document_field(Data);
2694%                 Data.Style='plane';
2695%             end
2696%     %%%%%%%%% initiate the average at the first iteration: check list and structure of variables
2697%             if ifile==i_slice%first field in the slice
2698%                 testfalse=0;
2699%                 ListIndex={};
2700%                 testnewcell=1;
2701%                 %group the variables (fields of 'Data') in cells of variables with the same dimensions
2702%                 [DimVarIndex,CellVarIndex]=find_field_indices(Data);
2703%                 VarIndex=CellVarIndex{1}; % ONLY THE FIRST VAR GROUP IS AVERAGED
2704%                 DimIndex=Data.VarDimIndex{VarIndex(1)};%indices of the dimensions of the first variable (common to all variables in the cell)         
2705%                 MeanData=Data;%transfer heading
2706%                 MeanData.Time=[time(1) time(end)];
2707%                 MeanData.Action=Series.Action;%name of the processing programme
2708%                 MeanData.ListDimName=Data.ListDimName(DimIndex);%name of dimension
2709%                 MeanData.DimValue=Data.DimValue(DimIndex);%values of dimension (nbre of vectors)
2710%                 MeanData.ListVarName=Data.ListVarName;
2711%                 MeanData.VarDimIndex=Data.VarDimIndex;
2712%                 MeanData.ListVarAttribute={'Role'};%list of variable attribute names A FAIRE: transferer les autres attributs
2713%                 testsum=ones(size(VarIndex));
2714%                 indexfalse=0;
2715%                 CoordName={};
2716%                 indexremove=[];
2717%                 if isfield(Data,'Role') % look for coordinate and flag variables   
2718%                     for ivar=1:length(VarIndex)
2719%                         VarName=Data.ListVarName{VarIndex(ivar)};
2720%                         var_role=Data.Role{VarIndex(ivar)};%'role' of the variable
2721%                         MeanData.Role{ivar}=var_role;
2722%                         if isequal(var_role,'falseflag')
2723%                             indexfalse=ivar; %test for false flag
2724%                             indexremove=ivar;
2725%                             FFName=VarName;
2726%                             testsum(ivar)=0;
2727%                             eval(['MeanData=rmfield(MeanData,''' VarName ''');']);%remove variable                     
2728%                         end
2729%                         if isequal(var_role,'warnflag')                       
2730%                             testsum(ivar)=0; %do not sum warn flag
2731%                             eval(['MeanData=rmfield(MeanData,''' VarName ''');']);%remove variable
2732%                             indexremove=[indexremove ivar];
2733%                         end                 
2734%                         if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|isequal(var_role,'coord_z')
2735%                             eval(['MeanData.' VarName '=Data.' VarName ';']);
2736%                             testsum(ivar)=0;
2737%                             eval(['CoordName=[CoordName ''' VarName '''];']);
2738%                         end
2739%                         if testsum(ivar)~=0
2740%                            eval(['MeanData.' VarName '=zeros(size(Data.' VarName '));']);%initialise sum
2741%                         end
2742%                     end
2743%                 end
2744%                 findsum=find(testsum);
2745%                 VarIndexSum=VarIndex(findsum);%indices of variables to sum (not coordinates nor flags)
2746%                 if length(CoordName)==0
2747%                     if isempty(DimVarIndex)|isequal(DimVarIndex,0)% no coordinate variable for structured coordinates, prepare histograms
2748%                          for ilist=1:length(VarIndexSum)
2749%                             VarName=Data.ListVarName{VarIndexSum(ilist)};
2750%                             eval(['MeanData=rmfield(MeanData,''' VarName ''');']);%remove variable
2751%                             indexremove=[indexremove ilist];
2752%                             eval(['[MeanData.' VarName 'hist,MeanData.' VarName 'val]=hist(Data.' VarName ',100);']);%make histo
2753%                             eval(['sizhist=size(MeanData.' VarName 'hist);'])
2754%                             if sizhist(1)==1
2755%                                 eval(['MeanData.' VarName 'hist=MeanData.' VarName 'hist'';'])
2756%                             end
2757%                             eval(['maxval=max(MeanData.' VarName 'val);']);
2758%                             eval(['minval=min(MeanData.' VarName 'val);']);
2759%                             dC(ilist)=(maxval-minval)/100;%size of the histogram bin   
2760%                          end
2761%                     else
2762% %                         icoord=0;
2763% %                         for ilist=1:length(DimVarIndex) 
2764% %                             VarDim=Data.ListVarName{DimVarIndex(ilist)};
2765% %                             icoord=icoord+1;
2766% %                             % eval(['Coord{' num2str(icord) '}=[' CoordName ''' VarName ''']']);
2767% %                              %eval(['Data.' CoordName{icoord} '=Data.' CoordName{icoord} '(indsel);']);
2768% %                         end
2769%                     end
2770%                 end
2771%                 if ~isempty(indexremove)
2772%                     MeanData.ListVarName(VarIndex(indexremove))=[];
2773%                     MeanData.VarDimIndex(VarIndex(indexremove))=[];
2774%                     if isfield(MeanData,'Role')%generaliser aus autres attributs
2775%                         MeanData.Role(VarIndex(indexremove))=[];
2776%                     end
2777%                 end
2778%                % END OF INITIALISATION
2779%
2780%             end
2781%       
2782%          % A FAIRE: regular grid if coord_x undefined
2783%             if indexfalse~=0 %suppress false data
2784%                  eval(['testexist=isfield(Data,''' FFName ''');'])
2785%                 if testexist
2786%                     eval(['indsel=find(Data.' FFName '==0);']);
2787%                     for icoord=1:length(CoordName)
2788%                         eval(['Data.' CoordName{icoord} '=Data.' CoordName{icoord} '(indsel);']);
2789%                     end
2790%                 end
2791%             end
2792%             for ilist=1:length(VarIndexSum)
2793%                 VarName=Data.ListVarName{VarIndexSum(ilist)};
2794%                 if indexfalse~=0 & testexist
2795%                     eval(['Data.' VarName '=Data.' VarName '(indsel);']);
2796%                 end
2797%                 if length(CoordName)==0%no variable use dfor unstructured coordinates
2798%                     if isempty(DimVarIndex)|isequal(DimVarIndex,0)% no coordinate variable for structured coordinates
2799% %                         %update histogram with the current field #ifile
2800%                         str_left=['[MeanData.' VarName 'val,MeanData.' VarName 'hist]='];
2801%                         str_right=['hist_update(MeanData.' VarName 'val,MeanData.' VarName 'hist,Data.' VarName ',dC(ilist));'];
2802%                         eval([str_left str_right]);%update global histo
2803%                     else
2804%                        %INTERPOLER
2805%                             
2806%                         eval(['MeanData.' VarName '=MeanData.' VarName '+Data.' VarName ';']);%increment sum%CAS x,y change
2807%                     end
2808%                 else   
2809%                     if length(CoordName)==2
2810%                         eval(['test_interp= ~isequal(Data.' CoordName{1} ',MeanData.' CoordName{1} ...
2811%                             ')|~isequal(Data.' CoordName{2} ',MeanData.' CoordName{2} ');'])
2812%                         if test_interp
2813%                             eval(['Data.' VarName '=griddata_uvmat(Data.' CoordName{1} ',Data.' CoordName{2}...
2814%                                 ',Data.' VarName ',MeanData.' CoordName{1} ',MeanData.' CoordName{2} ');']);
2815%                             test_interpolate=1;
2816%                         end
2817%                     end
2818%                     eval(['MeanData.' VarName '=MeanData.' VarName '+Data.' VarName ';']);%increment sum
2819%                 end
2820%             end
2821%         end
2822%     end
2823%     if length(CoordName)~=0 | ~isequal(DimVarIndex,0)% no coordinate variable for structured coordinates
2824%         for ilist=1:length(VarIndexSum) 
2825%             VarName=Data.ListVarName{VarIndexSum(ilist)};
2826%             eval(['MeanData.' VarName '=MeanData.' VarName '/itime;']);%normalize sum by the number of fields
2827%         end
2828%     else
2829%         MeanData.NbDim=1;
2830%         MeanData.ListDimName={};
2831%         MeanData.DimValue=[];
2832%         for ilist=1:length(VarIndexSum) 
2833%             VarName=Data.ListVarName{VarIndexSum(ilist)};
2834%             MeanData.ListVarName=[MeanData.ListVarName {[VarName 'val']} {[VarName 'hist']}];
2835%             MeanData.VarDimIndex=[MeanData.VarDimIndex {[ilist]} {[ilist]}];
2836%             MeanData.ListDimName=[MeanData.ListDimName {[VarName 'val']}];
2837%             eval(['MeanData.DimValue=[MeanData.DimValue length(MeanData.' VarName 'val)];']);
2838%         end   
2839%     end
2840%     figure
2841%     haxes=axes;
2842%     plot_field(MeanData,haxes)%plot the resulting average
2843%     % change variable names for consitency with civ1 data (need to generalize these programs)
2844%     if length(MeanData.ListVarName) >= 4 & isequal(MeanData.ListVarName(1:4), {'X'  'Y'  'U'  'V'})
2845%        MeanData.ListGlobalAttribute={'nb_coord','nb_dim','dt','absolut_time_T0','pixcmx','pixcmy','hart','civ','fix'};
2846%        MeanData.nb_coord=2;
2847%        MeanData.nb_dim=2;
2848%        MeanData.dt=1;
2849%        MeanData.absolut_time_T0=0;
2850%        MeanData.pixcmx=1; %pix per cm (1 by default)
2851%        MeanData.pixcmy=1; %pix per cm (1 by default)
2852%        MeanData.hart=0;
2853%        if isequal(Data.CoordType,'px')
2854%          MeanData.civ=1;
2855%       else
2856%          MeanData.civ=0;
2857%        end
2858%       MeanData.fix=0;
2859%         MeanData.ListVarName(1:4)={'vec_X'  'vec_Y'  'vec_U'  'vec_V'};
2860%         MeanData.vec_X=MeanData.X;
2861%         MeanData.vec_Y=MeanData.Y;
2862%         MeanData.vec_U=MeanData.U;
2863%         MeanData.vec_V=MeanData.V;
2864%     end
2865%     error=struct2nc(filemean,MeanData); %save result file
2866%     if isequal(error,0)
2867%         if test_interpolate
2868%             'fields interpolated to the positions of the first one'
2869%         end
2870%         [filemean ' written']
2871%     else
2872%         warndlg_uvmat(error,'ERROR')
2873%     end
2874% end
2875
2876%----------------------------------------------------------------------
2877% --project fields on a projection object (e. g. a regular grid), possibly
2878% merge several fields
2879%----------------------------------------------------------------------
2880%INPUT:
2881%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2882%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2883%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
2884%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
2885%OTHER INPUTS given by the structure Series
2886function GUI_input=merge_proj(num_i1,num_i2,num_j1,num_j2,Series);
2887
2888%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
2889if ~exist('num_i1','var')
2890    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
2891        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
2892        'RootFile';'on';... %root input file name ('on' by default)
2893        'FileExt';'on';... %input file extension ('on' by default)
2894        'NomType';'on';...%type of file indexing ('on' by default)
2895        'NbSlice';'on'; ...%nbre of slices ('off' by default)
2896        'VelTypeMenu';'one';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
2897        'FieldMenu';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
2898        'CoordType';'on';...%can use a transform function 'off' by default
2899        'GetObject';'on';...%can use projection object ,'off' by default
2900        %'GetMask';'on'...%can use mask option   ,'off' by default
2901        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
2902               ''};
2903    return %exit the function
2904end
2905
2906%-------------------------------------------------
2907hseries=guidata(Series.hseries);%handles of the GUI series
2908WaitbarPos=get(hseries.waitbar_frame,'Position'); %positiopn of waitbar frame
2909%-------------------------------------------------
2910
2911%numbers of view fields (nbre of inputs in RootPath)
2912testcell=iscell(Series.RootFile);
2913if ~testcell
2914    Series.RootPath={Series.RootPath};
2915    Series.RootFile={Series.RootFile};
2916    Series.SubDir={Series.SubDir};
2917    Series.FileExt={Series.FileExt};
2918    Series.NomType={Series.NomType};
2919    num_i1={num_i1};
2920    num_i2={num_i2};
2921    num_j1={num_j1};
2922    num_j2={num_j2};
2923end
2924nbview=length(Series.RootFile);%number of views (file series to merge)
2925nbfield=size(num_i1{1},1)*size(num_i1{1},2);%number of fields in the time series
2926transform=Series.CoordType; %  field transform function
2927hhh=which('mmreader');
2928for iview=1:nbview
2929    test_movie(iview)=0;
2930    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
2931        if isequal(lower(FileExt{iview}),'.avi')
2932            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
2933            test_movie(iview)=1;
2934        end
2935    end
2936end
2937
2938%Calibration data and timing: read the ImaDoc files
2939mode=''; %default
2940timecell={};
2941itime=0;
2942NbSlice_calib={}; %test for z index
2943for iview=1:nbview%Loop on views
2944    XmlData{iview}=[];%default
2945    filebase{iview}=fullfile(Series.RootPath{iview},Series.RootFile{iview});
2946    if exist([filebase{iview} '.xml'],'file')
2947        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
2948        if isfield(XmlData{iview},'Time')
2949            itime=itime+1;
2950            timecell{itime}=XmlData{iview}.Time;
2951        end
2952        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
2953            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);
2954            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
2955                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
2956            end
2957        end   
2958    elseif exist([filebase{iview} '.civ'],'file')
2959        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
2960        itime=itime+1;
2961        timecell{itime}=time;
2962        XmlData{iview}.Time=time;
2963        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
2964        GeometryCalib.Tx=0;
2965        GeometryCalib.Ty=0;
2966        GeometryCalib.Tz=1;
2967        GeometryCalib.dpx=1;
2968        GeometryCalib.dpy=1;
2969        GeometryCalib.sx=1;
2970        GeometryCalib.Cx=0;
2971        GeometryCalib.Cy=0;
2972        GeometryCalib.f=1;
2973        GeometryCalib.kappa1=0;
2974        GeometryCalib.CoordUnit='cm';
2975        XmlData{iview}.GeometryCalib=GeometryCalib;
2976        if error==1
2977            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
2978        end
2979    end
2980end
2981
2982%check coincidence in time
2983multitime=0;
2984if length(timecell)==0
2985    time=[];
2986elseif length(timecell)==1
2987    time=timecell{1};
2988elseif length(timecell)>1
2989    multitime=1;
2990    for icell=1:length(timecell)
2991        if ~isequal(size(timecell{icell}),size(timecell{1}))
2992            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
2993            time=timecell{1};
2994            multitime=0;
2995            break
2996        end
2997    end
2998end
2999if multitime
3000    for icell=1:length(timecell)
3001        time(icell,:,:)=timecell{icell};
3002    end
3003    diff_time=max(max(diff(time)));
3004    if diff_time>0
3005        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
3006    end   
3007end
3008if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
3009    time=[];
3010end
3011
3012% Field and velocity type (the same for all views)
3013Field_str=get(hseries.FieldMenu,'String');
3014val=get(hseries.FieldMenu,'Value');
3015FieldName=Field_str(val);%the same set of fields for all views
3016VelType_str=get(hseries.VelTypeMenu,'String');
3017VelType_val=get(hseries.VelTypeMenu,'Value');
3018VelType=VelType_str{VelType_val}; %the same for all views
3019if isequal(FieldName,'get_field...')
3020    hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
3021   % hhget_field=guidata(hget_field);%handles of GUI elements in get_field
3022    SubField=get_field('read_get_field',hObject,eventdata,hget_field); %read the names of the variables to plot in the get_field GUI
3023%     if isequal(get(hhget_field.menu_coord,'Visible'),'on')
3024%         list_transform=get(hhget_field.menu_coord,'String');
3025%         val_list=get(hhget_field.menu_coord,'Value');
3026%         transform=list_transform{val_list};
3027%     end
3028end
3029%detect whether all the files are 'images' or 'netcdf'
3030testima=0;
3031testvol=0;
3032testcivx=0;
3033testnc=0;
3034FileExt=get(hseries.FileExt,'String');
3035for iview=1:nbview
3036     ext=FileExt{iview};
3037     form=imformats(ext([2:end]));
3038     if isequal(lower(ext),'.vol')
3039         testvol=testvol+1;
3040     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
3041         testima=testima+1;
3042     elseif isequal(ext,'.nc')
3043         testnc=testnc+1;
3044     end
3045end
3046if testvol
3047    msgbox_uvmat('ERROR','volume images not implemented yet')
3048    return
3049end
3050if testnc~=nbview && testima~=nbview && testvol~=nbview
3051    msgbox_uvmat('ERROR','need a set of images or a set of netcdf files with the same fields as input')
3052    return
3053end
3054if ~isequal(FieldName,'get_field...')
3055    testcivx=testnc;
3056end
3057%name of output files and directory:
3058% res_subdir=fullfile(Series.RootPath{1},[Series.SubDir{1} '_STAT']);
3059ProjectDir=fileparts(fileparts(Series.RootPath{1}));% preoject directory (GERK)
3060prompt={['result directory (in' ProjectDir ')']};
3061RootPath=get(hseries.RootPath,'String');
3062SubDir=get(hseries.SubDir,'String');
3063if isequal(length(RootPath),1)
3064    fulldir=RootPath{1};
3065    subdir='GRID';
3066    res_subdir=fullfile(fulldir,subdir);
3067else
3068    def={fullfile(ProjectDir,'0_RESULTS')};
3069    dlgTitle='result directory';
3070    lineNo=1;
3071    answer=msgbox_uvmat('INPUT_TXT',dlgTitle,def);
3072    fulldir=answer{1};
3073    subdir=[];
3074    dirlist=sort(Series.RootFile);
3075    for iview=1:nbview
3076        if ~isempty(subdir)
3077            subdir=[subdir '-'];
3078        end
3079        subdir=[subdir dirlist{iview}];
3080    end 
3081    res_subdir=fullfile(fulldir,subdir);
3082end
3083ext=FileExt{1};
3084if ~exist(fulldir,'dir')
3085    msgbox_uvmat('ERROR',['directory ' fulldir ' needs to be created'])
3086    return
3087end
3088if ~exist(res_subdir,'dir')
3089    dircur=pwd;
3090    cd(fulldir)
3091    error=mkdir(subdir);
3092    cd(dircur)
3093end
3094filebasesub=fullfile(res_subdir,Series.RootFile{1});
3095filebase_merge=fullfile(res_subdir,'merged');%root name for the merged files
3096
3097%projection object
3098if isfield(Series,'sethandles')
3099    if ishandle(Series.sethandles.set_object)
3100        Series.ProjObject=read_set_object(Series.sethandles);
3101        if ~isfield(Series.ProjObject,'Style')
3102            msgbox_uvmat('ERROR','Undefined projection object style')
3103            return
3104        end
3105        if ~isequal(Series.ProjObject.Style,'plane')
3106            msgbox_uvmat('ERROR','The projection object must be a plane')
3107            return
3108        end
3109    end
3110end
3111
3112    %MAIN LOOP
3113for ifile=1:nbfield               
3114    stopstate=get(hseries.RUN,'BusyAction');
3115    if isequal(stopstate,'queue')% enable STOP command from the 'series' interface
3116         update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
3117         Amerge=0;
3118         
3119         %----------LOOP ON VIEWS----------------------
3120        nbtime=0;
3121        for iview=1:nbview
3122            %name of the current file
3123            filename=name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),Series.FileExt{iview},Series.NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile),SubDir{iview});
3124            if ~exist(filename,'file')
3125                msgbox_uvmat('ERROR',['missing input file' filename])
3126                break
3127            end
3128
3129            %reading the current file
3130            if testima
3131                if test_movie(iview)
3132                    Field{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
3133                else
3134                    Field{iview}.A=read_image(filename,Series.NomType{iview},num_i1{iview}(ifile));
3135                end % TODO: introduce ListVarName
3136                npxy=size(Field{iview}.A);
3137                Field{iview}.AX=[0.5 npxy(2)-0.5]; % coordinates of the first and last pixel centers
3138                Field{iview}.AY=[npxy(1)-0.5 0.5];
3139                Field{iview}.CoordType='px';
3140                Field{iview}.AName='image';
3141            else
3142                if testcivx
3143                    [Field{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
3144                else
3145                    [Field{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
3146                    Field{iview}.VarAttribute=SubField.VarAttribute;
3147                end
3148                if isfield(Field{iview},'Time')
3149                    timeread(iview)=Field{iview}.Time;
3150                    nbtime=nbtime+1;
3151                end
3152            end
3153            % coord transform
3154            % z index
3155            if ~isempty(NbSlice_calib)
3156                Field{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
3157            end
3158            if ~isequal(transform,'')
3159                Field{iview}=feval(Series.CoordType,Field{iview},XmlData{iview});%transform to phys if requested
3160            end
3161            if testcivx
3162                    Field{iview}=calc_field(FieldName,Field{iview});
3163            end
3164
3165            %projection on object (gridded plane)
3166            if isfield(Series,'ProjObject')
3167                Field{iview}=proj_field(Field{iview},Series.ProjObject);
3168            end
3169        end   
3170       
3171         %----------END LOOP ON VIEWS----------------------
3172         
3173        %merge the nbview fields
3174        MergeData=merge_field(Field);
3175        if isfield(MergeData,'Txt')
3176            msgbox_uvmat('ERROR',MergeData.Txt)
3177            return
3178        end
3179       
3180        % generating the name of the merged field
3181        mergename=name_generator(filebase_merge,num_i1{iview}(ifile),num_j1{iview}(ifile),Series.FileExt{iview},Series.NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile));
3182       
3183        % time:
3184        time_i=0;%default
3185        if isempty(time)% time from ImaDoc prevails
3186            time_i=sum(timeread)/nbtime;
3187        else
3188            time_i=(time(iview,num_i1{iview}(ifile),num_j1{iview}(ifile))+time(iview,num_i2{iview}(ifile),num_j2{iview}(ifile)))/2;
3189        end
3190       
3191        % recording the merged field
3192        if testima    %in case of input images an image is produced   
3193            if isa(MergeData.A,'uint8')
3194                bitdepth=8;
3195            elseif isa(MergeData.A,'uint16')
3196                bitdepth=16;
3197            end
3198            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
3199            %write xml calibration file
3200            siz=size(MergeData.A);
3201            npy=siz(1);
3202            npx=siz(2);
3203            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
3204                Rangx=MergeData.VarAttribute{1}.Coord_2;
3205                Rangy=MergeData.VarAttribute{1}.Coord_1;
3206            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
3207                Rangx=[MergeData.AX(1) MergeData.AX(end)];
3208                Rangy=[MergeData.AY(1) MergeData.AY(end)];
3209            else
3210                Rangx=[0.5 npx-0.5];
3211                Rangy=[npy-0.5 0.5];%default
3212            end
3213            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
3214            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
3215            T_x=-pxcmx*Rangx(1)+0.5;
3216            T_y=-pxcmy*Rangy(2)+0.5;
3217            GeometryCal.focal=1;
3218            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
3219            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
3220            ImaDoc.GeometryCalib=GeometryCal;
3221            t=struct2xml(ImaDoc);
3222            t=set(t,1,'name','ImaDoc');
3223            save(t,[filebase_merge '.xml'])     
3224            display([filebase_merge '.xml saved'])
3225        else
3226            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
3227            MergeData.nb_coord=2;
3228            MergeData.nb_dim=2;
3229            MergeData.dt=1;
3230            MergeData.Time=time_i;
3231            error=struct2nc(mergename,MergeData); %save result file
3232            if isempty(error)
3233                display(['output file ' mergename ' written'])
3234            else
3235                display(error)
3236            end
3237        end
3238    end
3239end
3240
3241%--------------------------------------------------------------------------   
3242function MergeData=merge_field(Data)
3243% initiate Matlab  structure for physical field
3244if isempty(Data)||~iscell(Data)
3245    MergeData=[];
3246    return
3247end
3248MergeData=Data{1};%default
3249error=0;
3250nbview=length(Data);
3251if nbview==1
3252    return
3253end
3254for iview=1:nbview
3255    if ~isequal(MergeData.ListDimName,Data{iview}.ListDimName)
3256        error=1;
3257    end
3258    if ~isequal(MergeData.ListVarName,Data{iview}.ListVarName)
3259        error=1;
3260    end
3261%      if ~isequal(MergeData.VarDimIndex,Data{iview}.VarDimIndex)
3262%         error=1;
3263%      end
3264end
3265if error
3266    MergeData.Txt='ERROR: attempt at merging fields of incompatible type';
3267    return
3268end
3269%group the variables (fields of 'FieldData') in cells of variables with the same dimensions
3270%-----------------------------------------------------------------
3271[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
3272%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
3273% CellVarIndex=cells of variable index arrays
3274ivar_new=0; % index of the current variable in the projected field
3275icoord=0;
3276for icell=1:length(CellVarIndex)
3277    if NbDim(icell)==1
3278        continue
3279    end
3280    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
3281    VarType=VarTypeCell{icell};
3282    ivar_X=VarType.coord_x;
3283    ivar_Y=VarType.coord_y;
3284    ivar_FF=VarType.errorflag;
3285    if isempty(ivar_X)
3286        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
3287    else
3288        if length(ivar_Y)~=1
3289                warndlg_uvmat('y coordinate missing in proj_field.m','ERROR')
3290                return
3291        end
3292        test_grid=0;
3293    end
3294%    DimIndices=Data{1}.VarDimIndex{VarIndex(1)};%indices of the dimensions of the first variable (common to all variables in the cell)
3295    %case of input fields with unstructured coordinates
3296    if ~test_grid
3297        for ivar=VarIndex
3298            VarName=MergeData.ListVarName{ivar};
3299            for iview=1:nbview
3300                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName ';'])
3301            end
3302        end
3303    %case of fields defined on a structured  grid
3304    else 
3305%        DimValue=MergeData.DimValue(DimIndices);%set of dimension values
3306        testFF=0;
3307        for iview=2:nbview
3308%             if ~isequal(DimValue,Data{iview}.DimValue(DimIndices))
3309%                 MergeData.Txt='ERROR: attempt at merging structured fields with different sizes';
3310%                 return
3311%             end
3312            for ivar=VarIndex
3313                VarName=MergeData.ListVarName{ivar};
3314                if isfield(MergeData,'VarAttribute')
3315                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
3316                        testFF=1;
3317                    end
3318                end
3319                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
3320            end
3321        end
3322        if testFF
3323            nbaver=nbview-MergeData.FF;
3324            indgood=find(nbaver>0);
3325            for ivar=VarIndex
3326                VarName=MergeData.ListVarName{ivar};
3327                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
3328            end
3329        else
3330            for ivar=VarIndex
3331                VarName=MergeData.ListVarName{ivar};
3332                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
3333            end   
3334        end
3335    end
3336end
3337   
3338   
3339%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3340 %detect the chosen series of files and check their date of modification:
3341%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3342%INPUT:
3343%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3344%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3345%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
3346%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
3347%OTHER INPUTS given by the structure Series
3348function GUI_input=clean_civ_cmx(num_i1,num_i2,num_j1,num_j2,Series) %(filecell,filecell_1,num_i,num_j,vel_type,field,param);
3349
3350%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
3351if ~exist('num_i1','var')
3352    GUI_input={'RootPath';'many';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
3353        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
3354        %'RootFile';'on';... %root input file name ('on' by default)
3355        %'FileExt';'on';... %input file extension ('on' by default)
3356        %'NomType';'on';...%type of file indexing ('on' by default)
3357        %'NbSlice';'on'; ...%nbre of slices ('off' by default)
3358        %'VelTypeMenu';'one';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
3359        %'FieldMenu';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
3360        %'CoordType';'on'...%can use a transform function 'off' by default
3361        %'GetObject';'on'...%can use projection object ,'off' by default
3362        %'GetMask';'on'...%can use mask option   ,'off' by default
3363        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
3364               ''};
3365    return %exit the function
3366end
3367%---------------------------------------------------------
3368hseries=guidata(Series.hseries);%handles of the GUI series
3369WaitbarPos=get(hseries.waitbar_frame,'Position');
3370
3371%%%%%%%%%%%%%%%%%%%%%%%%
3372message='this function will delete all files with extensions .log, .bat, .cmx,.cmx2,.errors in the input directory(ies)';
3373answer=msgbox_uvmat('INPUT_Y-N',message);
3374if ~isequal(answer,'Yes')
3375    return
3376end
3377nbdelete=0;
3378testcell=iscell(Series.RootFile);
3379if ~testcell
3380    Series.RootPath={Series.RootPath};
3381    Series.RootFile={Series.RootFile};
3382    Series.SubDir={Series.SubDir};
3383    Series.FileExt={Series.FileExt};
3384    Series.NomType={Series.NomType};
3385end
3386for iview=1:length(Series.RootFile)
3387    hdir=dir(fullfile(Series.RootPath{iview},Series.SubDir{iview}));%list files
3388    for ilist=1:length(hdir)
3389        update_waitbar(hseries.waitbar,WaitbarPos,ilist/length(hdir))
3390        FileName=hdir(ilist).name;
3391        [dd,ff,Ext]=fileparts(FileName);
3392        if isequal(Ext,'.log')||isequal(Ext,'.bat')||isequal(Ext,'.cmx')||isequal(Ext,'.cmx2')|| isequal(Ext,'.errors')
3393            delete(fullfile(Series.RootPath{iview},Series.SubDir{iview},FileName))
3394            nbdelete=nbdelete+1;
3395        end
3396    end
3397end
3398msgbox_uvmat('CONFIRMATION',['END: ' num2str(nbdelete) ' files deleted by clean_civ_cmx'])
3399
3400
3401
3402
3403
3404%-----------------------------
3405function mouse_up_gui(ggg,eventdata,handles)
3406if isequal(get(ggg,'SelectionType'),'alt')
3407    display('global CurData, UserData of GUI series')
3408    global CurData
3409    CurData=get(ggg,'UserData');
3410    evalin('base','global CurData');%make CurData global in the workspace
3411    evalin('base','CurData'); %display CurData in the workspace
3412    commandwindow
3413   % plot_text(CurData)
3414end
3415
3416
3417
3418% %----------------------------------------------------------------------
3419% % --- display image movie and display time average
3420% %OBSOLETE: A SUPPRIMER
3421% %----------------------------------------------------------------------
3422% function movie_ima(handles,filecell,filecell_1,num1,num_a,field)
3423%
3424% global hfig1 hfig2 hfig3 poscolbar
3425% global A val HIST
3426%
3427% A=[];aviobj=[];
3428% % set(hfig1,'UserData','ima')% set the current field state to 'image'
3429% set(handles.zoom,'Value',1); %put zoom on
3430% nom_type=get(handles.file_input,'UserData');
3431% % field=get(handles.civ1,'UserData');
3432% % fields=field(1).fields;
3433% set(handles.speed,'Visible','On')%show slider to set movie speed
3434% set(handles.mo_speed_txt,'Visible','On')
3435%
3436% if ~isempty(filecell_1)
3437%    file1=get(handles.file1_input,'UserData');
3438%    field1=file1.field;
3439%    scal_type1=field1.fields;
3440%    vel_type1=field1.vel_type;
3441%    filename_1=filecell_1(1);% first file name in the series
3442% else
3443%    filename_1=[];
3444% end
3445% scal_type{1}=field(1).fields;
3446% vel_type{1}=field(1).vel_type;
3447% % display the first field
3448% [A,time,dt,rangx0,rangy0]=view_ima(handles,cell2mat(filecell(1)),filename_1,num1(1),num_a(1));
3449%
3450% % calculate the histogram of the first image
3451% nxy=size(A);
3452% ndim=length(nxy);
3453% if ndim==2 % case of B/W images
3454%     nxy(3)=1;
3455% end
3456% C=reshape(A,nxy(1)*nxy(2),nxy(3));
3457% Amaxmax=double(max(max(max(A))));
3458% Aminmin=double(min(min(min(A))));
3459% if isa(C,'uint8')|isa(C,'uint16')
3460%     C=double(C);
3461%     dC=1;
3462% else
3463%     dC=(Amaxmax-Aminmin)/100;
3464% end
3465% val=[Aminmin:dC:Amaxmax];% define bins for histogram
3466% HIST=hist(C,val);% initiate the global histogram
3467% if ndim==2, HIST=HIST'; end;
3468%
3469% auto_scale=get(handles.auto_scale,'Value');
3470% min_input=str2num(get(handles.min_input,'String'));% select the minimum
3471% max_input=str2num(get(handles.scale_input,'String'));% select the max
3472% zoomstate=get(handles.zoom,'Value');
3473%
3474% if isequal(get(handles.window_input,'String'),'avi'),
3475%     basename=get(handles.file_input,'String');
3476%     prompt = {'file name';'frames per second';'frame resolution ([nbpixels x y])';'axis position relative to the frame'};
3477%     dlg_title = 'select properties of the output avi movie';
3478%     num_lines= 1;
3479%     def     = {[basename '_out.avi'];'5';'[1024 768]';'[0.05 0.07 0.87 0.88]'};
3480%     answer = inputdlg(prompt,dlg_title,num_lines,def);
3481%     aviname=answer{1};
3482%     fps=str2num(answer{2});
3483%     if exist(aviname,'file')==2
3484%         delete(aviname);
3485%     end;
3486%     aviobj=avifile(aviname,'Compression','None','fps',fps);
3487%     
3488%     %display first view for tests
3489%     figure(2);
3490%     hh=get(gcf,'CurrentAxes');
3491%     if isempty(hh),
3492%         hfig1=axes;
3493%     else
3494%         hfig1=hh;
3495%     end;
3496%     if isequal(filecell_1,{})
3497%         filename_1=[];
3498%     else
3499%         filename_1=cell2mat(filecell_1(1));
3500%     end
3501%     poscolbar=[0.93 0.15 0.02 0.7];
3502%     view_ima(handles,cell2mat(filecell(1)),filename_1,num1(1),num_a(1));% show the first field
3503%     nbpix=eval(answer{3});
3504%     set(gcf,'Position',[1 1 nbpix])% resolution XVGA
3505%     set(hfig1,'Position',eval(answer{4}));
3506%     
3507%     msgbox({'adjust figure 2 with its matlab edit menu ' ;...
3508%             'then type any keyboard key to get the avi movie as a copy of figure 2 display'})
3509%     pause;
3510%     hh=colorbar;
3511%     poscolbar=get(hh,'Position');
3512% end
3513%
3514% %%%%%%%%%%%%%%%%
3515% %mask and usrdfct
3516% maskname=[]; %default
3517% if isequal(get(handles.mask_test,'Value'),1)
3518%     maskbase=get(handles.mask_test,'UserData');
3519% end
3520% % image or scalar processing programme set by user
3521% % if (get(handles.usr_fct,'Value')==1)
3522% %      usrfct=get(handles.usr_fct,'UserData');
3523% % else
3524% %      usrfct='';
3525% % end
3526% nburst=1; % nburst(1) =nbre of names in filename= nbre of bursts
3527% set(handles.text_display_1,'String',['image movie'])
3528% nbfield=length(filecell);
3529% if nbfield >1
3530% for ifile=2:nbfield
3531%     stopstate=get(handles.run0,'BusyAction');
3532%     if isequal(stopstate,'queue')% enable STOP command
3533%        pausetime=1.02-get(handles.speed,'Value');
3534%          pause(pausetime)
3535%          if isequal(get(handles.mask_test,'Value'),1)
3536%                 maskname=name_generator(maskbase,num1(ifile),1,'.png','png_series');
3537%             end
3538%             if isequal(AName{1},'image')
3539%                 A=read_image(cell2mat(filecell(ifile)),num1(ifile),maskname);% read the first image, num2 is the counter for avi files
3540%             else % read the first field from the netcdf file, imposing the pixel positions in the selected domain
3541%                  [A,time(ifile),dtr,rgx,rgy,vt_out,erread]=read_scalar(filecell{ifile},vel_type,scal_type,rangx0,rangy0,nxy,maskname);
3542%                 if erread==1;
3543%                     errordlg({['no spatial derivative in ' filecell{ifile}]; 'run patch first'}); return
3544%                 elseif erread==2;
3545%                     errordlg(['no field ' vel_type{1} ' in ' filecell{ifile}]); return
3546%                 elseif erread==3;
3547%                     errordlg(['scalar ' scal_type{1} ' not found in' filecell{ifile}]); return
3548%                 elseif erread==4;
3549%                     errordlg(['all points aligned in' filecell{ifile}]); return
3550%                 end
3551%             end
3552%           
3553%             % read the second image
3554%             if ~isempty(filecell_1)
3555%                 if isequal(scal_type{1},'image')
3556%                     A1=read_image(cell2mat(filecell_1(ifile)),num1(ifile),maskname);% read the second image, num2 is the counter for avi files
3557%                     Avalue_1=double(A1(indy,indx,:));
3558%                 else % read the second field from the netcdf file, imposing the pixel positions in the selected domain
3559%                     [Avalue_1,time1(ifile),dtr,rgx,rgy,vt_out,erread]=read_scalar(filecell_1{ifile},{vel_type1},{scal_type1},rangx0,rangy0,npxy,maskname,usrfct);
3560%                     if erread==1;
3561%                         errordlg({['no spatial derivative in ' filecell_1{ifile}]; 'run patch first'}); return
3562%                     elseif erread==2;
3563%                         errordlg(['no field ' vel_type1 ' in ' filecell_1{ifile}]); return
3564%                     elseif erread==3;
3565%                         errordlg(['scalar ' scal_type1 ' not found in' filecell_1{ifile}]); return
3566%                     elseif erread==4;
3567%                         errordlg(['all points aligned in' filecell_1{ifile}]); return
3568%                     end
3569%                 end
3570%                 time(ifile)=(time(ifile)+time1(ifile))/2;
3571%                 Avalue=Avalue-Avalue_1;
3572%             end
3573%         set(handles.abs_time,'String',time);
3574%         set(handles.field_counter,'String',num2str(num1(ifile)));
3575%         set(handles.a_input,'String',num2stra(num_a(ifile),nom_type));
3576%         C=reshape(A,nxy(1)*nxy(2),nxy(3));% reshape in a vector
3577%         [val,HIST]=hist_update(val,HIST,C,dC);
3578%         [h,Amin,Amax]=plot_image(hfig1,rangx0,rangy0,1,scal_type{1},auto_scale,min_input,max_input,poscolbar,A);
3579%         set(handles.min_input,'String',num2str(Amin));% select the minimum
3580%         set(handles.scale_input,'String',num2str(Amax));% select the minimum
3581%          if ~isequal(aviobj,[]),
3582% %              mov=getframe(hfig1);
3583%               mov=getframe(gcf);
3584%              aviobj=addframe(aviobj,mov);end
3585%          if (get(handles.zoom,'Value') == get(handles.zoom,'Max')),zoom on,end
3586%          set(handles.field_counter,'String',num2str(num1(ifile)))
3587% %     end
3588% end
3589% end
3590% end
3591% aviobj=close(aviobj);
3592%
3593% %plot global image histogram
3594%         HIST=HIST/(nbfield*nxy(1)*nxy(2));% normalized by the number of points
3595%         axes(hfig2) %in main window
3596%         if ndim==2
3597%             plot(val,HIST)
3598%         else
3599%             plot(val,HIST(:,1),'r',val,HIST(:,2),'g',val,HIST(:,3),'b')
3600%         end
3601%         residu=1-sum(HIST,1);
3602%         title(['histo, residu ' num2str(residu)])
3603%         grid on
3604%         axes(hfig3)
3605%         cla %clear the second histogram window
3606%         
3607
3608
3609%----------------------------------------------------------------------
3610% --- make a time series analysis
3611%----------------------------------------------------------------------
3612%INPUT:
3613%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3614%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3615%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
3616%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
3617%OTHER INPUTS given by the structure Series
3618function GUI_input=time_series(num_i1,num_i2,num_j1,num_j2,Series)
3619
3620%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
3621if ~exist('num_i1','var')
3622    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
3623        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
3624        'RootFile';'on';... %root input file name ('on' by default)
3625        'FileExt';'on';... %input file extension ('on' by default)
3626        'NomType';'on';...%type of file indexing ('on' by default)
3627        'NbSlice';'on'; ...%nbre of slices ('off' by default)
3628        'VelTypeMenu';'two';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
3629        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
3630        'CoordType';'on';...%can use a transform function 'off' by default
3631        'GetObject';'on';...%can use projection object ,'off' by default
3632        %'GetMask';'on'...%can use mask option   ,'off' by default
3633        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
3634               ''};
3635    return %exit the function
3636end
3637
3638%------------------------------------------------------
3639hseries=guidata(Series.hseries);%handles in the GUI series
3640WaitbarPos=get(hseries.waitbar_frame,'Position'); %position of the waitbar frame
3641
3642%projection object
3643test_object=get(hseries.GetObject,'Value');
3644if test_object%isfield(Series,'sethandles')
3645    Series.ProjObject=read_set_object(Series.sethandles);
3646    %answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
3647    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' Series.ProjObject.Style]);
3648    if ~isequal(answeryes,'Yes')
3649        return
3650    end
3651else
3652    msgbox_uvmat('ERROR','a projection object is needed');
3653    return
3654end
3655
3656% root names
3657if iscell(Series.RootPath)
3658    RootPath=Series.RootPath;
3659    RootFile=Series.RootFile;
3660    SubDir=Series.SubDir;
3661    FileExt=Series.FileExt;
3662    NomType=Series.NomType;
3663else
3664    RootPath={Series.RootPath};
3665    RootFile={Series.RootFile};
3666    SubDir={Series.SubDir};
3667    FileExt={Series.FileExt};
3668    NomType={Series.NomType};
3669    num_i1={num_i1};
3670    num_i2={num_i2};
3671    num_j1={num_j1};
3672    num_j2={num_j2};
3673end
3674ext=FileExt{1};
3675form=imformats(ext([2:end]));%test valid Matlab image formats
3676testima=0;
3677if ~isempty(form)||isequal(lower(ext),'.avi')
3678    testima=1;
3679end
3680nbview=length(RootPath);%number of series (1 or 2)
3681nbfield=size(num_i1{1},1)*size(num_i1{1},2); %number of fields in the time series
3682
3683%Number of input series: this function  accepts only a single input file series
3684nbview=length(RootPath);
3685if nbview==2
3686    %TODO: choose between difference and two series
3687elseif nbview>2  % TODO: make multiple series
3688%     RootPath=RootPath(1:2);
3689%     set(hseries.RootPath,'String',RootPath)
3690%     SubDir=SubDir(1:2);
3691%     set(hseries.SubDir,'String',SubDir)
3692%     RootFile=RootFile(1:2);
3693%     set(hseries.RootFile,'String',RootFile)
3694%     NomType=NomType(1:2);
3695%     %set(hseries.NomType,'String',NomType)
3696%     FileExt=FileExt(1:2);
3697%     set(hseries.FileExt,'String',FileExt)
3698%     nbview=2;
3699end
3700hhh=which('mmreader');
3701for iview=1:nbview
3702    test_movie(iview)=0;
3703    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
3704        if isequal(lower(FileExt{iview}),'.avi')
3705            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
3706            test_movie(iview)=1;
3707        end
3708    end
3709end
3710filebase{1}=fullfile(RootPath{1},RootFile{1});
3711
3712% number of slices
3713NbSlice=str2num(get(hseries.NbSlice,'String'));
3714if isempty(NbSlice)
3715    NbSlice=1;
3716end
3717NbSlice_name=num2str(NbSlice);
3718
3719% Field and velocity type (the same for the two views)
3720if isfield(Series,'Field')
3721    FieldName=Series.Field;%the same set of fields for all views
3722else
3723    FieldName={''};
3724end
3725if isequal(FieldName,{'get_field...'})
3726    hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
3727    if numel(hget_field)>1
3728        delete(hget_field(2:end)) % delete multiple occurerence of the GUI get_fioeld
3729    elseif isempty(hget_field)
3730       filename=name_generator(filebase{1},num_i1{1}(1),num_j1{1}(1),FileExt{1},NomType{1},1,num_i2{1}(1),num_j2{1}(1),SubDir{1});
3731       idetect(iview)=exist(filename,'file');
3732       hget_field=get_field(filename);
3733       return
3734    end
3735    %hhget_field=guidata(hget_field);%handles of GUI elements in get_field
3736    SubField=read_get_field(hget_field) %read the names of the variables to plot in the get_field GUI
3737    if isempty(SubField)
3738        delete(hget_field)
3739       filename=name_generator(filebase{1},num_i1{1}(1),num_j1{1}(1),FileExt{1},NomType{1},1,num_i2{1}(1),num_j2{1}(1),SubDir{1});
3740        hget_field=get_field(filename);
3741        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
3742    end
3743%     if isequal(get(hhget_field.menu_coord,'Visible'),'on')
3744%         list_transform=get(hhget_field.menu_coord,'String');
3745%         val_list=get(hhget_field.menu_coord,'Value');
3746%         transform=list_transform{val_list};
3747%     end
3748end
3749
3750%detect whether the two files are 'images' or 'netcdf'
3751testima=0;
3752testvol=0;
3753testcivx=0;
3754testnc=0;
3755FileExt=get(hseries.FileExt,'String');
3756for iview=1:nbview
3757     ext=FileExt{iview};
3758     form=imformats(ext([2:end]));
3759     if isequal(lower(ext),'.vol')
3760         testvol=testvol+1;
3761     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
3762         testima=testima+1;
3763     elseif isequal(ext,'.nc')
3764         testnc=testnc+1;
3765     end
3766end
3767if testvol
3768    msgbox_uvmat('ERROR','volume images not implemented yet')
3769    return
3770end
3771if testnc~=nbview && testima~=nbview && testvol~=nbview
3772    msgbox_uvmat('need a set of images or a set of netcdf files with the same fields as input','ERROR')
3773    return
3774end
3775if ~isequal(FieldName,{'get_field...'})
3776    testcivx=testnc;
3777end
3778
3779% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
3780filebasesub=fullfile(RootPath{1},RootFile{1});
3781if NbSlice==1
3782    filebase_out=[filebasesub '_time'];
3783else
3784    filebase_out=[filebasesub '_' NbSlice_name 'mtim'];
3785    increment=num_i1{1}(2)-num_i1{1}(1);
3786    if ~isequal(increment,1) % if an increment is set
3787        answeryes=msgbox_uvmat('INPUT_Y-N',['will take time series in ' num2str(NbSlice) 'slices with increment = ' num2str(increment) '!']);
3788    else   
3789        answeryes=msgbox_uvmat('INPUT_Y-N',{['will take time series in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_out ' ...']});
3790    end
3791    if ~isequal(answeryes,'Yes')
3792        return
3793    end
3794end
3795VelType_str=get(hseries.VelTypeMenu,'String');
3796VelType_val=get(hseries.VelTypeMenu,'Value');
3797VelType{1}=VelType_str{VelType_val};
3798if nbview==2
3799    VelType_str=get(hseries.VelTypeMenu_1,'String');
3800    VelType_val=get(hseries.VelTypeMenu_1,'Value');
3801    VelType{2}=VelType_str{VelType_val};
3802end
3803
3804%Calibration data and timing: read the ImaDoc files
3805mode=''; %default
3806timecell={};
3807XmlData={};
3808itime=0;
3809NbSlice_calib={};
3810for iview=1:nbview%Loop on views
3811    XmlData{iview}=[];%default
3812    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
3813    if exist([filebase{iview} '.xml'],'file')
3814        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
3815        if isfield(XmlData{iview},'Time')
3816            itime=itime+1;
3817            timecell{itime}=XmlData{iview}.Time;
3818        end
3819        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
3820            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
3821            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
3822                msgbox_uvmat('WARNING','inconsistent number of Z indices for the field series');
3823            end
3824        end
3825    elseif exist([filebase{iview} '.civ'],'file')
3826        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
3827        itime=itime+1;
3828        timecell{itime}=time;
3829        XmlData{iview}.Time=time;
3830        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
3831        GeometryCalib.Tx=0;
3832        GeometryCalib.Ty=0;
3833        GeometryCalib.Tz=1;
3834        GeometryCalib.dpx=1;
3835        GeometryCalib.dpy=1;
3836        GeometryCalib.sx=1;
3837        GeometryCalib.Cx=0;
3838        GeometryCalib.Cy=0;
3839        GeometryCalib.f=1;
3840        GeometryCalib.kappa1=0;
3841        GeometryCalib.CoordUnit='cm';
3842        XmlData{iview}.GeometryCalib=GeometryCalib;
3843        if error==1
3844            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
3845        end
3846    end
3847end
3848
3849%check coincidence in time
3850multitime=0;
3851if length(timecell)==0
3852    time=[];
3853elseif length(timecell)==1
3854    time=timecell{1};
3855elseif length(timecell)>1
3856    multitime=1;
3857    for icell=1:length(timecell)
3858        if ~isequal(size(timecell{icell}),size(timecell{1}))
3859            warndlg_uvmat('inconsistent time array dimensions in ImaDoc fields, the time for the first series is used','WARNING')
3860            time=timecell{1};
3861            multitime=0;
3862            break
3863        end
3864    end
3865end
3866if multitime
3867    for icell=1:length(timecell)
3868        time(icell,:,:)=timecell{icell};
3869    end
3870    diff_time=max(max(diff(time)));
3871    if diff_time>0
3872        warndlg_uvmat(['times of series differ by more than ' num2str(diff_time)],'WARNING')
3873    end   
3874end
3875if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
3876    time=[];
3877end
3878
3879% image or scalar processing programme set by user
3880Coord_menu=get(hseries.CoordType,'String');
3881menu_val=get(hseries.CoordType,'Value');
3882usrfct=Coord_menu{menu_val};
3883testfct=~isequal(usrfct,'');
3884
3885% to update:
3886VelType_str=get(hseries.VelTypeMenu,'String');
3887VelType_val=get(hseries.VelTypeMenu,'Value');
3888VelType{1}=VelType_str{VelType_val};
3889if nbview==2
3890    VelType_str=get(hseries.VelTypeMenu_1,'String');
3891    VelType_val=get(hseries.VelTypeMenu_1,'Value');
3892    VelType{2}=VelType_str{VelType_val};
3893end
3894
3895%LOOP ON SLICES
3896for i_slice=1:NbSlice
3897     dt=[];
3898     nbmissing=0; %number of undetected files
3899     nbfiles=0;
3900    %%%%%%%%%%%%%%%%%%%%%%%%%%%%LOOP ON FIELDS IN  A SLICE
3901    for ifile=i_slice:NbSlice:nbfield 
3902        stopstate=get(hseries.RUN,'BusyAction');
3903        if isequal(stopstate,'queue')% enable STOP command
3904             update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
3905             for iview=1:nbview
3906                filename=...
3907                           name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),FileExt{iview},NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile),SubDir{iview});
3908                idetect(iview)=exist(filename,'file');
3909                Data{iview}=[]; %default     
3910                if testima                 
3911                    Data{iview}.ListVarName={'A'};
3912                    Data{iview}.AName='image';
3913                    if test_movie(iview)
3914                        A=read(MovieObject{iview},num_i1{iview}(ifile));
3915                    else
3916                        A=double(read_image(filename,NomType{iview},num_i1{iview}(ifile)));% read the image, num2 is the counter for avi files
3917                    end
3918                    Data{iview}.ListVarName={'coord_y','coord_x','A'}; %
3919                    npy=size(A,1);
3920                    npx=size(A,2);
3921                    nbcolor=size(A,3);
3922                    if nbcolor==3
3923                         Data{iview}.VarDimName={'coord_y','coord_x',{'coord_y','coord_x','rgb'}};
3924                    else
3925                         Data{iview}.VarDimName={'coord_y','coord_x',{'coord_y','coord_x'}};
3926                    end 
3927                    Data{iview}.coord_y=[npy-0.5 0.5];
3928                    Data{iview}.coord_x=[0.5 npx-0.5];
3929                    Data{iview}.A=A;
3930                    Data{iview}.CoordType='px';
3931                elseif testcivx
3932                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
3933                else
3934                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
3935                    Data{iview}.VarAttribute=SubField.VarAttribute;
3936                end
3937                if ~isempty(NbSlice_calib)  % z index
3938                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
3939                end
3940             end
3941            % geometry transform or other user defined transform
3942            if ~isequal(Series.CoordType,'')           
3943                if nbview==2
3944                    [Data{1},Data{2}]=feval(Series.CoordType,Data{1},XmlData{1},Data{2},XmlData{2});
3945                    if isempty(Data{2})
3946                        Data(2)=[];
3947                    end
3948                else
3949                    Data{1}=feval(Series.CoordType,Data{1},XmlData{1});
3950                end
3951            end
3952            if testcivx
3953                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
3954            end
3955            if length(Data)==2
3956                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
3957                if ~isempty(errormsg)
3958                    msgbox_uvmat('ERROR',['error in time_series/sub_field:' errormsg])
3959                    return
3960                end
3961            else
3962                Field=Data{1};
3963            end
3964            if isfield(Series,'ProjObject')
3965                Series.ProjObject
3966                [Field,errormsg]=proj_field(Field,Series.ProjObject);
3967                if ~isempty(errormsg)
3968                    msgbox_uvmat('ERROR',['error in time_series/proj_field:' errormsg])
3969                    return
3970                end
3971            end
3972            if min(idetect)>=1% the input file(s) have been detected         
3973                nbfiles=nbfiles+1;
3974                if nbfiles==1 %first field: initiate the time series
3975                    RecordData=Field;%default
3976                    RecordData.NbDim=Field.NbDim+1; %add the time dimension for plots         
3977                    nbvar=length(Field.ListVarName);
3978                    if nbvar==0
3979                        msgbox_uvmat('ERROR','no input variable selected in get_field')
3980                        return
3981                    end
3982                    testsum=2*ones(1,nbvar);%initiate flag for action on each variable
3983                    indexfalse=0;
3984                    CoordName={};
3985                    indexremove=[];
3986                    if isfield(Field,'VarAttribute') % look for coordinate and flag variables   
3987                        for ivar=1:nbvar
3988                            if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
3989                                var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
3990                                if isequal(var_role,'errorflag')
3991                                    msgbox_uvmat('ERROR','do not handle error flags in time series')
3992                                    return                                               
3993                                end
3994                                if isequal(var_role,'warnflag')                       
3995                                    testsum(ivar)=0;  % not recorded variable
3996                                    eval(['RecordData=rmfield(RecordData,''' Field.ListVarName{ivar} ''');']);%remove variable
3997                                end                 
3998                                if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|...
3999                                    isequal(var_role,'coord_z')|isequal(var_role,'coord')
4000                                    testsum(ivar)=1; %constant coordinates, record without time evolution
4001                                end
4002                                % check whether the variable ivar is a dimension variable
4003                                %index=Field.VarDimIndex{ivar};%dimension indices of the variable #ivar
4004                                DimCell=Field.VarDimName{ivar};
4005                                if ischar(DimCell)
4006                                    DimCell={DimCell};
4007                                end
4008                                if numel(DimCell)==1 && isequal(Field.ListVarName{ivar},DimCell{1})%detect dimension variables
4009                                   testsum(ivar)=1;
4010                                end
4011                            end
4012                        end
4013                    end
4014                    for ivar=1:nbvar
4015                        if testsum(ivar)==2                     
4016                            eval(['RecordData.' Field.ListVarName{ivar} '=[];'])
4017                        end
4018                    end
4019                    RecordData.ListVarName=[{'Time'} RecordData.ListVarName];
4020                end
4021                for ivar=1:length(Field.ListVarName)
4022                    VarName=Field.ListVarName{ivar};
4023                    eval(['VarVal=Field.' VarName ';']);
4024                    if testsum(ivar)==2% test for recorded variable
4025                        eval(['VarVal=Field.' VarName ';']);
4026                        if isequal(Series.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
4027                            if isempty(VarVal)
4028                                msgbox_uvmat('ERROR',['empty result at frame index ' num2str(num_i1{iview}(ifile))])
4029                                return                             
4030                            end
4031                            VarVal=mean(VarVal,1);
4032                        end
4033                        VarVal=shiftdim(VarVal,-1); %shift dimension
4034                        eval(['RecordData.' VarName '=cat(1,RecordData.' VarName ',VarVal);']);%concanete the current field to the time series   
4035                    elseif testsum(ivar)==1% variable representing fixed coordinates
4036                        eval(['VarInit=RecordData.' VarName ';']);
4037                        if ~isequal(VarVal,VarInit)
4038                            msgbox_uvmat('ERROR',['time series requires constant coordinates ' VarName])
4039                            return
4040                        end
4041                    end                 
4042                end
4043                % time:
4044                if isempty(time)% time read in ncfiles
4045                   if isfield(Field,'Time')
4046                       RecordData.Time(nbfiles,1)=Field.Time;
4047                   else
4048                       RecordData.Time(nbfiles,1)=nbfiles;%default
4049                   end
4050                else % time from ImaDoc prevails
4051                    RecordData.Time(nbfiles,1)=(time(1,num_i1{1}(ifile),num_j1{1}(ifile))+time(end,num_i2{end}(ifile),num_j2{end}(ifile)))/2;
4052                end
4053            else
4054                nbmissing=nbmissing+1;
4055            end
4056        end
4057    end
4058    %remove time for global attributes if exists
4059    for iattr=1:numel(RecordData.ListGlobalAttribute)
4060        if strcmp(RecordData.ListGlobalAttribute{iattr},'Time')
4061            RecordData.ListGlobalAttribute(iattr)=[];
4062            break
4063        end
4064    end
4065    for ivar=1:numel(RecordData.ListVarName)
4066        VarName=RecordData.ListVarName{ivar};
4067        eval(['RecordData.' VarName '=squeeze(RecordData.' VarName ');']) %remove singletons
4068    end
4069        % add time dimension and update VarDimIndex:
4070   %if ~isequal(Series.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
4071        for ivar=1:length(Field.ListVarName)
4072%              vardimindex=Field.VarDimIndex{ivar};% array of dimension indices for variable VarIndex(ivar)
4073             DimCell=Field.VarDimName(ivar);
4074             if testsum(ivar)==2%variable used as time series
4075%                  RecordData.VarDimIndex{ivar}=[1 vardimindex+1];
4076                  RecordData.VarDimName{ivar}=[{'Time'} DimCell];
4077             elseif testsum(ivar)==1
4078%                  RecordData.VarDimIndex{ivar}=[vardimindex+1];
4079                 RecordData.VarDimName{ivar}=DimCell;
4080             end
4081        end
4082   % end
4083    indexremove=find(~testsum);
4084    if ~isempty(indexremove)
4085        RecordData.ListVarName(1+indexremove)=[];
4086        RecordData.VarDimName(indexremove)=[];
4087        if isfield(RecordData,'Role')&~isempty(RecordData.Role{1})%generaliser aus autres attributs
4088            RecordData.Role(1+indexremove)=[];
4089        end
4090    end
4091    %RecordData.VarDimIndex=[{[1]} RecordData.VarDimIndex]; %time dimension
4092    %shift variable attributes
4093    if isfield(RecordData,'VarAttribute')
4094        RecordData.VarAttribute=[{[]} RecordData.VarAttribute];
4095    end
4096    RecordData.VarDimName=[{'Time'} RecordData.VarDimName];
4097    RecordData.Action=Series.Action;%name of the processing programme
4098    %name of result file
4099    [filemean]=...
4100               name_generator(filebase_out,num_i1{1}(i_slice),num_j1{1}(i_slice),'.nc','_i1-i2_j1-j2',1,num_i2{end}(ifile),num_j2{end}(ifile),SubDir{1});
4101    errormsg=struct2nc(filemean,RecordData); %save result file
4102    if isempty(errormsg)
4103        display([filemean ' written'])
4104    else
4105        msgbox_uvmat('ERROR',['error in Series/struct2nc' errormsg])
4106    end
4107end
4108figure
4109haxes=axes;
4110
4111plot_field(RecordData,haxes)
4112hget_field=findobj(allchild(0),'name','get_field');
4113if ~isempty(hget_field)
4114    delete(hget_field)
4115end
4116get_field(filemean,RecordData)
4117   
4118%-----------------------------------------------------------------------
4119% --- Executes on selection change in CoordType.
4120function CoordType_Callback(hObject, eventdata, handles)
4121menu_str=get(handles.CoordType,'String');
4122ind_coord=get(handles.CoordType,'Value');
4123coord_option=menu_str{ind_coord};
4124if isequal(coord_option,'more...');
4125    fct_name='';
4126    if exist('./TMP/current_usr_fct.mat','file')% if a file is found
4127        h=load('./TMP/current_usr_fct.mat');
4128        if isfield(h,'fct_name');
4129            fct_name=h.fct_name;
4130        end
4131    end
4132    prompt = {'Enter the name of the transform function'};
4133    dlg_title = 'user defined transform';
4134    num_lines= 1;
4135    [FileName, PathName, filterindex] = uigetfile( ...
4136       {'*.m', ' (*.m)';
4137        '*.m',  '.m files '; ...
4138        '*.*', 'All Files (*.*)'}, ...
4139        'Pick a file', fct_name);
4140    fct_name=fullfile(PathName,FileName);
4141    addpath(PathName);%add the path to the selected fct
4142    [errormsg,date_str]=check_functions;%check whether new functions can oversed the uvmat package A UTILISER
4143    if ~exist(fct_name,'file')
4144           warndlg(['image procesing fct ' fct_name ' not found'])
4145    else
4146        transform=FileName(1:end-2);%
4147        update_menu(handles.CoordType,transform)%add the selected fct to the menu
4148  %      set(handles.mouse_coord,'String',menu([1:end-1])')%update the mouse coord menu
4149      %save ('./TMP/current_usr_fct.mat','fct_name');
4150    end   
4151end
4152ind_coord=get(handles.CoordType,'Value');   
4153
4154%---------------------------------------------------------------------
4155% --- Executes on selection change in ProjObject.
4156function ProjObject_Callback(hObject, eventdata, handles)
4157
4158list_object=get(handles.ProjObject,'String');
4159index=get(handles.ProjObject,'Value');
4160hseries=get(handles.ProjObject,'Parent');
4161SeriesData=get(hseries,'UserData');
4162Obj=SeriesData.ProjObject{index};
4163[SeriesData.hset_object,SeriesData.sethandles]=set_object(SeriesData.ProjObject{index});
4164set(hseries,'UserData',SeriesData);
4165
4166%-------------------------------------------------------------
4167%generates a series of file names with reference numbers between range1 and
4168%range2 with increment incr. The reference number num_ref is the image number at the middle of the
4169%image pair. The set of first numbers num1 of the image pairs is also
4170%given as output
4171%------------------------------------------------------
4172function [num_i1,num_i2,num_j1,num_j2,nbmissing]=netseries_generator(filebase,subdir,mode,first_i,incr_i,last_i,first_j,incr_j,last_j)
4173[Path,Name]=fileparts(filebase);
4174filebasesub=fullfile(Path,subdir,Name);
4175filecell={};%default
4176num_i1=[];
4177num_i2=[];
4178num_j1=[];
4179num_j2=[];
4180ind0_i=first_i:incr_i:last_i;
4181nbcolumn=length(ind0_i);
4182ind0_j=first_j:incr_j:last_j;
4183nbline=length(ind0_j);
4184if isequal(mode,'#_ab')
4185    dirpair=dir([filebasesub '*_*.nc']);
4186elseif isequal(mode,'bursts')|isequal(mode,'series(Dj)') 
4187    dirpair=dir([filebasesub '_*_*-*.nc']);
4188elseif isequal(mode,'series(Di)')
4189    dirpair=dir([filebasesub '_*-*_*.nc']);
4190else
4191    errordlg('option *|* not yet implemented')
4192    return
4193end
4194if isempty(dirpair)
4195        errordlg('no pair detected in the selected range')
4196        return
4197end
4198    %ind0_i=first_i:incr_i:last_i;
4199    %nbcolumn=length(ind0_i);
4200    %dirpair=dir([filebasesub '_*_*-*.nc']);
4201if isequal(mode,'bursts')|isequal(mode,'#_ab')
4202    icount=0;
4203    for ifile=1:length(dirpair)
4204        [RootPath,RootFile,str_1,str_2,str_a,str_b,ext,nom_type]=name2display(dirpair(ifile).name);
4205       
4206%         if isempty(str2num(str_1))
4207%             dirpair(ifile).name
4208%         end
4209        num1_r=str2num(str_1);
4210        if isequal(RootFile,Name) & ~isempty(num1_r)   
4211            num_i1(ifile)=num1_r;
4212            num_a(ifile)=stra2num(str_a);
4213            num_b(ifile)=stra2num(str_b);
4214%             icount=icount+1;
4215        end     
4216    end
4217    length(dirpair)
4218%     num_j=floor((num_a+num_b)/2); %list of reference indices of the detected files
4219    test_range= (num_i1 >=first_i)&(num_i1<= last_i);% =1 when both numbers are in the range
4220    ind_i=((num_i1-first_i)/incr_i)+1;%indices i in the list of prescribed file indices
4221    select=find(test_range &(floor(ind_i)==ind_i));%selected indices of num_i1 in the file directory
4222    ind_i=ind_i(select);%set of selected indices ind_i
4223    [ind_i,indsort]=sort(ind_i);%sorted list of ind_i
4224    select=select(indsort);
4225    num_i1=num_i1(select);
4226    num_a=num_a(select);
4227    num_b=num_b(select);
4228    dirpair=dirpair(select);
4229    [ind_remove]=find_pairs(dirpair,ind_i,nbcolumn);
4230    ind_i(ind_remove)=[];
4231    num_a(ind_remove)=[];
4232    num_b(ind_remove)=[];
4233    num_j1=zeros(1,nbcolumn);%default
4234    num_j2=num_j1;
4235    num_j1(ind_i)=num_a;
4236    num_j2(ind_i)=num_b;
4237    num_i1=first_i:incr_i:last_i;
4238    num_i2=num_i1;
4239    nbmissing=nbcolumn-length(ind_i);
4240
4241elseif isequal(mode,'series(Di)')
4242    %ind0_i=first_i:incr_i:last_i;
4243    %nbcolumn=length(ind0_i);
4244    %ind0_j=first_j:incr_j:last_j;
4245    %nbline=length(ind0_j);
4246    %dirpair=dir([filebasesub '_*-*_*.nc']);
4247    for ifile=1:length(dirpair)
4248        [RootPath,RootFile,str_1,str_2,str_a,str_b,ext,nom_type]=name2display(dirpair(ifile).name);
4249        num_i1_r(ifile)=str2num(str_1);
4250        num_i2_r(ifile)=str2num(str_2);
4251        num_j(ifile)=str2num(str_a);
4252    end
4253    num_i=floor((num_i1_r+num_i2_r)/2); %list of reference indices of the detected files
4254    test_range= (num_i >=first_i)&(num_i<= last_i)&(num_j >=first_j)&(num_j<= last_j);% =1 when both numbers are in the range
4255    ind_i=((num_i-first_i)/incr_i)+1;%indices i and j in the list of prescribed file indices
4256    ind_j=((num_j-first_j)/incr_j)+1;
4257    ind_ij=ind_j+nbline*(ind_i-1);%indices in the reshhaped series of prescribed file indices
4258    select=find(test_range &(floor(ind_i)==ind_i)&(floor(ind_j)==ind_j));%selected indices in the file directory
4259    ind_ij=ind_ij(select);%set of selected indices ind_ij
4260    [ind_ij,indsort]=sort(ind_ij);%sorted list of ind_ij
4261    select=select(indsort);
4262    num_i1_r=num_i1_r(select);
4263    num_i2_r=num_i2_r(select);
4264%     num_j=num_j(select);
4265    dirpair=dirpair(select);
4266    [ind_remove]=find_pairs(dirpair,ind_ij,nbcolumn*nbline) ;
4267    ind_ij(ind_remove)=[];
4268    num_i1_r(ind_remove)=[];
4269    num_i2_r(ind_remove)=[];
4270    num_i1=zeros(1,nbline*nbcolumn);%default
4271    num_i2=num_i1;
4272    num_i1(ind_ij)=num_i1_r;
4273    num_j2(ind_ij)=num_i2_r;
4274    num_i1=reshape(num_i1,nbline,nbcolumn);
4275    num_i2=reshape(num_i2,nbline,nbcolumn);
4276    num_j1=meshgrid(ind0_i,ind0_j);
4277    num_j2=num_j1;
4278    nbmissing=nbline*nbcolumn-length(ind_ij);
4279elseif isequal(mode,'series(Dj)')
4280 %   ind0_i=first_i:incr_i:last_i;
4281 %   nbcolumn=length(ind0_i);
4282 %   ind0_j=first_j:incr_j:last_j;
4283  %  nbline=length(ind0_j);
4284  %  dirpair=dir([filebasesub '_*_*-*.nc']);
4285    for ifile=1:length(dirpair)
4286        [RootPath,RootFile,str_1,str_2,str_a,str_b,ext,nom_type]=name2display(dirpair(ifile).name);
4287        num_i(ifile)=str2num(str_1);
4288        num_a(ifile)=str2num(str_a);
4289        num_b(ifile)=str2num(str_b);
4290    end
4291    num_j=floor((num_a+num_b)/2); %list of reference indices of the detected files
4292    test_range= (num_i >=first_i)&(num_i<= last_i)&(num_j >=first_j)&(num_j<= last_j);% =1 when both numbers are in the range
4293    ind_i=((num_i-first_i)/incr_i)+1;%indices i and j in the list of prescribed file indices
4294    ind_j=((num_j-first_j)/incr_j)+1;
4295    ind_ij=ind_j+nbline*(ind_i-1);%indices in the reshhaped series of prescribed file indices
4296    select=find(test_range &(floor(ind_i)==ind_i)&(floor(ind_j)==ind_j));%selected indices in the file directory
4297    ind_ij=ind_ij(select);%set of selected indices ind_ij
4298    [ind_ij,indsort]=sort(ind_ij);%sorted list of ind_ij
4299    select=select(indsort);
4300    num_i=num_i(select);
4301    num_a=num_a(select);
4302    num_b=num_b(select);
4303    dirpair=dirpair(select);
4304    [ind_remove]=find_pairs(dirpair,ind_ij,nbcolumn*nbline) ;
4305    ind_ij(ind_remove)=[];
4306    num_a(ind_remove)=[];
4307    num_b(ind_remove)=[];
4308    num_j1=zeros(1,nbline*nbcolumn);%default
4309    num_j2=num_j1;
4310    num_j1(ind_ij)=num_a;
4311    num_j2(ind_ij)=num_b;
4312    num_j1=reshape(num_j1,nbline,nbcolumn);
4313    num_j2=reshape(num_j2,nbline,nbcolumn);
4314    num_i1=meshgrid(ind0_i,ind0_j);
4315    num_i2=num_i1;
4316    nbmissing=nbline*nbcolumn-length(ind_ij);
4317%     for i=1:length(indsel);%A SUPPRIMER ULTERIEUREMENT
4318%         if indsel(i)==0
4319%             filecell{i}='';
4320%         else
4321%             Name=dirpair(indsel(i)).name;
4322%             filecell{i}=fullfile(Path,subdir,Name);
4323%         end
4324%     end
4325%else
4326%    errordlg('option *|* not yet implemented')
4327%    return
4328end
4329
4330%%%%%%%%%%%%%
4331function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
4332
4333        indsel=ind_i;
4334        indiff=diff(ind_i); %test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
4335        indiff=[1 indiff last_i-ind_i(end)+1];%for testing gaps with the imposed bounds
4336        if ~isempty(indiff)
4337            indiff2=diff(indiff);
4338            indiffp=[indiff2 1];
4339            indiffm=[1 indiff2];
4340            ind_multi_m=find((indiff==0)&(indiffm<0))-1;%indices of first members of multiplets
4341            ind_multi_p=find((indiff==0)&(indiffp>0));%indices of last members of multiplets
4342                %for each multiplet, select the most recent file
4343            ind_remove=[];
4344            for i=1:length(ind_multi_m)
4345                ind_pairs=ind_multi_m(i):ind_multi_p(i);
4346                for imulti=1:length(ind_pairs)
4347                    datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date);%dates of creation
4348                end
4349                [datenew,indsort2]=sort(datepair); %sort the multiplet by creation date
4350                ind_s=indsort2(1:end-1);%
4351                ind_remove=[ind_remove ind_pairs(ind_s)];%remove these indices, leave the last one
4352            end
4353        end
4354
4355%--------------------------------------------------------
4356
4357 
4358%-----------------------------------------------------------
4359% find the times corresponding to the first and last indices of a series
4360%
4361function displ_time(handles,times)
4362hseries=get(handles.last_i,'parent');
4363SeriesData=get(hseries,'UserData');%
4364first_i=str2num(get(handles.first_i,'String'));
4365first_j=str2num(get(handles.first_j,'String'));
4366last_i=str2num(get(handles.last_i,'String'));
4367last_j=str2num(get(handles.last_j,'String'));
4368% index_civ=get(handles.list_pair_civ,'Value');
4369% NomType=get(handles.NomType,'String');
4370NomType=SeriesData.NomType;
4371mode_list=get(handles.mode,'String');
4372index_mode=get(handles.mode,'Value');
4373mode=mode_list{index_mode};
4374% ind_shift=0;%default
4375
4376time_first=[];
4377time_last=[];
4378if ~isfield(SeriesData,'Time')
4379    SeriesData.Time{1}=[];
4380end
4381for iview=1:length(NomType)
4382    time_first_cell{iview}='?';
4383    time_last_cell{iview}='?';%default
4384    time=SeriesData.Time{iview};
4385    if isequal(NomType{iview},'_i1-i2_j')|isequal(NomType{iview},'_i_j1-j2')|isequal(NomType{iview},'#_ab')|isequal(NomType{iview},'_i1-i2')
4386        if isfield(SeriesData,'displ_num')& ~isempty(SeriesData.displ_num)
4387            ind_shift=SeriesData.displ_num(iview,:);
4388            if isequal(mode,'bursts')
4389                first_j=0;
4390                last_j=0;
4391            end
4392            first_i1=first_i +ind_shift(3);
4393            first_i2 =first_i +ind_shift(4);
4394            first_j1 =first_j +ind_shift(1);
4395            first_j2 =first_j +ind_shift(2);
4396            last_i1=last_i +ind_shift(3);
4397            last_i2 =last_i +ind_shift(4);   
4398            last_j1 =last_j +ind_shift(1);
4399            last_j2 =last_j +ind_shift(2);
4400            siz=size(SeriesData.Time{1});
4401            if siz(1)>=last_i2 & siz(2)>=last_j2
4402                time_first=(time(first_i1,first_j1)+time(first_i2,first_j2))/2;
4403                time_last=(time(last_i1,last_j1)+time(last_i2,last_j2))/2;
4404            else%read the time in the nc files
4405                RootPath=get(handles.RootPath,'String');
4406                RootFile=get(handles.RootFile,'String');
4407                SubDir=get(handles.SubDir,'String');
4408                %VelType=get(handles.VelType,'String');
4409                VelType_str=get(handles.VelTypeMenu,'String');
4410                VelType_val=get(handles.VelTypeMenu,'Value');
4411                VelType=VelType_str{VelType_val};
4412                filebase=fullfile(RootPath{1},RootFile{1});
4413                [filefirst]=name_generator(filebase,first_i1,first_j1,'.nc',NomType{iview},1,first_i2,first_j2,SubDir{iview});
4414                if  exist(filefirst,'file')
4415                    Attrib=nc2struct(filefirst,[]);
4416                    if isfield(Attrib,'Time')
4417                        time_first=Attrib.Time;
4418                    else
4419                        if isfield(Attrib,'absolut_time_T0')
4420                            time_first=Attrib.absolut_time_T0;
4421                        end
4422                        if isfield(Attrib,'absolut_time_T0_2')&&~(isequal(VelType,'civ1')||isequal(VelType,'interp1')||isequal(VelType,'filter1'))
4423                            time_first=Attrib.absolut_time_T0_2;
4424                        end
4425                    end
4426                end
4427                [filelast]=name_generator(filebase,last_i1,last_j1,'.nc',NomType{iview},1,last_i2,last_j2,SubDir{iview});
4428                if exist(filelast,'file')
4429                   Attrib=nc2struct(filelast,[]);
4430                    if isfield(Attrib,'Time')
4431                        time_last=Attrib.Time;
4432                    else
4433                        if isfield(Attrib,'absolut_time_T0')
4434                            time_last=Attrib.absolut_time_T0;
4435                        end
4436                        if isfield(Attrib,'absolut_time_T0_2')&&~(isequal(VelType,'civ1')||isequal(VelType,'interp1')||isequal(VelType,'filter1'))
4437                            time_last=Attrib.absolut_time_T0_2;
4438                        end
4439                    end
4440                end
4441            end
4442        end
4443    else
4444        siz=size(times);
4445        if siz(1)>=last_i & siz(2)>=last_j
4446            time_first=times(first_i,first_j);
4447            time_last=times(last_i,last_j);
4448        end
4449    end
4450    time_first_cell{iview}=num2str(time_first,4);
4451    time_last_cell{iview}=num2str(time_last,4);
4452end
4453set(handles.time_first,'Value',1)
4454set(handles.time_last,'Value',1)
4455set(handles.time_first,'String',time_first_cell);
4456set(handles.time_last,'String',time_last_cell);
4457
4458%--------------------------------------------------------------------
4459% --- Executes on selection change in VelTypeMenu.
4460function VelTypeMenu_Callback(hObject, eventdata, handles)
4461% VelTypeList=get(handles.VelTypeMenu,'String');
4462% VelTypeIndex=get(handles.VelTypeMenu,'Value');
4463% VelTypeCell=get(handles.VelType,'String');
4464% VelTypeCell{1}=VelTypeList{VelTypeIndex};
4465% set(handles.VelType,'String',VelTypeCell)
4466
4467
4468%--------------------------------------------------------------------
4469% --- Executes on button press in GetObject.
4470function GetObject_Callback(hObject, eventdata, handles)
4471hseries=get(handles.GetObject,'parent');
4472SeriesData=get(hseries,'UserData');
4473value=get(handles.GetObject,'Value');
4474if value
4475     set(handles.GetObject,'BackgroundColor',[1 1 0])%put unactivated buttons to yellow
4476     DataInit.ParentButton=handles.GetObject;
4477     hset_object=findobj(allchild(0),'Name','set_object');%find the set_object interface handle
4478     if ishandle(hset_object)
4479         [SeriesData.hset_object,SeriesData.sethandles]=set_object(DataInit); %open the set_object interface
4480     else
4481         DataInit.TITLE='POINTS';%default option
4482         [SeriesData.hset_object,SeriesData.sethandles]=set_object(DataInit); %open the set_object interface
4483     end
4484else
4485    set(handles.GetObject,'BackgroundColor',[0 1 0])%put activated buttons to green
4486    if isfield(SeriesData,'hset_object')&& ishandle(SeriesData.hset_object)
4487        close(SeriesData.hset_object)
4488    end
4489end
4490set(hseries,'UserData',SeriesData)
4491
4492%--------------------------------------------------------------
4493function GetMask_Callback(hObject, eventdata, handles)
4494value=get(handles.GetMask,'Value');
4495if value
4496    errordlg('not implemented yet')
4497end
4498%--------------------------------------------------------------
4499
4500%--------------------------------------------------------------------------
4501%'uv_ncbrowser': interactively calls the netcdf file browser 'get_field.m'
4502function ncbrowser_uvmat(hObject, eventdata)
4503     bla=get(gcbo,'String');
4504     ind=get(gcbo,'Value');
4505     filename=cell2mat(bla(ind));
4506      blank=find(filename==' ');
4507      filename=filename(1:blank-1);
4508     get_field(filename)
4509
4510
4511
4512% --------------------------------------------------------------------
4513function MenuHelp_Callback(hObject, eventdata, handles)
4514
4515path_to_uvmat=which ('uvmat');% check the path of uvmat
4516pathelp=fileparts(path_to_uvmat);
4517helpfile=fullfile(pathelp,'UVMAT_DOC','uvmat_doc.html');
4518if isempty(dir(helpfile)), errordlg('Please put the help file uvmat_doc.html in the  directory UVMAT/UVMAT_DOC')
4519else
4520web([helpfile '#series'])   
4521end
4522
4523
4524
4525
4526
4527
Note: See TracBrowser for help on using the repository browser.