source: trunk/src/series.m @ 2

Last change on this file since 2 was 2, checked in by gostiaux, 11 years ago
  • Initial import
  • Add .m files in src
  • Add .fig files in src
  • Add .xml config files
File size: 183.6 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                            lastfield='civ1'; %default
2002                            if ~isempty(Data.patch2) && isequal(Data.patch2,1)
2003                                lastfield='patch2';
2004                            elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
2005                                lastfield='fix2';
2006                            elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
2007                                lastfield='civ2';
2008                            elseif ~isempty(Data.patch) && isequal(Data.patch,1);
2009                                lastfield='patch1';
2010                            elseif ~isempty(Data.fix) && isequal(Data.fix,1);
2011                                lastfield='fix1';
2012                            elseif ~isempty(Data.absolut_time_T0) && ~isempty(Data.hart)
2013                                lastfield='civ1';
2014                            end   
2015%                             Data=nc2struct(file,[]);       
2016%                              lastfield='civ1'; %default
2017%                             if isfield(Data,'patch2') & isequal(Data.patch2,1);
2018%                                 lastfield='patch2';
2019%                             elseif isfield(Data,'fix2') & isequal(Data.fix2,1);
2020%                                 lastfield='fix2';
2021%                             elseif isfield(Data,'civ2') & isequal(Data.civ2,1);
2022%                                 lastfield='civ2';
2023%                             elseif isfield(Data,'patch') & isequal(Data.patch,1);
2024%                                 lastfield='patch1';
2025%                             elseif isfield(Data,'fix') & isequal(Data.fix,1);
2026%                                 lastfield='fix1';
2027%                             elseif isfield(Data,'absolut_time_T0') & isfield(Data,'hart')
2028%                                 lastfield='civ1';
2029%                             end   
2030                         
2031                        end
2032                    end
2033                    Tabchar(1,i_slice)={['slice #' num2str(i_slice)]};
2034                    Tabchar(index+1,i_slice)={[file '   ' lastfield]};
2035                end
2036            end
2037        end
2038        if isempty(datnum)
2039            if NbSlice>1
2040                message=['no set of ' num2str(NbSlice) ' (NbSlices) files found'];
2041            else
2042                 message='no file found';
2043            end
2044        else
2045            datnum=datnum(find(datnum));%keep the non zero values corresponding to existing files
2046            [first,ind]=min(datnum);
2047            [last,indlast]=max(datnum);
2048            message={['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
2049                ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
2050        end
2051        if ~isempty(Tabchar)
2052          Tabchar=reshape(Tabchar,NbSlice*(nbfield*nbfield2+1),1);
2053        end
2054    end
2055    hfig=figure(iview);
2056    clf
2057    if iview>1
2058        pos=get(iview-1,'Position');
2059        pos(1)=pos(1)+(iview-1)*pos(1)/nbview;
2060        set(hfig,'Position',pos)
2061    end
2062    set(hfig,'name',['view= ' num2str(iview)])
2063   
2064    h=uicontrol('Style','listbox', 'Position', [20 20 500 300], 'String', Tabchar, 'Callback', @ncbrowser_uvmat);
2065    hh=uicontrol('Style','listbox', 'Position', [20 340 500 40], 'String', message);
2066end
2067%----------------------------------------------------
2068%  determine the list of index pairs of processing file
2069%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2070function [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)
2071num_i1=num_i;% set of first image numbers by default
2072num_i2=num_i;
2073num_j1=num_j;
2074num_j2=num_j;
2075num_i_out=num_i;
2076num_j_out=num_j;
2077if isequal (NomType,'_i1-i2_j') |isequal (NomType,'_i1-i2')
2078    num_i1_line=num_i+ind_shift(3);% set of first image numbers
2079    num_i2_line=num_i+ind_shift(4);
2080    % adjust the first and last field number
2081        indsel=find(num_i1_line >= 1);
2082    num_i_out=num_i(indsel);
2083    num_i1_line=num_i1_line(indsel);
2084    num_i2_line=num_i2_line(indsel);
2085    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2086    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2087    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2088    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2089elseif isequal (NomType,'_i_j1-j2') || isequal (NomType,'#_ab')
2090    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2091        num_j1=ind_shift(1)*ones(size(num_i));
2092        num_j2=ind_shift(2)*ones(size(num_i));
2093    else
2094        num_j1_col=num_j+ind_shift(1);% set of first image numbers
2095        num_j2_col=num_j+ind_shift(2);
2096        % adjust the first field number
2097        indsel=find((num_j1_col >= 1));   
2098        num_j_out=num_j(indsel);
2099        num_j1_col=num_j1_col(indsel);
2100        num_j2_col=num_j2_col(indsel);
2101        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
2102        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
2103    end   
2104end
2105
2106
2107%----------------------------------------------------------------------
2108% --- make average on a series of files
2109%----------------------------------------------------------------------
2110%INPUT:
2111%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2112%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2113%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
2114%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
2115%OTHER INPUTS given by the structure Series
2116%  Series.Time:
2117%  Series.GeometryCalib:
2118function GUI_input=aver_stat(num_i1,num_i2,num_j1,num_j2,Series)
2119%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
2120if ~exist('num_i1','var')
2121    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
2122        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
2123        'RootFile';'on';... %root input file name ('on' by default)
2124        'FileExt';'on';... %input file extension ('on' by default)
2125        'NomType';'on';...%type of file indexing ('on' by default)
2126        'NbSlice';'on'; ...%nbre of slices ('off' by default)
2127        'VelTypeMenu';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
2128        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
2129        'CoordType'; 'on';...%can use a transform function
2130        'GetObject';'on';...%can use projection object(option 'off'/'one'/'two',
2131        %'GetMask';'on'...%can use mask option   
2132        %'PARAMETER'; %options: name of the user defined parameter',repeat a line for each parameter
2133               ''};
2134        return
2135end
2136
2137%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2138hseries=guidata(Series.hseries);%handles of the GUI series
2139WaitbarPos=get(hseries.waitbar_frame,'Position');
2140%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2141
2142%root input file and type
2143if ~iscell(Series.RootPath)% case of a single input field series
2144    num_i1={num_i1};num_j1={num_j1};num_i2={num_i2};num_j2={num_j2};
2145    RootPath={Series.RootPath};
2146    RootFile={Series.RootFile};
2147    SubDir={Series.SubDir};
2148    FileExt={Series.FileExt};
2149    NomType={Series.NomType};
2150else
2151    RootPath=Series.RootPath;
2152    RootFile=Series.RootFile;
2153    SubDir=Series.SubDir;
2154    NomType=Series.NomType;
2155    FileExt=Series.FileExt;
2156end   
2157ext=FileExt{1};
2158form=imformats(ext([2:end]));%test valid Matlab image formats
2159testima=0;
2160if ~isempty(form)||isequal(lower(ext),'.avi')||isequal(lower(ext),'.vol')
2161    testima(1)=1;
2162end
2163if length(FileExt)>=2
2164    ext_1=FileExt{2};
2165    form=imformats(ext_1([2:end]));%test valid Matlab image formats
2166    if ~isempty(form)||isequal(lower(ext_1),'.avi')||isequal(lower(ext_1),'.vol')
2167        testima(2)=1;
2168    end
2169    if testima(2)~=testima(1)
2170        msgbox_uvmat('ERROR','images and netcdf files cannot be compared')
2171        return
2172    end
2173end
2174
2175%Number of input series: this function  accepts two input file series at most (then it operates on the difference of fields)
2176nbview=length(RootPath);
2177if nbview>2 
2178    RootPath=RootPath(1:2);
2179    set(hseries.RootPath,'String',RootPath)
2180    SubDir=SubDir(1:2);
2181    set(hseries.SubDir,'String',SubDir)
2182    RootFile=RootFile(1:2);
2183    set(hseries.RootFile,'String',RootFile)
2184    NomType=NomType(1:2);
2185    FileExt=FileExt(1:2);
2186    set(hseries.FileExt,'String',FileExt)
2187    nbview=2;
2188end
2189hhh=which('mmreader');
2190for iview=1:nbview
2191    test_movie(iview)=0;
2192    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
2193        if isequal(lower(FileExt{iview}),'.avi')
2194            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
2195            test_movie(iview)=1;
2196        end
2197    end
2198end
2199
2200% number of slices
2201NbSlice=str2num(get(hseries.NbSlice,'String'));
2202if isempty(NbSlice)
2203    NbSlice=1;
2204end
2205NbSlice_name=num2str(NbSlice);
2206
2207% Field and velocity type (the same for the two views)
2208Field_str=get(hseries.FieldMenu,'String');
2209FieldName=[]; %default
2210testfield=get(hseries.FieldMenu,'Visible');
2211if isequal(testfield,'on')
2212    val=get(hseries.FieldMenu,'Value');
2213    FieldName=Field_str(val);%the same set of fields for all views
2214    if isequal(FieldName,{'get_field...'})
2215        hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
2216        if length(hget_field)>1
2217            delete(hget_field(2:end))
2218        elseif isempty(hget_field)
2219           filename=...
2220                 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});
2221           get_field(filename);
2222           return
2223        end
2224        hhget_field=guidata(hget_field);%handles of GUI elements in get_field
2225        SubField=read_var_names(hhget_field); %read the names of the variables to plot in the get_field GUI
2226    end
2227end
2228%detect whether the two files are 'images' or 'netcdf'
2229testima=0;
2230testvol=0;
2231testcivx=0;
2232testnc=0;
2233FileExt=get(hseries.FileExt,'String');
2234% test_movie=0;
2235for iview=1:nbview
2236     ext=FileExt{iview};
2237     form=imformats(ext([2:end]));
2238     if isequal(lower(ext),'.vol')
2239         testvol=testvol+1;
2240     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
2241         testima=testima+1;
2242     elseif isequal(ext,'.nc')
2243         testnc=testnc+1;
2244     end
2245end
2246if testvol
2247    msgbox_uvmat('ERROR','volume images not implemented yet')
2248    return
2249end
2250if testnc~=nbview && testima~=nbview && testvol~=nbview
2251    msgbox_uvmat('ERROR','compare two image series or two netcdf files with the same fields as input')
2252    return
2253end
2254if ~isequal(FieldName,{'get_field...'})
2255    testcivx=testnc;
2256end
2257
2258if testcivx
2259    VelType_str=get(hseries.VelTypeMenu,'String');
2260    VelType_val=get(hseries.VelTypeMenu,'Value');
2261    VelType{1}=VelType_str{VelType_val};
2262    if nbview==2
2263        VelType_str=get(hseries.VelTypeMenu_1,'String');
2264        VelType_val=get(hseries.VelTypeMenu_1,'Value');
2265        VelType{2}=VelType_str{VelType_val};
2266    end
2267end
2268
2269%Calibration data and timing: read the ImaDoc files
2270mode=''; %default
2271timecell={};
2272itime=0;
2273NbSlice_calib={};
2274for iview=1:nbview%Loop on views
2275    XmlData{iview}=[];%default
2276    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
2277    if exist([filebase{iview} '.xml'],'file')
2278        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
2279        if isfield(XmlData{iview},'Time')
2280            itime=itime+1;
2281            timecell{itime}=XmlData{iview}.Time;
2282        end
2283        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
2284            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
2285            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
2286                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
2287            end
2288        end
2289    elseif exist([filebase{iview} '.civ'],'file')
2290        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
2291        itime=itime+1;
2292        timecell{itime}=time;
2293        XmlData{iview}.Time=time;
2294        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
2295        GeometryCalib.Tx=0;
2296        GeometryCalib.Ty=0;
2297        GeometryCalib.Tz=1;
2298        GeometryCalib.dpx=1;
2299        GeometryCalib.dpy=1;
2300        GeometryCalib.sx=1;
2301        GeometryCalib.Cx=0;
2302        GeometryCalib.Cy=0;
2303        GeometryCalib.f=1;
2304        GeometryCalib.kappa1=0;
2305        GeometryCalib.CoordUnit='cm';
2306        XmlData{iview}.GeometryCalib=GeometryCalib;
2307        if error==1
2308            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
2309        end
2310    end
2311end
2312
2313%check coincidence in time
2314multitime=0;
2315if length(timecell)==0
2316    time=[];
2317elseif length(timecell)==1
2318    time=timecell{1};
2319elseif length(timecell)>1
2320    multitime=1;
2321    for icell=1:length(timecell)
2322        if ~isequal(size(timecell{icell}),size(timecell{1}))
2323            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
2324            time=timecell{1};
2325            multitime=0;
2326            break
2327        end
2328    end
2329end
2330if multitime
2331    for icell=1:length(timecell)
2332        time(icell,:,:)=timecell{icell};
2333    end
2334    diff_time=max(max(diff(time)));
2335    if diff_time>0
2336        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
2337    end   
2338end
2339if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
2340    time=[];
2341end
2342
2343% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
2344filebasesub=fullfile(RootPath{1},SubDir{1},RootFile{1});
2345if isempty(SubDir{1}) % create a subdirectory '/mean'
2346    subdir_result='mean';
2347%     filebasemean=fullfile(RootPath{1},subdir_result);
2348    if ~exist(fullfile(RootPath{1},subdir_result),'dir')
2349        dircur=pwd; %record current working directory
2350        cd(RootPath{1})% goes to the iamge directory
2351        [m1,m2,m3]=mkdir(subdir_result);
2352        if ~isequal(m2,'')
2353             msgbox_uvmat('CONFIRMATION',m2);%error message for directory creation
2354        end
2355        cd(dircur) %back to the initial working directory
2356    end
2357    filebase_out=filebase{1};
2358else
2359   subdir_result=SubDir{1};
2360   filebase_out=[filebase{1} '_mean'];% output root name obtained by adding the suffix _mean to the input
2361end
2362%output nomtype (to generalise)
2363NomTypeOut=nomtype2pair(NomType{1},num_i2{end}(end)-num_i1{1}(1),num_j2{end}(end)-num_j1{1}(1));
2364   
2365if NbSlice==1 
2366    filebase_out=[filebasesub '_mean'];
2367else
2368    filebase_out=[filebasesub '_' NbSlice_name 'mean'];
2369    answeryes=questdlg({['will make average in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_out ' ...']});
2370    if ~isequal(answeryes,'Yes')
2371        return
2372    end
2373end
2374
2375% coordinate transform or other user defined transform
2376Coord_menu=get(hseries.CoordType,'String');
2377menu_val=get(hseries.CoordType,'Value');
2378usrfct=Coord_menu{menu_val};
2379testfct=~isequal(usrfct,'');
2380
2381%slice loop
2382siz=size(num_i1{1});
2383lengthtot=siz(1)*siz(2);
2384nbfield=floor(lengthtot/(siz(1)*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
2385nbfield_slice=nbfield*siz(1);% number of fields per slice
2386
2387for i_slice=1:NbSlice
2388   S=0; %initiate the image sum S
2389   nbfiles=0;
2390   nbmissing=0;
2391    %averaging loop
2392   for ifile=i_slice:NbSlice:lengthtot
2393        stopstate=get(hseries.RUN,'BusyAction');
2394        if isequal(stopstate,'queue') % enable STOP command
2395             update_waitbar(hseries.waitbar,WaitbarPos,ifile/lengthtot)
2396             for iview=1:nbview
2397                [filename]=...
2398                           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});
2399                if testima
2400                    Data{iview}.ListVarName={'A'};
2401                    Data{iview}.AName='image';
2402                    if test_movie(iview)
2403                        Data{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
2404                    else
2405                        Data{iview}.A=read_image(filename,NomType{iview},num_i1{iview}(ifile));% read the image, num2 is the counter for avi files
2406                    end
2407                    Atype{iview}=class(Data{iview}.A);
2408                    Data{iview}.A=double(Data{iview}.A);
2409                elseif testcivx
2410                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
2411                else
2412                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
2413                    Data{iview}.VarAttribute=SubField.VarAttribute;
2414                end
2415                if isfield(Data{iview},'Txt')
2416                    msgbox_uvmat('ERROR',['error of input reading: ' Data{iview}.Txt])
2417                    return
2418                end
2419             end   
2420             % coordinate transform (or other user defined transform)
2421             if ~isequal(Series.CoordType,'')
2422                 % z index
2423                if ~isempty(NbSlice_calib)
2424                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;%Zindex for phys transform
2425                end
2426                if nbview==2
2427                    [Data{1},Data{2}]=feval(Series.CoordType,Data{1},XmlData{1},Data{2},XmlData{2});
2428                    if isempty(Data{2})
2429                        Data(2)=[];
2430                    end
2431                else
2432                    Data{1}=feval(Series.CoordType,Data{1},XmlData);
2433                end
2434             end     
2435            if testcivx
2436                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
2437            end
2438            if length(Data)==2
2439                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
2440                if ~isempty(errormsg)
2441                    msgbox_uvmat('ERROR',['error in aver_stat/sub_field:' errormsg])
2442                    return
2443                end
2444            else
2445                Field=Data{1};
2446            end
2447            if isfield(Series,'ProjObject')
2448                [Field,errormsg]=proj_field(Field,Series.ProjObject);
2449                 if ~isempty(errormsg)
2450                    msgbox_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg])
2451                    return
2452                end
2453             end                                                       
2454                nbfiles=nbfiles+1;
2455                if nbfiles==1 %first field
2456                    time_1=[];
2457                    if isfield(Field,'Time')
2458                        time_1=Field.Time(1);
2459                    end
2460                    DataMean=Field;%default
2461                else
2462                    for ivar=1:length(Field.ListVarName)
2463                        VarName=Field.ListVarName{ivar};
2464                        eval(['sizmean=size(DataMean.' VarName ');']);
2465                        eval(['siz=size(Field.' VarName ');']);
2466                        if ~isequal(siz,sizmean)
2467                            warndlg_uvmat(['unequal size of input field ' VarName ', need to interpolate on a grid'],'WARNING')
2468                            nbmissing=nbmissing+1;
2469                            break
2470                        else
2471                            eval(['DataMean.' VarName '=DataMean.' VarName '+ Field.' VarName ';']); % update the sum
2472                        end
2473                    end
2474                end
2475%             else
2476%                 nbmissing=nbmissing+1;
2477%             end
2478        end
2479    end %end averaging loop
2480    for ivar=1:length(Field.ListVarName)
2481        VarName=Field.ListVarName{ivar};
2482        eval(['DataMean.' VarName '=DataMean.' VarName '/nbfiles;']); % normalize the mean
2483    end
2484    if nbmissing~=0
2485        msgbox_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'])
2486    end
2487    if isempty(time) % time read from files  prevails
2488        time_end=[];
2489        if isfield(Field,'Time')
2490            time_end=Field.Time(1);%last time read
2491            if ~isempty(time_1)
2492                DataMean.Time=time_1;
2493                DataMean.Time_end=time_end;
2494            end
2495        end
2496    else  % time from ImaDoc prevails
2497        DataMean.Time=time(1,num_i1{1}(1),num_j1{1}(1));
2498        DataMean.Time_end=time(end,num_i1{end}(end),num_j1{end}(end));
2499    end
2500   
2501    %writing the result file
2502   if testima   
2503       if NbSlice==1
2504        [filemean]=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.png',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end));
2505       else % label the file number by the slice # for simplicity
2506          [filemean]=name_generator(filebase_out,i_slice,1,'.png','_i');
2507       end
2508        if exist(filemean,'file')
2509            backupfile=filemean;
2510            testexist=2;
2511            while testexist==2
2512                backupfile=[backupfile(1:end-4) '~.png'];
2513                testexist=exist(backupfile,'file');
2514            end
2515            [success,message]=copyfile(filemean,backupfile);%make backup
2516            if ~isequal(success,1)
2517                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
2518                return
2519            end
2520        end
2521        if isequal(Atype{1},'uint16')
2522            imwrite(uint16(DataMean.A),filemean,'BitDepth',16);
2523        else
2524            imwrite(uint8(DataMean.A),filemean,'BitDepth',8);
2525        end
2526        display([filemean ' written']);
2527    else %determine global attributes
2528        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {Series.Action}];
2529        ActionKey='Action';
2530        while isfield(DataMean,ActionKey)
2531            ActionKey=[ActionKey '_1'];
2532        end
2533        eval(['DataMean.' ActionKey '=Series.Action;'])
2534        DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {ActionKey}];
2535        if isfield(DataMean,'Time')
2536            DataMean.ListGlobalAttribute=[DataMean.ListGlobalAttribute {'Time','Time_end'}];
2537        end 
2538        if NbSlice==1
2539          filemean=name_generator(filebase_out,num_i1{1}(1),num_j1{1}(1),'.nc',NomTypeOut,1,num_i2{end}(end),num_j2{end}(end));
2540        else % label the file number by the slice # for simplicity
2541          [filemean]=name_generator(filebase_out,i_slice,1,'.nc','_i');
2542        end
2543        if exist(filemean,'file')
2544            backupfile=filemean;
2545            testexist=2;
2546            while testexist==2
2547                backupfile=[backupfile(1:end-3) '~.nc'];
2548                testexist=exist(backupfile,'file');
2549            end
2550            [success,message]=copyfile(filemean,backupfile);%make backup
2551            if ~isequal(success,1)
2552                msgbox_uvmat('ERROR',['previous file result ' filemean ' already exists, problem in backup'])
2553                display(['previous file result ' filemean ' already exists, problem in backup'])
2554                return
2555            end
2556        end
2557        errormsg=struct2nc(filemean,DataMean); %save result file
2558        if isempty(errormsg)
2559            display([filemean ' written']);
2560        else
2561            msgbox_uvmat('ERROR',['error in writting result file: ' errormsg])
2562            display(errormsg)
2563        end
2564   end
2565end
2566hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
2567delete(hget_field)
2568uvmat(filemean)
2569
2570
2571% %----------------------------------------------------------------------
2572% % --makes a time averaged velocity field
2573% %----------------------------------------------------------------------
2574% function aver_vel(num_i1,num_i2,num_j1,num_j2,Series)
2575%                           %handles of the GUI series
2576%   
2577% hseries=guidata(Series.hseries);%handles of the GUI series
2578% WaitbarPos=get(hseries.waitbar_frame,'Position');
2579% Field_list=get(hseries.FieldMenu,'String');
2580% val=get(hseries.FieldMenu,'Value');
2581% FieldName=Field_list{val(1)};
2582% set(hseries.FieldMenu,'Value',val(1))% select only one input field
2583% if isequal(FieldName,'get_field...')
2584%     hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
2585% end
2586% %root input file and type
2587% RootPath=get(hseries.RootPath,'String');
2588% SubDir=get(hseries.SubDir,'String');
2589% RootFile=get(hseries.RootFile,'String');
2590% %NomType=get(hseries.NomType,'String');
2591% NomType=Series.NomType;
2592% FileExt=get(hseries.FileExt,'String');
2593% ext=FileExt{1};     
2594% VelType_str=get(hseries.VelTypeMenu,'String');
2595% VelType_val=get(hseries.VelTypeMenu,'Value');
2596% VelType{1}=VelType_str{VelType_val};
2597%
2598% time=0; %default
2599% % number of slices
2600% NbSlice=str2num(get(hseries.NbSlice,'String'));
2601% if isempty(NbSlice)
2602%     NbSlice=1;
2603% end
2604% NbSlice_name=num2str(NbSlice);
2605% filebase=fullfile(RootPath{1},RootFile{1});
2606% Calib=[];
2607% if exist([filebase '.xml'],'file')
2608%     %[error,Heading,nom_type_read,ext_ima_read,time_imadoc,TimeUnit,mode,NbSlice,npx,npy,Calib]=read_imadoc([filebase '.xml']);
2609%     [XmlData,warntext]=imadoc2struct([filebase '.xml']);
2610% end
2611% if NbSlice==1
2612%    filebase_mean=[filebase '_mean']; %root name for the result
2613% else
2614%    filebase_mean=[filebase '_' NbSlice_name 'mean']; %root name for the results
2615%    answeryes=questdlg({['will make average in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_mean ' ...']});
2616%     if ~isequal(answeryes,'Yes')
2617%     return
2618%     end
2619% end
2620% siz=size(num_i1);
2621% nbfield2=siz(1); %nb of consecutive fields at each level(burst)
2622% lengthtot=siz(1)*siz(2);
2623% nbfield=floor(lengthtot/(nbfield2*NbSlice));%total number of i indexes (adjusted to an integer number of slices)
2624% nbfield_slice=nbfield*nbfield2;% number of fields per slice
2625% %projection object
2626% GridX=[];
2627% GridY=[];
2628% if isfield(Series,'sethandles')
2629%         Series.ProjObject=read_set_object(Series.sethandles);
2630%         if isfield(Series.ProjObject,'Style')
2631%             answeryes=questdlg({['statistics on field series projected on ' Series.ProjObject.Style]});
2632%             if ~isequal(answeryes,'Yes')
2633%                 return
2634%             end
2635%         end
2636% end
2637%
2638% %LOOP ON SLICES
2639% for i_slice=1:NbSlice
2640%     %select the series of image indices at the level islice
2641%     for ifield=1:nbfield
2642%         indselect(:,ifield)=((ifield-1)*NbSlice+(i_slice-1))*nbfield2+[1:nbfield2]';%selected indices on the list of files of a slice
2643%     end 
2644%     %name of result file
2645%     [filemean,idetect]=...
2646%                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});
2647%
2648%     % field=get(handles.civ1,'UserData');%read current selected field type (civ1,civ2...)
2649%     itime=0;
2650%      dt=[];
2651%      %LOOP ON FIELDS IN  A SLICE
2652%      test_interpolate=0;%default
2653%     for index=1:nbfield*nbfield2
2654%             ifile=indselect(index);
2655%         stopstate=get(hseries.RUN,'BusyAction');
2656%         if isequal(stopstate,'queue')% enable STOP command
2657%             update_waitbar(hseries.waitbar,WaitbarPos,ifile/(nbfield*nbfield2))
2658%             %name of the current file
2659%             [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});
2660%             %read input file
2661%             itime=itime+1;
2662%             if isequal(FieldName,'get_field...')
2663%                 hhget_field=guidata(hget_field);%handles of GUI elements in get_field
2664%                 hObject=0;
2665%                 eventdata=0;
2666%                 SubField=get_field('read_var_names',hObject,eventdata,hhget_field); %read the names of the variables to plot in the get_field GUI
2667%                 [Data,var_detect]=nc2struct(filename,SubField.ListVarName); %read input data   
2668%                 time(itime)=itime;
2669%                 dt=1;
2670%                 Calib_read=[];
2671%             else
2672%                 [nb_coord,nb_dim,Civ,CivStage,timeread,Data,VelTypeOut,Calib_read]=read_ncfield(filename,VelType{1});%reading the first file
2673%                  time(itime)=timeread;
2674%                 if isequal(Civ,1)
2675%                     Data.CoordType='px';%test for pixel coordinates
2676%                     if isequal(itime,1)
2677%                         dt=Data.dt;
2678%                     elseif ~isequal(Data.dt,dt)
2679%                         warndlg_uvmat('series with non constant dt, need phys coordinates','ERROR')
2680%                         return
2681%                     end
2682%                 end
2683%             end
2684%             %increment the detected fields, skip the others
2685%             if idetect==0
2686%                 warndlg_uvmat(['input file ' filename ' not found'],'ERROR')
2687%                 %A FAIRE STOCKER LE RESULT ACTUEL S'IL EXISTE
2688%             end
2689% %             itime=itime+1;
2690% %             time(itime)=timeread;
2691%       
2692%             %coordinate transform
2693%             if isempty(Calib)
2694%                 Calib=Calib_read;%use Calib from xml file in priority, then Calib from the current file
2695%             end
2696%             if ~isequal(Series.CoordType,'')
2697%                 Data=feval(Series.CoordType,Data,Calib);
2698%             end
2699%             %projection on object if defined
2700%             if isfield(Series,'ProjObject');
2701%                 Data=proj_field(Data,Series.ProjObject);
2702%                 if isequal(itime,1)%use the positions on the first field for the whole series, ou utiliser grille
2703%                     if isfield(Data,'Txt')%display error message
2704%                         warndlg(Data.Txt,'ERROR')
2705%                         return
2706%                     end
2707%                 end
2708%             else%remove false vectors and interpolate on the positions of the first field
2709%                 Data=document_field(Data);
2710%                 Data.Style='plane';
2711%             end
2712%     %%%%%%%%% initiate the average at the first iteration: check list and structure of variables
2713%             if ifile==i_slice%first field in the slice
2714%                 testfalse=0;
2715%                 ListIndex={};
2716%                 testnewcell=1;
2717%                 %group the variables (fields of 'Data') in cells of variables with the same dimensions
2718%                 [DimVarIndex,CellVarIndex]=find_field_indices(Data);
2719%                 VarIndex=CellVarIndex{1}; % ONLY THE FIRST VAR GROUP IS AVERAGED
2720%                 DimIndex=Data.VarDimIndex{VarIndex(1)};%indices of the dimensions of the first variable (common to all variables in the cell)         
2721%                 MeanData=Data;%transfer heading
2722%                 MeanData.Time=[time(1) time(end)];
2723%                 MeanData.Action=Series.Action;%name of the processing programme
2724%                 MeanData.ListDimName=Data.ListDimName(DimIndex);%name of dimension
2725%                 MeanData.DimValue=Data.DimValue(DimIndex);%values of dimension (nbre of vectors)
2726%                 MeanData.ListVarName=Data.ListVarName;
2727%                 MeanData.VarDimIndex=Data.VarDimIndex;
2728%                 MeanData.ListVarAttribute={'Role'};%list of variable attribute names A FAIRE: transferer les autres attributs
2729%                 testsum=ones(size(VarIndex));
2730%                 indexfalse=0;
2731%                 CoordName={};
2732%                 indexremove=[];
2733%                 if isfield(Data,'Role') % look for coordinate and flag variables   
2734%                     for ivar=1:length(VarIndex)
2735%                         VarName=Data.ListVarName{VarIndex(ivar)};
2736%                         var_role=Data.Role{VarIndex(ivar)};%'role' of the variable
2737%                         MeanData.Role{ivar}=var_role;
2738%                         if isequal(var_role,'falseflag')
2739%                             indexfalse=ivar; %test for false flag
2740%                             indexremove=ivar;
2741%                             FFName=VarName;
2742%                             testsum(ivar)=0;
2743%                             eval(['MeanData=rmfield(MeanData,''' VarName ''');']);%remove variable                     
2744%                         end
2745%                         if isequal(var_role,'warnflag')                       
2746%                             testsum(ivar)=0; %do not sum warn flag
2747%                             eval(['MeanData=rmfield(MeanData,''' VarName ''');']);%remove variable
2748%                             indexremove=[indexremove ivar];
2749%                         end                 
2750%                         if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|isequal(var_role,'coord_z')
2751%                             eval(['MeanData.' VarName '=Data.' VarName ';']);
2752%                             testsum(ivar)=0;
2753%                             eval(['CoordName=[CoordName ''' VarName '''];']);
2754%                         end
2755%                         if testsum(ivar)~=0
2756%                            eval(['MeanData.' VarName '=zeros(size(Data.' VarName '));']);%initialise sum
2757%                         end
2758%                     end
2759%                 end
2760%                 findsum=find(testsum);
2761%                 VarIndexSum=VarIndex(findsum);%indices of variables to sum (not coordinates nor flags)
2762%                 if length(CoordName)==0
2763%                     if isempty(DimVarIndex)|isequal(DimVarIndex,0)% no coordinate variable for structured coordinates, prepare histograms
2764%                          for ilist=1:length(VarIndexSum)
2765%                             VarName=Data.ListVarName{VarIndexSum(ilist)};
2766%                             eval(['MeanData=rmfield(MeanData,''' VarName ''');']);%remove variable
2767%                             indexremove=[indexremove ilist];
2768%                             eval(['[MeanData.' VarName 'hist,MeanData.' VarName 'val]=hist(Data.' VarName ',100);']);%make histo
2769%                             eval(['sizhist=size(MeanData.' VarName 'hist);'])
2770%                             if sizhist(1)==1
2771%                                 eval(['MeanData.' VarName 'hist=MeanData.' VarName 'hist'';'])
2772%                             end
2773%                             eval(['maxval=max(MeanData.' VarName 'val);']);
2774%                             eval(['minval=min(MeanData.' VarName 'val);']);
2775%                             dC(ilist)=(maxval-minval)/100;%size of the histogram bin   
2776%                          end
2777%                     else
2778% %                         icoord=0;
2779% %                         for ilist=1:length(DimVarIndex) 
2780% %                             VarDim=Data.ListVarName{DimVarIndex(ilist)};
2781% %                             icoord=icoord+1;
2782% %                             % eval(['Coord{' num2str(icord) '}=[' CoordName ''' VarName ''']']);
2783% %                              %eval(['Data.' CoordName{icoord} '=Data.' CoordName{icoord} '(indsel);']);
2784% %                         end
2785%                     end
2786%                 end
2787%                 if ~isempty(indexremove)
2788%                     MeanData.ListVarName(VarIndex(indexremove))=[];
2789%                     MeanData.VarDimIndex(VarIndex(indexremove))=[];
2790%                     if isfield(MeanData,'Role')%generaliser aus autres attributs
2791%                         MeanData.Role(VarIndex(indexremove))=[];
2792%                     end
2793%                 end
2794%                % END OF INITIALISATION
2795%
2796%             end
2797%       
2798%          % A FAIRE: regular grid if coord_x undefined
2799%             if indexfalse~=0 %suppress false data
2800%                  eval(['testexist=isfield(Data,''' FFName ''');'])
2801%                 if testexist
2802%                     eval(['indsel=find(Data.' FFName '==0);']);
2803%                     for icoord=1:length(CoordName)
2804%                         eval(['Data.' CoordName{icoord} '=Data.' CoordName{icoord} '(indsel);']);
2805%                     end
2806%                 end
2807%             end
2808%             for ilist=1:length(VarIndexSum)
2809%                 VarName=Data.ListVarName{VarIndexSum(ilist)};
2810%                 if indexfalse~=0 & testexist
2811%                     eval(['Data.' VarName '=Data.' VarName '(indsel);']);
2812%                 end
2813%                 if length(CoordName)==0%no variable use dfor unstructured coordinates
2814%                     if isempty(DimVarIndex)|isequal(DimVarIndex,0)% no coordinate variable for structured coordinates
2815% %                         %update histogram with the current field #ifile
2816%                         str_left=['[MeanData.' VarName 'val,MeanData.' VarName 'hist]='];
2817%                         str_right=['hist_update(MeanData.' VarName 'val,MeanData.' VarName 'hist,Data.' VarName ',dC(ilist));'];
2818%                         eval([str_left str_right]);%update global histo
2819%                     else
2820%                        %INTERPOLER
2821%                             
2822%                         eval(['MeanData.' VarName '=MeanData.' VarName '+Data.' VarName ';']);%increment sum%CAS x,y change
2823%                     end
2824%                 else   
2825%                     if length(CoordName)==2
2826%                         eval(['test_interp= ~isequal(Data.' CoordName{1} ',MeanData.' CoordName{1} ...
2827%                             ')|~isequal(Data.' CoordName{2} ',MeanData.' CoordName{2} ');'])
2828%                         if test_interp
2829%                             eval(['Data.' VarName '=griddata_uvmat(Data.' CoordName{1} ',Data.' CoordName{2}...
2830%                                 ',Data.' VarName ',MeanData.' CoordName{1} ',MeanData.' CoordName{2} ');']);
2831%                             test_interpolate=1;
2832%                         end
2833%                     end
2834%                     eval(['MeanData.' VarName '=MeanData.' VarName '+Data.' VarName ';']);%increment sum
2835%                 end
2836%             end
2837%         end
2838%     end
2839%     if length(CoordName)~=0 | ~isequal(DimVarIndex,0)% no coordinate variable for structured coordinates
2840%         for ilist=1:length(VarIndexSum) 
2841%             VarName=Data.ListVarName{VarIndexSum(ilist)};
2842%             eval(['MeanData.' VarName '=MeanData.' VarName '/itime;']);%normalize sum by the number of fields
2843%         end
2844%     else
2845%         MeanData.NbDim=1;
2846%         MeanData.ListDimName={};
2847%         MeanData.DimValue=[];
2848%         for ilist=1:length(VarIndexSum) 
2849%             VarName=Data.ListVarName{VarIndexSum(ilist)};
2850%             MeanData.ListVarName=[MeanData.ListVarName {[VarName 'val']} {[VarName 'hist']}];
2851%             MeanData.VarDimIndex=[MeanData.VarDimIndex {[ilist]} {[ilist]}];
2852%             MeanData.ListDimName=[MeanData.ListDimName {[VarName 'val']}];
2853%             eval(['MeanData.DimValue=[MeanData.DimValue length(MeanData.' VarName 'val)];']);
2854%         end   
2855%     end
2856%     figure
2857%     haxes=axes;
2858%     plot_field(MeanData,haxes)%plot the resulting average
2859%     % change variable names for consitency with civ1 data (need to generalize these programs)
2860%     if length(MeanData.ListVarName) >= 4 & isequal(MeanData.ListVarName(1:4), {'X'  'Y'  'U'  'V'})
2861%        MeanData.ListGlobalAttribute={'nb_coord','nb_dim','dt','absolut_time_T0','pixcmx','pixcmy','hart','civ','fix'};
2862%        MeanData.nb_coord=2;
2863%        MeanData.nb_dim=2;
2864%        MeanData.dt=1;
2865%        MeanData.absolut_time_T0=0;
2866%        MeanData.pixcmx=1; %pix per cm (1 by default)
2867%        MeanData.pixcmy=1; %pix per cm (1 by default)
2868%        MeanData.hart=0;
2869%        if isequal(Data.CoordType,'px')
2870%          MeanData.civ=1;
2871%       else
2872%          MeanData.civ=0;
2873%        end
2874%       MeanData.fix=0;
2875%         MeanData.ListVarName(1:4)={'vec_X'  'vec_Y'  'vec_U'  'vec_V'};
2876%         MeanData.vec_X=MeanData.X;
2877%         MeanData.vec_Y=MeanData.Y;
2878%         MeanData.vec_U=MeanData.U;
2879%         MeanData.vec_V=MeanData.V;
2880%     end
2881%     error=struct2nc(filemean,MeanData); %save result file
2882%     if isequal(error,0)
2883%         if test_interpolate
2884%             'fields interpolated to the positions of the first one'
2885%         end
2886%         [filemean ' written']
2887%     else
2888%         warndlg_uvmat(error,'ERROR')
2889%     end
2890% end
2891
2892%----------------------------------------------------------------------
2893% --project fields on a projection object (e. g. a regular grid), possibly
2894% merge several fields
2895%----------------------------------------------------------------------
2896%INPUT:
2897%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2898%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
2899%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
2900%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
2901%OTHER INPUTS given by the structure Series
2902function GUI_input=merge_proj(num_i1,num_i2,num_j1,num_j2,Series);
2903
2904%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
2905if ~exist('num_i1','var')
2906    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
2907        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
2908        'RootFile';'on';... %root input file name ('on' by default)
2909        'FileExt';'on';... %input file extension ('on' by default)
2910        'NomType';'on';...%type of file indexing ('on' by default)
2911        'NbSlice';'on'; ...%nbre of slices ('off' by default)
2912        'VelTypeMenu';'one';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
2913        'FieldMenu';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
2914        'CoordType';'on';...%can use a transform function 'off' by default
2915        'GetObject';'on';...%can use projection object ,'off' by default
2916        %'GetMask';'on'...%can use mask option   ,'off' by default
2917        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
2918               ''};
2919    return %exit the function
2920end
2921
2922%-------------------------------------------------
2923hseries=guidata(Series.hseries);%handles of the GUI series
2924WaitbarPos=get(hseries.waitbar_frame,'Position'); %positiopn of waitbar frame
2925%-------------------------------------------------
2926
2927%numbers of view fields (nbre of inputs in RootPath)
2928testcell=iscell(Series.RootFile);
2929if ~testcell
2930    Series.RootPath={Series.RootPath};
2931    Series.RootFile={Series.RootFile};
2932    Series.SubDir={Series.SubDir};
2933    Series.FileExt={Series.FileExt};
2934    Series.NomType={Series.NomType};
2935    num_i1={num_i1};
2936    num_i2={num_i2};
2937    num_j1={num_j1};
2938    num_j2={num_j2};
2939end
2940nbview=length(Series.RootFile);%number of views (file series to merge)
2941nbfield=size(num_i1{1},1)*size(num_i1{1},2);%number of fields in the time series
2942transform=Series.CoordType; %  field transform function
2943hhh=which('mmreader');
2944for iview=1:nbview
2945    test_movie(iview)=0;
2946    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
2947        if isequal(lower(FileExt{iview}),'.avi')
2948            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
2949            test_movie(iview)=1;
2950        end
2951    end
2952end
2953
2954%Calibration data and timing: read the ImaDoc files
2955mode=''; %default
2956timecell={};
2957itime=0;
2958NbSlice_calib={}; %test for z index
2959for iview=1:nbview%Loop on views
2960    XmlData{iview}=[];%default
2961    filebase{iview}=fullfile(Series.RootPath{iview},Series.RootFile{iview});
2962    if exist([filebase{iview} '.xml'],'file')
2963        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
2964        if isfield(XmlData{iview},'Time')
2965            itime=itime+1;
2966            timecell{itime}=XmlData{iview}.Time;
2967        end
2968        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
2969            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);
2970            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
2971                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
2972            end
2973        end   
2974    elseif exist([filebase{iview} '.civ'],'file')
2975        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
2976        itime=itime+1;
2977        timecell{itime}=time;
2978        XmlData{iview}.Time=time;
2979        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
2980        GeometryCalib.Tx=0;
2981        GeometryCalib.Ty=0;
2982        GeometryCalib.Tz=1;
2983        GeometryCalib.dpx=1;
2984        GeometryCalib.dpy=1;
2985        GeometryCalib.sx=1;
2986        GeometryCalib.Cx=0;
2987        GeometryCalib.Cy=0;
2988        GeometryCalib.f=1;
2989        GeometryCalib.kappa1=0;
2990        GeometryCalib.CoordUnit='cm';
2991        XmlData{iview}.GeometryCalib=GeometryCalib;
2992        if error==1
2993            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
2994        end
2995    end
2996end
2997
2998%check coincidence in time
2999multitime=0;
3000if length(timecell)==0
3001    time=[];
3002elseif length(timecell)==1
3003    time=timecell{1};
3004elseif length(timecell)>1
3005    multitime=1;
3006    for icell=1:length(timecell)
3007        if ~isequal(size(timecell{icell}),size(timecell{1}))
3008            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
3009            time=timecell{1};
3010            multitime=0;
3011            break
3012        end
3013    end
3014end
3015if multitime
3016    for icell=1:length(timecell)
3017        time(icell,:,:)=timecell{icell};
3018    end
3019    diff_time=max(max(diff(time)));
3020    if diff_time>0
3021        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
3022    end   
3023end
3024if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
3025    time=[];
3026end
3027
3028% Field and velocity type (the same for all views)
3029Field_str=get(hseries.FieldMenu,'String');
3030val=get(hseries.FieldMenu,'Value');
3031FieldName=Field_str(val);%the same set of fields for all views
3032VelType_str=get(hseries.VelTypeMenu,'String');
3033VelType_val=get(hseries.VelTypeMenu,'Value');
3034VelType=VelType_str{VelType_val}; %the same for all views
3035if isequal(FieldName,'get_field...')
3036    hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
3037    hhget_field=guidata(hget_field);%handles of GUI elements in get_field
3038    SubField=get_field('read_var_names',hObject,eventdata,hhget_field); %read the names of the variables to plot in the get_field GUI
3039    if isequal(get(hhget_field.menu_coord,'Visible'),'on')
3040        list_transform=get(hhget_field.menu_coord,'String');
3041        val_list=get(hhget_field.menu_coord,'Value');
3042        transform=list_transform{val_list};
3043    end
3044end
3045%detect whether all the files are 'images' or 'netcdf'
3046testima=0;
3047testvol=0;
3048testcivx=0;
3049testnc=0;
3050FileExt=get(hseries.FileExt,'String');
3051for iview=1:nbview
3052     ext=FileExt{iview};
3053     form=imformats(ext([2:end]));
3054     if isequal(lower(ext),'.vol')
3055         testvol=testvol+1;
3056     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
3057         testima=testima+1;
3058     elseif isequal(ext,'.nc')
3059         testnc=testnc+1;
3060     end
3061end
3062if testvol
3063    msgbox_uvmat('ERROR','volume images not implemented yet')
3064    return
3065end
3066if testnc~=nbview && testima~=nbview && testvol~=nbview
3067    msgbox_uvmat('ERROR','need a set of images or a set of netcdf files with the same fields as input')
3068    return
3069end
3070if ~isequal(FieldName,'get_field...')
3071    testcivx=testnc;
3072end
3073%name of output files and directory:
3074% res_subdir=fullfile(Series.RootPath{1},[Series.SubDir{1} '_STAT']);
3075ProjectDir=fileparts(fileparts(Series.RootPath{1}));% preoject directory (GERK)
3076prompt={['result directory (in' ProjectDir ')']};
3077RootPath=get(hseries.RootPath,'String');
3078SubDir=get(hseries.SubDir,'String');
3079if isequal(length(RootPath),1)
3080    fulldir=RootPath{1};
3081    subdir='GRID';
3082    res_subdir=fullfile(fulldir,subdir);
3083else
3084    def={fullfile(ProjectDir,'0_RESULTS')};
3085    dlgTitle='result directory';
3086    lineNo=1;
3087    answer=msgbox_uvmat('INPUT_TXT',dlgTitle,def);
3088    fulldir=answer{1};
3089    subdir=[];
3090    dirlist=sort(Series.RootFile);
3091    for iview=1:nbview
3092        if ~isempty(subdir)
3093            subdir=[subdir '-'];
3094        end
3095        subdir=[subdir dirlist{iview}];
3096    end 
3097    res_subdir=fullfile(fulldir,subdir);
3098end
3099ext=FileExt{1};
3100if ~exist(fulldir,'dir')
3101    msgbox_uvmat('ERROR',['directory ' fulldir ' needs to be created'])
3102    return
3103end
3104if ~exist(res_subdir,'dir')
3105    dircur=pwd;
3106    cd(fulldir)
3107    error=mkdir(subdir);
3108    cd(dircur)
3109end
3110filebasesub=fullfile(res_subdir,Series.RootFile{1});
3111filebase_merge=fullfile(res_subdir,'merged');%root name for the merged files
3112
3113%projection object
3114if isfield(Series,'sethandles')
3115    if ishandle(Series.sethandles.set_object)
3116        Series.ProjObject=read_set_object(Series.sethandles);
3117        if ~isfield(Series.ProjObject,'Style')
3118            msgbox_uvmat('ERROR','Undefined projection object style')
3119            return
3120        end
3121        if ~isequal(Series.ProjObject.Style,'plane')
3122            msgbox_uvmat('ERROR','The projection object must be a plane')
3123            return
3124        end
3125    end
3126end
3127
3128    %MAIN LOOP
3129for ifile=1:nbfield               
3130    stopstate=get(hseries.RUN,'BusyAction');
3131    if isequal(stopstate,'queue')% enable STOP command from the 'series' interface
3132         update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
3133         Amerge=0;
3134         
3135         %----------LOOP ON VIEWS----------------------
3136        nbtime=0;
3137        for iview=1:nbview
3138            %name of the current file
3139            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});
3140            if ~exist(filename,'file')
3141                msgbox_uvmat('ERROR',['missing input file' filename])
3142                break
3143            end
3144
3145            %reading the current file
3146            if testima
3147                if test_movie(iview)
3148                    Field{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
3149                else
3150                    Field{iview}.A=read_image(filename,Series.NomType{iview},num_i1{iview}(ifile));
3151                end % TODO: introduce ListVarName
3152                npxy=size(Field{iview}.A);
3153                Field{iview}.AX=[0.5 npxy(2)-0.5]; % coordinates of the first and last pixel centers
3154                Field{iview}.AY=[npxy(1)-0.5 0.5];
3155                Field{iview}.CoordType='px';
3156                Field{iview}.AName='image';
3157            else
3158                if testcivx
3159                    [Field{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
3160                else
3161                    [Field{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
3162                    Field{iview}.VarAttribute=SubField.VarAttribute;
3163                end
3164                if isfield(Field{iview},'Time')
3165                    timeread(iview)=Field{iview}.Time;
3166                    nbtime=nbtime+1;
3167                end
3168            end
3169            % coord transform
3170            % z index
3171            if ~isempty(NbSlice_calib)
3172                Field{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
3173            end
3174            if ~isequal(transform,'')
3175                Field{iview}=feval(Series.CoordType,Field{iview},XmlData{iview});%transform to phys if requested
3176            end
3177            if testcivx
3178                    Field{iview}=calc_field(FieldName,Field{iview});
3179            end
3180
3181            %projection on object (gridded plane)
3182            if isfield(Series,'ProjObject')
3183                Field{iview}=proj_field(Field{iview},Series.ProjObject);
3184            end
3185        end   
3186       
3187         %----------END LOOP ON VIEWS----------------------
3188         
3189        %merge the nbview fields
3190        MergeData=merge_field(Field);
3191        if isfield(MergeData,'Txt')
3192            msgbox_uvmat('ERROR',MergeData.Txt)
3193            return
3194        end
3195       
3196        % generating the name of the merged field
3197        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));
3198       
3199        % time:
3200        time_i=0;%default
3201        if isempty(time)% time from ImaDoc prevails
3202            time_i=sum(timeread)/nbtime;
3203        else
3204            time_i=(time(iview,num_i1{iview}(ifile),num_j1{iview}(ifile))+time(iview,num_i2{iview}(ifile),num_j2{iview}(ifile)))/2;
3205        end
3206       
3207        % recording the merged field
3208        if testima    %in case of input images an image is produced   
3209            if isa(MergeData.A,'uint8')
3210                bitdepth=8;
3211            elseif isa(MergeData.A,'uint16')
3212                bitdepth=16;
3213            end
3214            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
3215            %write xml calibration file
3216            siz=size(MergeData.A);
3217            npy=siz(1);
3218            npx=siz(2);
3219            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
3220                Rangx=MergeData.VarAttribute{1}.Coord_2;
3221                Rangy=MergeData.VarAttribute{1}.Coord_1;
3222            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
3223                Rangx=[MergeData.AX(1) MergeData.AX(end)];
3224                Rangy=[MergeData.AY(1) MergeData.AY(end)];
3225            else
3226                Rangx=[0.5 npx-0.5];
3227                Rangy=[npy-0.5 0.5];%default
3228            end
3229            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
3230            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
3231            T_x=-pxcmx*Rangx(1)+0.5;
3232            T_y=-pxcmy*Rangy(2)+0.5;
3233            GeometryCal.focal=1;
3234            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
3235            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
3236            ImaDoc.GeometryCalib=GeometryCal;
3237            t=struct2xml(ImaDoc);
3238            t=set(t,1,'name','ImaDoc');
3239            save(t,[filebase_merge '.xml'])     
3240            display([filebase_merge '.xml saved'])
3241        else
3242            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
3243            MergeData.nb_coord=2;
3244            MergeData.nb_dim=2;
3245            MergeData.dt=1;
3246            MergeData.Time=time_i;
3247            error=struct2nc(mergename,MergeData); %save result file
3248            if isempty(error)
3249                display(['output file ' mergename ' written'])
3250            else
3251                display(error)
3252            end
3253        end
3254    end
3255end
3256
3257%--------------------------------------------------------------------------   
3258function MergeData=merge_field(Data)
3259% initiate Matlab  structure for physical field
3260if isempty(Data)||~iscell(Data)
3261    MergeData=[];
3262    return
3263end
3264MergeData=Data{1};%default
3265error=0;
3266nbview=length(Data);
3267if nbview==1
3268    return
3269end
3270for iview=1:nbview
3271    if ~isequal(MergeData.ListDimName,Data{iview}.ListDimName)
3272        error=1;
3273    end
3274    if ~isequal(MergeData.ListVarName,Data{iview}.ListVarName)
3275        error=1;
3276    end
3277%      if ~isequal(MergeData.VarDimIndex,Data{iview}.VarDimIndex)
3278%         error=1;
3279%      end
3280end
3281if error
3282    MergeData.Txt='ERROR: attempt at merging fields of incompatible type';
3283    return
3284end
3285%group the variables (fields of 'FieldData') in cells of variables with the same dimensions
3286%-----------------------------------------------------------------
3287[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
3288%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
3289% CellVarIndex=cells of variable index arrays
3290ivar_new=0; % index of the current variable in the projected field
3291icoord=0;
3292for icell=1:length(CellVarIndex)
3293    if NbDim(icell)==1
3294        continue
3295    end
3296    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
3297    VarType=VarTypeCell{icell};
3298    ivar_X=VarType.coord_x;
3299    ivar_Y=VarType.coord_y;
3300    ivar_FF=VarType.errorflag;
3301    if isempty(ivar_X)
3302        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
3303    else
3304        if length(ivar_Y)~=1
3305                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
3306                return
3307        end
3308        test_grid=0;
3309    end
3310 %   DimIndices=Data{1}.VarDimIndex{VarIndex(1)};%indices of the dimensions of the first variable (common to all variables in the cell)
3311    %case of input fields with unstructured coordinates
3312    if ~test_grid
3313        for ivar=VarIndex
3314            VarName=MergeData.ListVarName{ivar};
3315            for iview=1:nbview
3316                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName ';'])
3317            end
3318        end
3319    %case of fields defined on a structured  grid
3320    else 
3321%         DimValue=MergeData.DimValue(DimIndices);%set of dimension values
3322        testFF=0;
3323        for iview=2:nbview
3324%             if ~isequal(DimValue,Data{iview}.DimValue(DimIndices))
3325%                 MergeData.Txt='ERROR: attempt at merging structured fields with different sizes';
3326%                 return
3327%             end
3328            for ivar=VarIndex
3329                VarName=MergeData.ListVarName{ivar};
3330                if isfield(MergeData,'VarAttribute')
3331                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
3332                        testFF=1;
3333                    end
3334                end
3335                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
3336            end
3337        end
3338        if testFF
3339            nbaver=nbview-MergeData.FF;
3340            indgood=find(nbaver>0);
3341            for ivar=VarIndex
3342                VarName=MergeData.ListVarName{ivar};
3343                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
3344            end
3345        else
3346            for ivar=VarIndex
3347                VarName=MergeData.ListVarName{ivar};
3348                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
3349            end   
3350        end
3351    end
3352end
3353   
3354   
3355%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3356 %detect the chosen series of files and check their date of modification:
3357%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3358%INPUT:
3359%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3360%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3361%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
3362%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
3363%OTHER INPUTS given by the structure Series
3364function 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);
3365
3366%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
3367if ~exist('num_i1','var')
3368    GUI_input={'RootPath';'many';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
3369        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
3370        %'RootFile';'on';... %root input file name ('on' by default)
3371        %'FileExt';'on';... %input file extension ('on' by default)
3372        %'NomType';'on';...%type of file indexing ('on' by default)
3373        %'NbSlice';'on'; ...%nbre of slices ('off' by default)
3374        %'VelTypeMenu';'one';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
3375        %'FieldMenu';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
3376        %'CoordType';'on'...%can use a transform function 'off' by default
3377        %'GetObject';'on'...%can use projection object ,'off' by default
3378        %'GetMask';'on'...%can use mask option   ,'off' by default
3379        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
3380               ''};
3381    return %exit the function
3382end
3383%---------------------------------------------------------
3384hseries=guidata(Series.hseries);%handles of the GUI series
3385WaitbarPos=get(hseries.waitbar_frame,'Position');
3386
3387%%%%%%%%%%%%%%%%%%%%%%%%
3388message='this function will delete all files with extensions .log, .bat, .cmx,.cmx2,.errors in the input directory(ies)';
3389answer=msgbox_uvmat('INPUT_Y-N',message);
3390if ~isequal(answer,'Yes')
3391    return
3392end
3393nbdelete=0;
3394testcell=iscell(Series.RootFile);
3395if ~testcell
3396    Series.RootPath={Series.RootPath};
3397    Series.RootFile={Series.RootFile};
3398    Series.SubDir={Series.SubDir};
3399    Series.FileExt={Series.FileExt};
3400    Series.NomType={Series.NomType};
3401end
3402for iview=1:length(Series.RootFile)
3403    hdir=dir(fullfile(Series.RootPath{iview},Series.SubDir{iview}));%list files
3404    for ilist=1:length(hdir)
3405        update_waitbar(hseries.waitbar,WaitbarPos,ilist/length(hdir))
3406        FileName=hdir(ilist).name;
3407        [dd,ff,Ext]=fileparts(FileName);
3408        if isequal(Ext,'.log')||isequal(Ext,'.bat')||isequal(Ext,'.cmx')||isequal(Ext,'.cmx2')|| isequal(Ext,'.errors')
3409            delete(fullfile(Series.RootPath{iview},Series.SubDir{iview},FileName))
3410            nbdelete=nbdelete+1;
3411        end
3412    end
3413end
3414msgbox_uvmat('CONFIRMATION',['END: ' num2str(nbdelete) ' files deleted by clean_civ_cmx'])
3415
3416
3417
3418
3419
3420%-----------------------------
3421function mouse_up_gui(ggg,eventdata,handles)
3422if isequal(get(ggg,'SelectionType'),'alt')
3423    display('global CurData, UserData of GUI series')
3424    global CurData
3425    CurData=get(ggg,'UserData');
3426    evalin('base','global CurData');%make CurData global in the workspace
3427    evalin('base','CurData'); %display CurData in the workspace
3428    commandwindow
3429   % plot_text(CurData)
3430end
3431
3432
3433
3434% %----------------------------------------------------------------------
3435% % --- display image movie and display time average
3436% %OBSOLETE: A SUPPRIMER
3437% %----------------------------------------------------------------------
3438% function movie_ima(handles,filecell,filecell_1,num1,num_a,field)
3439%
3440% global hfig1 hfig2 hfig3 poscolbar
3441% global A val HIST
3442%
3443% A=[];aviobj=[];
3444% % set(hfig1,'UserData','ima')% set the current field state to 'image'
3445% set(handles.zoom,'Value',1); %put zoom on
3446% nom_type=get(handles.file_input,'UserData');
3447% % field=get(handles.civ1,'UserData');
3448% % fields=field(1).fields;
3449% set(handles.speed,'Visible','On')%show slider to set movie speed
3450% set(handles.mo_speed_txt,'Visible','On')
3451%
3452% if ~isempty(filecell_1)
3453%    file1=get(handles.file1_input,'UserData');
3454%    field1=file1.field;
3455%    scal_type1=field1.fields;
3456%    vel_type1=field1.vel_type;
3457%    filename_1=filecell_1(1);% first file name in the series
3458% else
3459%    filename_1=[];
3460% end
3461% scal_type{1}=field(1).fields;
3462% vel_type{1}=field(1).vel_type;
3463% % display the first field
3464% [A,time,dt,rangx0,rangy0]=view_ima(handles,cell2mat(filecell(1)),filename_1,num1(1),num_a(1));
3465%
3466% % calculate the histogram of the first image
3467% nxy=size(A);
3468% ndim=length(nxy);
3469% if ndim==2 % case of B/W images
3470%     nxy(3)=1;
3471% end
3472% C=reshape(A,nxy(1)*nxy(2),nxy(3));
3473% Amaxmax=double(max(max(max(A))));
3474% Aminmin=double(min(min(min(A))));
3475% if isa(C,'uint8')|isa(C,'uint16')
3476%     C=double(C);
3477%     dC=1;
3478% else
3479%     dC=(Amaxmax-Aminmin)/100;
3480% end
3481% val=[Aminmin:dC:Amaxmax];% define bins for histogram
3482% HIST=hist(C,val);% initiate the global histogram
3483% if ndim==2, HIST=HIST'; end;
3484%
3485% auto_scale=get(handles.auto_scale,'Value');
3486% min_input=str2num(get(handles.min_input,'String'));% select the minimum
3487% max_input=str2num(get(handles.scale_input,'String'));% select the max
3488% zoomstate=get(handles.zoom,'Value');
3489%
3490% if isequal(get(handles.window_input,'String'),'avi'),
3491%     basename=get(handles.file_input,'String');
3492%     prompt = {'file name';'frames per second';'frame resolution ([nbpixels x y])';'axis position relative to the frame'};
3493%     dlg_title = 'select properties of the output avi movie';
3494%     num_lines= 1;
3495%     def     = {[basename '_out.avi'];'5';'[1024 768]';'[0.05 0.07 0.87 0.88]'};
3496%     answer = inputdlg(prompt,dlg_title,num_lines,def);
3497%     aviname=answer{1};
3498%     fps=str2num(answer{2});
3499%     if exist(aviname,'file')==2
3500%         delete(aviname);
3501%     end;
3502%     aviobj=avifile(aviname,'Compression','None','fps',fps);
3503%     
3504%     %display first view for tests
3505%     figure(2);
3506%     hh=get(gcf,'CurrentAxes');
3507%     if isempty(hh),
3508%         hfig1=axes;
3509%     else
3510%         hfig1=hh;
3511%     end;
3512%     if isequal(filecell_1,{})
3513%         filename_1=[];
3514%     else
3515%         filename_1=cell2mat(filecell_1(1));
3516%     end
3517%     poscolbar=[0.93 0.15 0.02 0.7];
3518%     view_ima(handles,cell2mat(filecell(1)),filename_1,num1(1),num_a(1));% show the first field
3519%     nbpix=eval(answer{3});
3520%     set(gcf,'Position',[1 1 nbpix])% resolution XVGA
3521%     set(hfig1,'Position',eval(answer{4}));
3522%     
3523%     msgbox({'adjust figure 2 with its matlab edit menu ' ;...
3524%             'then type any keyboard key to get the avi movie as a copy of figure 2 display'})
3525%     pause;
3526%     hh=colorbar;
3527%     poscolbar=get(hh,'Position');
3528% end
3529%
3530% %%%%%%%%%%%%%%%%
3531% %mask and usrdfct
3532% maskname=[]; %default
3533% if isequal(get(handles.mask_test,'Value'),1)
3534%     maskbase=get(handles.mask_test,'UserData');
3535% end
3536% % image or scalar processing programme set by user
3537% % if (get(handles.usr_fct,'Value')==1)
3538% %      usrfct=get(handles.usr_fct,'UserData');
3539% % else
3540% %      usrfct='';
3541% % end
3542% nburst=1; % nburst(1) =nbre of names in filename= nbre of bursts
3543% set(handles.text_display_1,'String',['image movie'])
3544% nbfield=length(filecell);
3545% if nbfield >1
3546% for ifile=2:nbfield
3547%     stopstate=get(handles.run0,'BusyAction');
3548%     if isequal(stopstate,'queue')% enable STOP command
3549%        pausetime=1.02-get(handles.speed,'Value');
3550%          pause(pausetime)
3551%          if isequal(get(handles.mask_test,'Value'),1)
3552%                 maskname=name_generator(maskbase,num1(ifile),1,'.png','png_series');
3553%             end
3554%             if isequal(AName{1},'image')
3555%                 A=read_image(cell2mat(filecell(ifile)),num1(ifile),maskname);% read the first image, num2 is the counter for avi files
3556%             else % read the first field from the netcdf file, imposing the pixel positions in the selected domain
3557%                  [A,time(ifile),dtr,rgx,rgy,vt_out,erread]=read_scalar(filecell{ifile},vel_type,scal_type,rangx0,rangy0,nxy,maskname);
3558%                 if erread==1;
3559%                     errordlg({['no spatial derivative in ' filecell{ifile}]; 'run patch first'}); return
3560%                 elseif erread==2;
3561%                     errordlg(['no field ' vel_type{1} ' in ' filecell{ifile}]); return
3562%                 elseif erread==3;
3563%                     errordlg(['scalar ' scal_type{1} ' not found in' filecell{ifile}]); return
3564%                 elseif erread==4;
3565%                     errordlg(['all points aligned in' filecell{ifile}]); return
3566%                 end
3567%             end
3568%           
3569%             % read the second image
3570%             if ~isempty(filecell_1)
3571%                 if isequal(scal_type{1},'image')
3572%                     A1=read_image(cell2mat(filecell_1(ifile)),num1(ifile),maskname);% read the second image, num2 is the counter for avi files
3573%                     Avalue_1=double(A1(indy,indx,:));
3574%                 else % read the second field from the netcdf file, imposing the pixel positions in the selected domain
3575%                     [Avalue_1,time1(ifile),dtr,rgx,rgy,vt_out,erread]=read_scalar(filecell_1{ifile},{vel_type1},{scal_type1},rangx0,rangy0,npxy,maskname,usrfct);
3576%                     if erread==1;
3577%                         errordlg({['no spatial derivative in ' filecell_1{ifile}]; 'run patch first'}); return
3578%                     elseif erread==2;
3579%                         errordlg(['no field ' vel_type1 ' in ' filecell_1{ifile}]); return
3580%                     elseif erread==3;
3581%                         errordlg(['scalar ' scal_type1 ' not found in' filecell_1{ifile}]); return
3582%                     elseif erread==4;
3583%                         errordlg(['all points aligned in' filecell_1{ifile}]); return
3584%                     end
3585%                 end
3586%                 time(ifile)=(time(ifile)+time1(ifile))/2;
3587%                 Avalue=Avalue-Avalue_1;
3588%             end
3589%         set(handles.abs_time,'String',time);
3590%         set(handles.field_counter,'String',num2str(num1(ifile)));
3591%         set(handles.a_input,'String',num2stra(num_a(ifile),nom_type));
3592%         C=reshape(A,nxy(1)*nxy(2),nxy(3));% reshape in a vector
3593%         [val,HIST]=hist_update(val,HIST,C,dC);
3594%         [h,Amin,Amax]=plot_image(hfig1,rangx0,rangy0,1,scal_type{1},auto_scale,min_input,max_input,poscolbar,A);
3595%         set(handles.min_input,'String',num2str(Amin));% select the minimum
3596%         set(handles.scale_input,'String',num2str(Amax));% select the minimum
3597%          if ~isequal(aviobj,[]),
3598% %              mov=getframe(hfig1);
3599%               mov=getframe(gcf);
3600%              aviobj=addframe(aviobj,mov);end
3601%          if (get(handles.zoom,'Value') == get(handles.zoom,'Max')),zoom on,end
3602%          set(handles.field_counter,'String',num2str(num1(ifile)))
3603% %     end
3604% end
3605% end
3606% end
3607% aviobj=close(aviobj);
3608%
3609% %plot global image histogram
3610%         HIST=HIST/(nbfield*nxy(1)*nxy(2));% normalized by the number of points
3611%         axes(hfig2) %in main window
3612%         if ndim==2
3613%             plot(val,HIST)
3614%         else
3615%             plot(val,HIST(:,1),'r',val,HIST(:,2),'g',val,HIST(:,3),'b')
3616%         end
3617%         residu=1-sum(HIST,1);
3618%         title(['histo, residu ' num2str(residu)])
3619%         grid on
3620%         axes(hfig3)
3621%         cla %clear the second histogram window
3622%         
3623
3624
3625%----------------------------------------------------------------------
3626% --- make a time series analysis
3627%----------------------------------------------------------------------
3628%INPUT:
3629%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3630%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
3631%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
3632%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
3633%OTHER INPUTS given by the structure Series
3634function GUI_input=time_series(num_i1,num_i2,num_j1,num_j2,Series)
3635
3636%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
3637if ~exist('num_i1','var')
3638    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
3639        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
3640        'RootFile';'on';... %root input file name ('on' by default)
3641        'FileExt';'on';... %input file extension ('on' by default)
3642        'NomType';'on';...%type of file indexing ('on' by default)
3643        'NbSlice';'on'; ...%nbre of slices ('off' by default)
3644        'VelTypeMenu';'two';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
3645        'FieldMenu';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
3646        'CoordType';'on';...%can use a transform function 'off' by default
3647        'GetObject';'on';...%can use projection object ,'off' by default
3648        %'GetMask';'on'...%can use mask option   ,'off' by default
3649        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
3650               ''};
3651    return %exit the function
3652end
3653
3654%------------------------------------------------------
3655hseries=guidata(Series.hseries);%handles in the GUI series
3656WaitbarPos=get(hseries.waitbar_frame,'Position'); %position of the waitbar frame
3657
3658%projection object
3659test_object=get(hseries.GetObject,'Value');
3660if test_object%isfield(Series,'sethandles')
3661    Series.ProjObject=read_set_object(Series.sethandles);
3662    answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
3663    if ~isequal(answeryes,'Yes')
3664        return
3665    end
3666else
3667    msgbox_uvmat('ERROR','a projection object is needed');
3668    return
3669end
3670
3671% root names
3672if iscell(Series.RootPath)
3673    RootPath=Series.RootPath;
3674    RootFile=Series.RootFile;
3675    SubDir=Series.SubDir;
3676    FileExt=Series.FileExt;
3677    NomType=Series.NomType;
3678else
3679    RootPath={Series.RootPath};
3680    RootFile={Series.RootFile};
3681    SubDir={Series.SubDir};
3682    FileExt={Series.FileExt};
3683    NomType={Series.NomType};
3684    num_i1={num_i1};
3685    num_i2={num_i2};
3686    num_j1={num_j1};
3687    num_j2={num_j2};
3688end
3689ext=FileExt{1};
3690form=imformats(ext([2:end]));%test valid Matlab image formats
3691testima=0;
3692if ~isempty(form)||isequal(lower(ext),'.avi')
3693    testima=1;
3694end
3695nbview=length(RootPath);%number of series (1 or 2)
3696nbfield=size(num_i1{1},1)*size(num_i1{1},2); %number of fields in the time series
3697
3698%Number of input series: this function  accepts only a single input file series
3699nbview=length(RootPath);
3700if nbview>2 
3701    RootPath=RootPath(1:2);
3702    set(hseries.RootPath,'String',RootPath)
3703    SubDir=SubDir(1:2);
3704    set(hseries.SubDir,'String',SubDir)
3705    RootFile=RootFile(1:2);
3706    set(hseries.RootFile,'String',RootFile)
3707    NomType=NomType(1:2);
3708    %set(hseries.NomType,'String',NomType)
3709    FileExt=FileExt(1:2);
3710    set(hseries.FileExt,'String',FileExt)
3711    nbview=2;
3712end
3713hhh=which('mmreader');
3714for iview=1:nbview
3715    test_movie(iview)=0;
3716    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
3717        if isequal(lower(FileExt{iview}),'.avi')
3718            MovieObject{iview}=mmreader(fullfile(RootPath{iview},[RootFile{iview} FileExt{iview}]));
3719            test_movie(iview)=1;
3720        end
3721    end
3722end
3723filebase{1}=fullfile(RootPath{1},RootFile{1});
3724% FileDisplay=fullfile(RootPath{1},SubDir{1},RootFile{1});
3725
3726% number of slices
3727NbSlice=str2num(get(hseries.NbSlice,'String'));
3728if isempty(NbSlice)
3729    NbSlice=1;
3730end
3731NbSlice_name=num2str(NbSlice);
3732
3733% Field and velocity type (the same for the two views)
3734if isfield(Series,'Field')
3735    FieldName=Series.Field;%the same set of fields for all views
3736else
3737    FieldName={''};
3738end
3739if isequal(FieldName,{'get_field...'})
3740    hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
3741    if length(hget_field)>1
3742        delete(hget_field(2:end))
3743    elseif isempty(hget_field)
3744       filename=...
3745               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});
3746       idetect(iview)=exist(filename,'file');
3747       hget_field=get_field(filename);
3748       return
3749    end
3750    hhget_field=guidata(hget_field);%handles of GUI elements in get_field
3751    SubField=read_var_names(hhget_field); %read the names of the variables to plot in the get_field GUI
3752    if isequal(get(hhget_field.menu_coord,'Visible'),'on')
3753        list_transform=get(hhget_field.menu_coord,'String');
3754        val_list=get(hhget_field.menu_coord,'Value');
3755        transform=list_transform{val_list};
3756    end
3757end
3758
3759%detect whether the two files are 'images' or 'netcdf'
3760testima=0;
3761testvol=0;
3762testcivx=0;
3763testnc=0;
3764FileExt=get(hseries.FileExt,'String');
3765for iview=1:nbview
3766     ext=FileExt{iview};
3767     form=imformats(ext([2:end]));
3768     if isequal(lower(ext),'.vol')
3769         testvol=testvol+1;
3770     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
3771         testima=testima+1;
3772     elseif isequal(ext,'.nc')
3773         testnc=testnc+1;
3774     end
3775end
3776if testvol
3777    msgbox_uvmat('ERROR','volume images not implemented yet')
3778    return
3779end
3780if testnc~=nbview && testima~=nbview && testvol~=nbview
3781    msgbox_uvmat('need a set of images or a set of netcdf files with the same fields as input','ERROR')
3782    return
3783end
3784if ~isequal(FieldName,{'get_field...'})
3785    testcivx=testnc;
3786end
3787
3788% Root name of output files (TO GENERALISE FOR TWO INPUT SERIES)
3789filebasesub=fullfile(RootPath{1},RootFile{1});
3790if NbSlice==1
3791    filebase_out=[filebasesub '_time'];
3792else
3793    filebase_out=[filebasesub '_' NbSlice_name 'mtim'];
3794    increment=num_i1{1}(2)-num_i1{1}(1);
3795    if ~isequal(increment,1) % if an increment is set
3796        answeryes=msgbox_uvmat('INPUT_Y-N',['will take time series in ' num2str(NbSlice) 'slices with increment = ' num2str(increment) '!'])
3797    else   
3798        answeryes=msgbox_uvmat('INPUT_Y-N',{['will take time series in ' num2str(NbSlice) ' slices'];['results stored as files ' filebase_out ' ...']});
3799    end
3800    if ~isequal(answeryes,'Yes')
3801        return
3802    end
3803end
3804VelType_str=get(hseries.VelTypeMenu,'String');
3805VelType_val=get(hseries.VelTypeMenu,'Value');
3806VelType{1}=VelType_str{VelType_val};
3807if nbview==2
3808    VelType_str=get(hseries.VelTypeMenu_1,'String');
3809    VelType_val=get(hseries.VelTypeMenu_1,'Value');
3810    VelType{2}=VelType_str{VelType_val};
3811end
3812
3813%Calibration data and timing: read the ImaDoc files
3814mode=''; %default
3815timecell={};
3816XmlData={};
3817itime=0;
3818NbSlice_calib={};
3819for iview=1:nbview%Loop on views
3820    XmlData{iview}=[];%default
3821    filebase{iview}=fullfile(RootPath{iview},RootFile{iview});
3822    if exist([filebase{iview} '.xml'],'file')
3823        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
3824        if isfield(XmlData{iview},'Time')
3825            itime=itime+1;
3826            timecell{itime}=XmlData{iview}.Time;
3827        end
3828        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
3829            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
3830            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
3831                msgbox_uvmat('WARNING','inconsistent number of Z indices for the field series');
3832            end
3833        end
3834    elseif exist([filebase{iview} '.civ'],'file')
3835        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
3836        itime=itime+1;
3837        timecell{itime}=time;
3838        XmlData{iview}.Time=time;
3839        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
3840        GeometryCalib.Tx=0;
3841        GeometryCalib.Ty=0;
3842        GeometryCalib.Tz=1;
3843        GeometryCalib.dpx=1;
3844        GeometryCalib.dpy=1;
3845        GeometryCalib.sx=1;
3846        GeometryCalib.Cx=0;
3847        GeometryCalib.Cy=0;
3848        GeometryCalib.f=1;
3849        GeometryCalib.kappa1=0;
3850        GeometryCalib.CoordUnit='cm';
3851        XmlData{iview}.GeometryCalib=GeometryCalib;
3852        if error==1
3853            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
3854        end
3855    end
3856end
3857
3858%check coincidence in time
3859multitime=0;
3860if length(timecell)==0
3861    time=[];
3862elseif length(timecell)==1
3863    time=timecell{1};
3864elseif length(timecell)>1
3865    multitime=1;
3866    for icell=1:length(timecell)
3867        if ~isequal(size(timecell{icell}),size(timecell{1}))
3868            warndlg_uvmat('inconsistent time array dimensions in ImaDoc fields, the time for the first series is used','WARNING')
3869            time=timecell{1};
3870            multitime=0;
3871            break
3872        end
3873    end
3874end
3875if multitime
3876    for icell=1:length(timecell)
3877        time(icell,:,:)=timecell{icell};
3878    end
3879    diff_time=max(max(diff(time)));
3880    if diff_time>0
3881        warndlg_uvmat(['times of series differ by more than ' num2str(diff_time)],'WARNING')
3882    end   
3883end
3884if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
3885    time=[];
3886end
3887
3888% image or scalar processing programme set by user
3889Coord_menu=get(hseries.CoordType,'String');
3890menu_val=get(hseries.CoordType,'Value');
3891usrfct=Coord_menu{menu_val};
3892testfct=~isequal(usrfct,'');
3893
3894% to update:
3895VelType_str=get(hseries.VelTypeMenu,'String');
3896VelType_val=get(hseries.VelTypeMenu,'Value');
3897VelType{1}=VelType_str{VelType_val};
3898if nbview==2
3899    VelType_str=get(hseries.VelTypeMenu_1,'String');
3900    VelType_val=get(hseries.VelTypeMenu_1,'Value');
3901    VelType{2}=VelType_str{VelType_val};
3902end
3903
3904%LOOP ON SLICES
3905for i_slice=1:NbSlice
3906     dt=[];
3907     nbmissing=0; %number of undetected files
3908     nbfiles=0;
3909    %%%%%%%%%%%%%%%%%%%%%%%%%%%%LOOP ON FIELDS IN  A SLICE
3910    for ifile=i_slice:NbSlice:nbfield 
3911        stopstate=get(hseries.RUN,'BusyAction');
3912        if isequal(stopstate,'queue')% enable STOP command
3913             update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
3914             for iview=1:nbview
3915                filename=...
3916                           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});
3917                idetect(iview)=exist(filename,'file');
3918                Data{iview}=[]; %default     
3919                if testima                 
3920                    Data{iview}.ListVarName={'A'};
3921                    Data{iview}.AName='image';
3922                    if test_movie(iview)
3923                        A=read(MovieObject{iview},num_i1{iview}(ifile));
3924                    else
3925                        A=double(read_image(filename,NomType{iview},num_i1{iview}(ifile)));% read the image, num2 is the counter for avi files
3926                    end
3927                    Data{iview}.ListVarName={'coord_y','coord_x','A'}; %
3928                    npy=size(A,1);
3929                    npx=size(A,2);
3930                    nbcolor=size(A,3);
3931                    if nbcolor==3
3932%                         Data{iview}.ListDimName={'coord_y','coord_x','rgb'};
3933%                         Data{iview}.DimValue=[npy npx 3];
3934%                         Data{iview}.VarDimIndex={[1 2 3]};
3935                           Data{iview}.VarDimName={'coord_y','coord_x',{'coord_y','coord_x','rgb'}};
3936                    else
3937%                         Data{iview}.ListDimName={'coord_y','coord_x'}; 
3938%                         Data{iview}.DimValue=[npy npx];
3939%                         Data{iview}.VarDimIndex={[1 2]};
3940%                         Data{iview}.VarAttribute{1}.Coord_1=[npy-0.5 0.5];
3941%                         Data{iview}.VarAttribute{1}.Coord_2=[0.5 npx-0.5];
3942                         Data{iview}.VarDimName={'coord_y','coord_x',{'coord_y','coord_x'}};
3943                    end 
3944                    Data{iview}.coord_y=[npy-0.5 0.5];
3945                    Data{iview}.coord_x=[0.5 npx-0.5];
3946                    Data{iview}.A=A;
3947                    Data{iview}.CoordType='px';
3948                elseif testcivx
3949                    [Data{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
3950                else
3951                    [Data{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
3952                    Data{iview}.VarAttribute=SubField.VarAttribute;
3953                end
3954                if ~isempty(NbSlice_calib)  % z index
3955                    Data{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
3956                end
3957             end
3958            % geometry transform or other user defined transform
3959            if ~isequal(Series.CoordType,'')           
3960                if nbview==2
3961                    [Data{1},Data{2}]=feval(Series.CoordType,Data{1},XmlData{1},Data{2},XmlData{2});
3962                    if isempty(Data{2})
3963                        Data(2)=[];
3964                    end
3965                else
3966                    Data{1}=feval(Series.CoordType,Data{1},XmlData{1});
3967                end
3968            end
3969            if testcivx
3970                    Data{iview}=calc_field(FieldName,Data{iview});%calculate field (vort..)
3971            end
3972            if length(Data)==2
3973                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
3974                if ~isempty(errormsg)
3975                    msgbox_uvmat('ERROR',['error in time_series/sub_field:' errormsg])
3976                    return
3977                end
3978            else
3979                Field=Data{1};
3980            end
3981            if isfield(Series,'ProjObject')
3982                [Field,errormsg]=proj_field(Field,Series.ProjObject);
3983                if ~isempty(errormsg)
3984                    msgbox_uvmat('ERROR',['error in time_series/proj_field:' errormsg])
3985                    return
3986                end
3987            end
3988            if min(idetect)>=1% the input file(s) have been detected         
3989                nbfiles=nbfiles+1;
3990                if nbfiles==1 %first field: initiate the time series
3991                    RecordData=Field;%default
3992                    RecordData.NbDim=Field.NbDim+1; %add the time dimension for plots         
3993                    nbvar=length(Field.ListVarName);
3994                    if nbvar==0
3995                        msgbox_uvmat('ERROR','no input variable selected in get_field')
3996                        return
3997                    end
3998                    testsum=2*ones(1,nbvar);%initiate flag for action on each variable
3999                    indexfalse=0;
4000                    CoordName={};
4001                    indexremove=[];
4002                    if isfield(Field,'VarAttribute') % look for coordinate and flag variables   
4003                        for ivar=1:nbvar
4004                            if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
4005                                var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
4006                                if isequal(var_role,'errorflag')
4007                                    msgbox_uvmat('ERROR','do not handle error flags in time series')
4008                                    return                                               
4009                                end
4010                                if isequal(var_role,'warnflag')                       
4011                                    testsum(ivar)=0;  % not recorded variable
4012                                    eval(['RecordData=rmfield(RecordData,''' Field.ListVarName{ivar} ''');']);%remove variable
4013                                end                 
4014                                if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|...
4015                                    isequal(var_role,'coord_z')|isequal(var_role,'coord')
4016                                    testsum(ivar)=1; %constant coordinates, record without time evolution
4017                                end
4018                                % check whether the variable ivar is a dimension variable
4019                                %index=Field.VarDimIndex{ivar};%dimension indices of the variable #ivar
4020                                DimCell=Field.VarDimName{ivar};
4021                                if ischar(DimCell)
4022                                    DimCell={DimCell};
4023                                end
4024                                if numel(DimCell)==1 && isequal(Field.ListVarName{ivar},DimCell)%TODO generalise with attribute
4025                               % if length(Field.ListDimName)>=index & isequal(Field.ListVarName{ivar},Field.ListDimName{index})%detect dimension variables
4026                                   testsum(ivar)=1;
4027                                end
4028                            end
4029                        end
4030                    end
4031                    for ivar=1:nbvar
4032                        if testsum(ivar)==2                     
4033                            eval(['RecordData.' Field.ListVarName{ivar} '=[];'])
4034                        end
4035                    end
4036                 %   RecordData.ListDimName=[{'Time'} RecordData.ListDimName];%name of dimension
4037                    RecordData.ListVarName=[{'Time'} RecordData.ListVarName];
4038                end
4039                for ivar=1:length(Field.ListVarName)
4040                    VarName=Field.ListVarName{ivar};
4041                    eval(['VarVal=Field.' VarName ';']);
4042                    if testsum(ivar)==2% test for recorded variable
4043                        eval(['VarVal=Field.' VarName ';']);
4044                        if isequal(Series.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
4045                            if isempty(VarVal)
4046                                msgbox_uvmat('ERROR',['empty result at frame index ' num2str(num_i1{iview}(ifile))])
4047                                return                             
4048                            end
4049                            VarVal=mean(VarVal,1);
4050                        end
4051                        VarVal=shiftdim(VarVal,-1); %shift dimension
4052                        eval(['RecordData.' VarName '=cat(1,RecordData.' VarName ',VarVal);']);%concanete the current field to the time series                     
4053                    elseif testsum(ivar)==1% variable representing fixed coordinates
4054                        eval(['VarInit=RecordData.' VarName ';']);
4055                        if ~isequal(VarVal,VarInit)
4056                            msgbox_uvmat('ERROR',['time series requires constant coordinates ' VarName])
4057                            return
4058                        end
4059                    end                 
4060                end
4061                % time:
4062                if isempty(time)% time read in ncfiles
4063                   if isfield(Field,'Time')
4064                       RecordData.Time(nbfiles,1)=Field.Time;
4065                   else
4066                       RecordData.Time(nbfiles,1)=nbfiles;%default
4067                   end
4068                else % time from ImaDoc prevails
4069                    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;
4070                end
4071            else
4072                nbmissing=nbmissing+1;
4073            end
4074        end
4075    end
4076    %remove time for global attributes if exists
4077    for iattr=1:numel(RecordData.ListGlobalAttribute)
4078        if strcmp(RecordData.ListGlobalAttribute{iattr},'Time')
4079            RecordData.ListGlobalAttribute(iattr)=[];
4080            break
4081        end
4082    end
4083    for ivar=1:numel(RecordData.ListVarName)
4084        VarName=RecordData.ListVarName{ivar};
4085        eval(['RecordData.' VarName '=squeeze(RecordData.' VarName ');']) %remove singletons
4086    end
4087        % add time dimension and update VarDimIndex:
4088   %if ~isequal(Series.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
4089        for ivar=1:length(Field.ListVarName)
4090%              vardimindex=Field.VarDimIndex{ivar};% array of dimension indices for variable VarIndex(ivar)
4091             DimCell=Field.VarDimName(ivar);
4092             if testsum(ivar)==2%variable used as time series
4093%                  RecordData.VarDimIndex{ivar}=[1 vardimindex+1];
4094                  RecordData.VarDimName{ivar}=[{'Time'} DimCell];
4095             elseif testsum(ivar)==1
4096%                  RecordData.VarDimIndex{ivar}=[vardimindex+1];
4097                 RecordData.VarDimName{ivar}=DimCell;
4098             end
4099        end
4100   % end
4101    indexremove=find(~testsum);
4102    if ~isempty(indexremove)
4103        RecordData.ListVarName(1+indexremove)=[];
4104        RecordData.VarDimName(indexremove)=[];
4105        if isfield(RecordData,'Role')&~isempty(RecordData.Role{1})%generaliser aus autres attributs
4106            RecordData.Role(1+indexremove)=[];
4107        end
4108    end
4109    %RecordData.VarDimIndex=[{[1]} RecordData.VarDimIndex]; %time dimension
4110    %shift variable attributes
4111    if isfield(RecordData,'VarAttribute')
4112        RecordData.VarAttribute=[{[]} RecordData.VarAttribute];
4113    end
4114    RecordData.VarDimName=[{'Time'} RecordData.VarDimName];
4115    RecordData.Action=Series.Action;%name of the processing programme
4116    %name of result file
4117    [filemean]=...
4118               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});
4119    RecordData
4120     RecordData.VarDimName{1}
4121     RecordData.VarDimName{2}
4122      RecordData.VarDimName{3}
4123    errormsg=struct2nc(filemean,RecordData); %save result file
4124    if isempty(errormsg)
4125        display([filemean ' written'])
4126    else
4127        msgbox_uvmat('ERROR',['error in Series/struct2nc' errormsg])
4128    end
4129end
4130figure
4131haxes=axes;
4132
4133plot_field(RecordData,haxes)
4134hget_field=findobj(allchild(0),'name','get_field');
4135if ~isempty(hget_field)
4136    delete(hget_field)
4137end
4138get_field(filemean,RecordData)
4139   
4140%-----------------------------------------------------------------------
4141% --- Executes on selection change in CoordType.
4142function CoordType_Callback(hObject, eventdata, handles)
4143menu_str=get(handles.CoordType,'String');
4144ind_coord=get(handles.CoordType,'Value');
4145coord_option=menu_str{ind_coord};
4146if isequal(coord_option,'more...');
4147    fct_name='';
4148    if exist('./TMP/current_usr_fct.mat','file')% if a file is found
4149        h=load('./TMP/current_usr_fct.mat');
4150        if isfield(h,'fct_name');
4151            fct_name=h.fct_name;
4152        end
4153    end
4154    prompt = {'Enter the name of the transform function'};
4155    dlg_title = 'user defined transform';
4156    num_lines= 1;
4157    [FileName, PathName, filterindex] = uigetfile( ...
4158       {'*.m', ' (*.m)';
4159        '*.m',  '.m files '; ...
4160        '*.*', 'All Files (*.*)'}, ...
4161        'Pick a file', fct_name);
4162    fct_name=fullfile(PathName,FileName);
4163    addpath(PathName);%add the path to the selected fct
4164    [errormsg,date_str]=check_functions;%check whether new functions can oversed the uvmat package A UTILISER
4165    if ~exist(fct_name,'file')
4166           warndlg(['image procesing fct ' fct_name ' not found'])
4167    else
4168        transform=FileName(1:end-2);%
4169        update_menu(handles.CoordType,transform)%add the selected fct to the menu
4170  %      set(handles.mouse_coord,'String',menu([1:end-1])')%update the mouse coord menu
4171      %save ('./TMP/current_usr_fct.mat','fct_name');
4172    end   
4173end
4174ind_coord=get(handles.CoordType,'Value');   
4175
4176%---------------------------------------------------------------------
4177% --- Executes on selection change in ProjObject.
4178function ProjObject_Callback(hObject, eventdata, handles)
4179
4180list_object=get(handles.ProjObject,'String');
4181index=get(handles.ProjObject,'Value');
4182hseries=get(handles.ProjObject,'Parent');
4183SeriesData=get(hseries,'UserData');
4184Obj=SeriesData.ProjObject{index};
4185[SeriesData.hset_object,SeriesData.sethandles]=set_object(SeriesData.ProjObject{index});
4186set(hseries,'UserData',SeriesData);
4187
4188%-------------------------------------------------------------
4189%generates a series of file names with reference numbers between range1 and
4190%range2 with increment incr. The reference number num_ref is the image number at the middle of the
4191%image pair. The set of first numbers num1 of the image pairs is also
4192%given as output
4193%------------------------------------------------------
4194function [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)
4195[Path,Name]=fileparts(filebase);
4196filebasesub=fullfile(Path,subdir,Name);
4197filecell={};%default
4198num_i1=[];
4199num_i2=[];
4200num_j1=[];
4201num_j2=[];
4202ind0_i=first_i:incr_i:last_i;
4203nbcolumn=length(ind0_i);
4204ind0_j=first_j:incr_j:last_j;
4205nbline=length(ind0_j);
4206if isequal(mode,'#_ab')
4207    dirpair=dir([filebasesub '*_*.nc']);
4208elseif isequal(mode,'bursts')|isequal(mode,'series(Dj)') 
4209    dirpair=dir([filebasesub '_*_*-*.nc']);
4210elseif isequal(mode,'series(Di)')
4211    dirpair=dir([filebasesub '_*-*_*.nc']);
4212else
4213    errordlg('option *|* not yet implemented')
4214    return
4215end
4216if isempty(dirpair)
4217        errordlg('no pair detected in the selected range')
4218        return
4219end
4220    %ind0_i=first_i:incr_i:last_i;
4221    %nbcolumn=length(ind0_i);
4222    %dirpair=dir([filebasesub '_*_*-*.nc']);
4223if isequal(mode,'bursts')|isequal(mode,'#_ab')
4224    icount=0;
4225    for ifile=1:length(dirpair)
4226        [RootPath,RootFile,str_1,str_2,str_a,str_b,ext,nom_type]=name2display(dirpair(ifile).name);
4227       
4228%         if isempty(str2num(str_1))
4229%             dirpair(ifile).name
4230%         end
4231        num1_r=str2num(str_1);
4232        if isequal(RootFile,Name) & ~isempty(num1_r)   
4233            num_i1(ifile)=num1_r;
4234            num_a(ifile)=stra2num(str_a);
4235            num_b(ifile)=stra2num(str_b);
4236%             icount=icount+1;
4237        end     
4238    end
4239    length(dirpair)
4240%     num_j=floor((num_a+num_b)/2); %list of reference indices of the detected files
4241    test_range= (num_i1 >=first_i)&(num_i1<= last_i);% =1 when both numbers are in the range
4242    ind_i=((num_i1-first_i)/incr_i)+1;%indices i in the list of prescribed file indices
4243    select=find(test_range &(floor(ind_i)==ind_i));%selected indices of num_i1 in the file directory
4244    ind_i=ind_i(select);%set of selected indices ind_i
4245    [ind_i,indsort]=sort(ind_i);%sorted list of ind_i
4246    select=select(indsort);
4247    num_i1=num_i1(select);
4248    num_a=num_a(select);
4249    num_b=num_b(select);
4250    dirpair=dirpair(select);
4251    [ind_remove]=find_pairs(dirpair,ind_i,nbcolumn);
4252    ind_i(ind_remove)=[];
4253    num_a(ind_remove)=[];
4254    num_b(ind_remove)=[];
4255    num_j1=zeros(1,nbcolumn);%default
4256    num_j2=num_j1;
4257    num_j1(ind_i)=num_a;
4258    num_j2(ind_i)=num_b;
4259    num_i1=first_i:incr_i:last_i;
4260    num_i2=num_i1;
4261    nbmissing=nbcolumn-length(ind_i);
4262
4263elseif isequal(mode,'series(Di)')
4264    %ind0_i=first_i:incr_i:last_i;
4265    %nbcolumn=length(ind0_i);
4266    %ind0_j=first_j:incr_j:last_j;
4267    %nbline=length(ind0_j);
4268    %dirpair=dir([filebasesub '_*-*_*.nc']);
4269    for ifile=1:length(dirpair)
4270        [RootPath,RootFile,str_1,str_2,str_a,str_b,ext,nom_type]=name2display(dirpair(ifile).name);
4271        num_i1_r(ifile)=str2num(str_1);
4272        num_i2_r(ifile)=str2num(str_2);
4273        num_j(ifile)=str2num(str_a);
4274    end
4275    num_i=floor((num_i1_r+num_i2_r)/2); %list of reference indices of the detected files
4276    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
4277    ind_i=((num_i-first_i)/incr_i)+1;%indices i and j in the list of prescribed file indices
4278    ind_j=((num_j-first_j)/incr_j)+1;
4279    ind_ij=ind_j+nbline*(ind_i-1);%indices in the reshhaped series of prescribed file indices
4280    select=find(test_range &(floor(ind_i)==ind_i)&(floor(ind_j)==ind_j));%selected indices in the file directory
4281    ind_ij=ind_ij(select);%set of selected indices ind_ij
4282    [ind_ij,indsort]=sort(ind_ij);%sorted list of ind_ij
4283    select=select(indsort);
4284    num_i1_r=num_i1_r(select);
4285    num_i2_r=num_i2_r(select);
4286%     num_j=num_j(select);
4287    dirpair=dirpair(select);
4288    [ind_remove]=find_pairs(dirpair,ind_ij,nbcolumn*nbline) ;
4289    ind_ij(ind_remove)=[];
4290    num_i1_r(ind_remove)=[];
4291    num_i2_r(ind_remove)=[];
4292    num_i1=zeros(1,nbline*nbcolumn);%default
4293    num_i2=num_i1;
4294    num_i1(ind_ij)=num_i1_r;
4295    num_j2(ind_ij)=num_i2_r;
4296    num_i1=reshape(num_i1,nbline,nbcolumn);
4297    num_i2=reshape(num_i2,nbline,nbcolumn);
4298    num_j1=meshgrid(ind0_i,ind0_j);
4299    num_j2=num_j1;
4300    nbmissing=nbline*nbcolumn-length(ind_ij);
4301elseif isequal(mode,'series(Dj)')
4302 %   ind0_i=first_i:incr_i:last_i;
4303 %   nbcolumn=length(ind0_i);
4304 %   ind0_j=first_j:incr_j:last_j;
4305  %  nbline=length(ind0_j);
4306  %  dirpair=dir([filebasesub '_*_*-*.nc']);
4307    for ifile=1:length(dirpair)
4308        [RootPath,RootFile,str_1,str_2,str_a,str_b,ext,nom_type]=name2display(dirpair(ifile).name);
4309        num_i(ifile)=str2num(str_1);
4310        num_a(ifile)=str2num(str_a);
4311        num_b(ifile)=str2num(str_b);
4312    end
4313    num_j=floor((num_a+num_b)/2); %list of reference indices of the detected files
4314    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
4315    ind_i=((num_i-first_i)/incr_i)+1;%indices i and j in the list of prescribed file indices
4316    ind_j=((num_j-first_j)/incr_j)+1;
4317    ind_ij=ind_j+nbline*(ind_i-1);%indices in the reshhaped series of prescribed file indices
4318    select=find(test_range &(floor(ind_i)==ind_i)&(floor(ind_j)==ind_j));%selected indices in the file directory
4319    ind_ij=ind_ij(select);%set of selected indices ind_ij
4320    [ind_ij,indsort]=sort(ind_ij);%sorted list of ind_ij
4321    select=select(indsort);
4322    num_i=num_i(select);
4323    num_a=num_a(select);
4324    num_b=num_b(select);
4325    dirpair=dirpair(select);
4326    [ind_remove]=find_pairs(dirpair,ind_ij,nbcolumn*nbline) ;
4327    ind_ij(ind_remove)=[];
4328    num_a(ind_remove)=[];
4329    num_b(ind_remove)=[];
4330    num_j1=zeros(1,nbline*nbcolumn);%default
4331    num_j2=num_j1;
4332    num_j1(ind_ij)=num_a;
4333    num_j2(ind_ij)=num_b;
4334    num_j1=reshape(num_j1,nbline,nbcolumn);
4335    num_j2=reshape(num_j2,nbline,nbcolumn);
4336    num_i1=meshgrid(ind0_i,ind0_j);
4337    num_i2=num_i1;
4338    nbmissing=nbline*nbcolumn-length(ind_ij);
4339%     for i=1:length(indsel);%A SUPPRIMER ULTERIEUREMENT
4340%         if indsel(i)==0
4341%             filecell{i}='';
4342%         else
4343%             Name=dirpair(indsel(i)).name;
4344%             filecell{i}=fullfile(Path,subdir,Name);
4345%         end
4346%     end
4347%else
4348%    errordlg('option *|* not yet implemented')
4349%    return
4350end
4351
4352%%%%%%%%%%%%%
4353function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
4354
4355        indsel=ind_i;
4356        indiff=diff(ind_i); %test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
4357        indiff=[1 indiff last_i-ind_i(end)+1];%for testing gaps with the imposed bounds
4358        if ~isempty(indiff)
4359            indiff2=diff(indiff);
4360            indiffp=[indiff2 1];
4361            indiffm=[1 indiff2];
4362            ind_multi_m=find((indiff==0)&(indiffm<0))-1;%indices of first members of multiplets
4363            ind_multi_p=find((indiff==0)&(indiffp>0));%indices of last members of multiplets
4364                %for each multiplet, select the most recent file
4365            ind_remove=[];
4366            for i=1:length(ind_multi_m)
4367                ind_pairs=ind_multi_m(i):ind_multi_p(i);
4368                for imulti=1:length(ind_pairs)
4369                    datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date);%dates of creation
4370                end
4371                [datenew,indsort2]=sort(datepair); %sort the multiplet by creation date
4372                ind_s=indsort2(1:end-1);%
4373                ind_remove=[ind_remove ind_pairs(ind_s)];%remove these indices, leave the last one
4374            end
4375        end
4376
4377%--------------------------------------------------------
4378
4379 
4380%-----------------------------------------------------------
4381% find the times corresponding to the first and last indices of a series
4382%
4383function displ_time(handles,times)
4384hseries=get(handles.last_i,'parent');
4385SeriesData=get(hseries,'UserData');%
4386first_i=str2num(get(handles.first_i,'String'));
4387first_j=str2num(get(handles.first_j,'String'));
4388last_i=str2num(get(handles.last_i,'String'));
4389last_j=str2num(get(handles.last_j,'String'));
4390% index_civ=get(handles.list_pair_civ,'Value');
4391% NomType=get(handles.NomType,'String');
4392NomType=SeriesData.NomType;
4393mode_list=get(handles.mode,'String');
4394index_mode=get(handles.mode,'Value');
4395mode=mode_list{index_mode};
4396% ind_shift=0;%default
4397
4398time_first=[];
4399time_last=[];
4400if ~isfield(SeriesData,'Time')
4401    SeriesData.Time{1}=[];
4402end
4403for iview=1:length(NomType)
4404    time_first_cell{iview}='?';
4405    time_last_cell{iview}='?';%default
4406    time=SeriesData.Time{iview};
4407    if isequal(NomType{iview},'_i1-i2_j')|isequal(NomType{iview},'_i_j1-j2')|isequal(NomType{iview},'#_ab')|isequal(NomType{iview},'_i1-i2')
4408        if isfield(SeriesData,'displ_num')& ~isempty(SeriesData.displ_num)
4409            ind_shift=SeriesData.displ_num(iview,:);
4410            if isequal(mode,'bursts')
4411                first_j=0;
4412                last_j=0;
4413            end
4414            first_i1=first_i +ind_shift(3);
4415            first_i2 =first_i +ind_shift(4);
4416            first_j1 =first_j +ind_shift(1);
4417            first_j2 =first_j +ind_shift(2);
4418            last_i1=last_i +ind_shift(3);
4419            last_i2 =last_i +ind_shift(4);   
4420            last_j1 =last_j +ind_shift(1);
4421            last_j2 =last_j +ind_shift(2);
4422            siz=size(SeriesData.Time{1});
4423            if siz(1)>=last_i2 & siz(2)>=last_j2
4424                time_first=(time(first_i1,first_j1)+time(first_i2,first_j2))/2;
4425                time_last=(time(last_i1,last_j1)+time(last_i2,last_j2))/2;
4426            else%read the time in the nc files
4427                RootPath=get(handles.RootPath,'String');
4428                RootFile=get(handles.RootFile,'String');
4429                SubDir=get(handles.SubDir,'String');
4430                %VelType=get(handles.VelType,'String');
4431                VelType_str=get(handles.VelTypeMenu,'String');
4432                VelType_val=get(handles.VelTypeMenu,'Value');
4433                VelType=VelType_str{VelType_val};
4434                filebase=fullfile(RootPath{1},RootFile{1});
4435                [filefirst]=name_generator(filebase,first_i1,first_j1,'.nc',NomType{iview},1,first_i2,first_j2,SubDir{iview});
4436                if  exist(filefirst,'file')
4437                    Attrib=nc2struct(filefirst,[]);
4438                    if isfield(Attrib,'Time')
4439                        time_first=Attrib.Time;
4440                    else
4441                        if isfield(Attrib,'absolut_time_T0')
4442                            time_first=Attrib.absolut_time_T0;
4443                        end
4444                        if isfield(Attrib,'absolut_time_T0_2')&~(isequal(VelType,'civ1')|isequal(VelType,'interp1')|isequal(VelType,'filter1'))
4445                            time_first=Attrib.absolut_time_T0_2;
4446                        end
4447                    end
4448                end
4449                [filelast]=name_generator(filebase,last_i1,last_j1,'.nc',NomType{iview},1,last_i2,last_j2,SubDir{iview});
4450                if exist(filelast,'file')
4451                   Attrib=nc2struct(filelast,[]);
4452                    if isfield(Attrib,'Time')
4453                        time_last=Attrib.Time;
4454                    else
4455                        if isfield(Attrib,'absolut_time_T0')
4456                            time_last=Attrib.absolut_time_T0;
4457                        end
4458                        if isfield(Attrib,'absolut_time_T0_2')&~(isequal(VelType,'civ1')|isequal(VelType,'interp1')|isequal(VelType,'filter1'))
4459                            time_last=Attrib.absolut_time_T0_2;
4460                        end
4461                    end
4462                end
4463            end
4464        end
4465    else
4466        siz=size(times);
4467        if siz(1)>=last_i & siz(2)>=last_j
4468            time_first=times(first_i,first_j);
4469            time_last=times(last_i,last_j);
4470        end
4471    end
4472    time_first_cell{iview}=num2str(time_first,4);
4473    time_last_cell{iview}=num2str(time_last,4);
4474end
4475set(handles.time_first,'Value',1)
4476set(handles.time_last,'Value',1)
4477set(handles.time_first,'String',time_first_cell);
4478set(handles.time_last,'String',time_last_cell);
4479
4480%--------------------------------------------------------------------
4481% --- Executes on selection change in VelTypeMenu.
4482function VelTypeMenu_Callback(hObject, eventdata, handles)
4483% VelTypeList=get(handles.VelTypeMenu,'String');
4484% VelTypeIndex=get(handles.VelTypeMenu,'Value');
4485% VelTypeCell=get(handles.VelType,'String');
4486% VelTypeCell{1}=VelTypeList{VelTypeIndex};
4487% set(handles.VelType,'String',VelTypeCell)
4488
4489
4490%--------------------------------------------------------------------
4491% --- Executes on button press in GetObject.
4492function GetObject_Callback(hObject, eventdata, handles)
4493hseries=get(handles.GetObject,'parent');
4494SeriesData=get(hseries,'UserData');
4495value=get(handles.GetObject,'Value');
4496if value
4497     set(handles.GetObject,'BackgroundColor',[1 1 0])%put unactivated buttons to yellow
4498     DataInit.ParentButton=handles.GetObject;
4499     hset_object=findobj(allchild(0),'Name','set_object');%find the set_object interface handle
4500     if ishandle(hset_object)
4501         [SeriesData.hset_object,SeriesData.sethandles]=set_object(DataInit); %open the set_object interface
4502     else
4503         DataInit.TITLE='POINTS';%default option
4504         [SeriesData.hset_object,SeriesData.sethandles]=set_object(DataInit); %open the set_object interface
4505     end
4506else
4507    set(handles.GetObject,'BackgroundColor',[0 1 0])%put activated buttons to green
4508    if isfield(SeriesData,'hset_object')&& ishandle(SeriesData.hset_object)
4509        close(SeriesData.hset_object)
4510    end
4511end
4512set(hseries,'UserData',SeriesData)
4513
4514%--------------------------------------------------------------
4515function GetMask_Callback(hObject, eventdata, handles)
4516value=get(handles.GetMask,'Value');
4517if value
4518    errordlg('not implemented yet')
4519end
4520%--------------------------------------------------------------
4521
4522%--------------------------------------------------------------------------
4523%'uv_ncbrowser': interactively calls the netcdf file browser 'get_field.m'
4524function ncbrowser_uvmat(hObject, eventdata)
4525     bla=get(gcbo,'String');
4526     ind=get(gcbo,'Value');
4527     filename=cell2mat(bla(ind));
4528      blank=find(filename==' ');
4529      filename=filename(1:blank-1);
4530     get_field(filename)
4531
4532
4533
4534% --------------------------------------------------------------------
4535function MenuHelp_Callback(hObject, eventdata, handles)
4536
4537path_to_uvmat=which ('uvmat');% check the path of uvmat
4538pathelp=fileparts(path_to_uvmat);
4539helpfile=fullfile(pathelp,'UVMAT_DOC','uvmat_doc.html');
4540if isempty(dir(helpfile)), errordlg('Please put the help file uvmat_doc.html in the  directory UVMAT/UVMAT_DOC')
4541else
4542web([helpfile '#series'])   
4543end
4544
4545
4546
4547
4548
4549
Note: See TracBrowser for help on using the repository browser.