source: trunk/src/uvmat.m @ 503

Last change on this file since 503 was 503, checked in by sommeria, 12 years ago

datatree_browse introduced (still work to do)
get_field revised to introduce new transform fcts, like FFT

File size: 207.1 KB
Line 
1%'uvmat': function associated with the GUI 'uvmat.fig' for images and data field visualization
2%------------------------------------------------------------------------
3% function huvmat=uvmat(input)
4%
5%OUTPUT
6% huvmat=current handles of the GUI uvmat.fig
7%%
8%
9%INPUT:
10% input: input file name (if character chain), or input image matrix to
11% visualize, or Matlab structure representing  netcdf fields (with fields
12% ListVarName....)
13%
14%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
15%  Copyright Joel Sommeria,  2008, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
16%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
17%     This open is part of the toolbox UVMAT.
18%
19%     UVMAT is free software; you can redistribute it and/or modify
20%     it under the terms of the GNU General Public License as published by
21%     the Free Software Foundation; either version 2 of the License, or
22%     (at your option) any later version.
23%
24%     UVMAT is distributed in the hope that it will be useful,
25%     but WITHOUT ANY WARRANTY; without even the implied warranty of
26%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
28%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
29%
30% Information stored on the interface:
31%    'Strings' of all edit boxes and menus: get(handles.Tag,'String')
32%    'Values' of all menus and toggle buttons: get(handles.Tag,'Value')
33%     Matlab structure called UvData stored as 'UserData' of the figure uvmat.fig,(can be obtained by right mouse click on the interface).
34%          It contains the following fields:
35%     - Fixed specifiacation of plotting figures and axes (defined bu uvmat_OpeningFcn)
36%          .PosColorbar: [0.8210 0.4710 0.0190 0.4450]; specified position of the colorbar on figures
37%     - Information read in the documentation open of a series (activated by RootPath_Callback) :
38%          .XmlData, with fields:
39%               .Time: matrix of times of the images with index i and j
40%               .GeometryCalib: [1x1 struct]
41%     - Information defined from the interface:
42%           .NewSeries: =1 when the first view of a new field series is displayed, else 0
43%           .FileName:(char string)
44%           .FieldName: (char string) main field selected('image', 'velocity'...)
45%           .CName: (char string)name of the scalar used for vector colors
46%          .MovieObject{1}: movie object representing an input movie
47%          .MovieObject{2}: idem for a second input series (_1)
48%          .FileName_1 : last second input file name (to deal with a constant second input without reading again the file)
49%          .ZMin, .ZMax: range of the z coordinate
50%..... to complement
51%     - Information on  projection objects
52%           .Object: {[1x1 struct]}
53%           .CurrentObjectIndex: index of the projection object .Object currently selected for editing
54%     -Information on the current field (Field{i})
55%            .Txt : text information to display (e.g. error message)
56%            .NbDim: number of dimensions (=0 by default)
57%            .NbCoord: number of vector components
58%            .CoordType: expresses the type of coordinate ('px' for image, 'sig' for instruments, or 'phys')
59%            .dt: time interval for the corresponding image pair
60%            .Mesh: estimated typical distance between vectors
61%            .ZMax:
62%            .ZMin:
63%            .X, .Y, .Z: set of vector coordinates
64%            .U,.V,.W: corresponding set of vector components
65%            .F: corresponding set of warning flags
66%            .FF: corresponding set of false flags, =0 for good vectors
67%            .C: corresponding values of the scalar used for vector color
68%             (.X, .Y, .Z,.U,.V,.W,.F,.FF,.C are matlab vectors of the same length,
69%                     equal to the number of vectors stored in the input open)
70%            .CName: name of the scalar .C
71%            .CType: type of the scalar .C, setting how the scalar is obtained (see 'Scalars' below)
72%            .A image or scalar
73%            .AX: vector of dimension 2 representing the first and last values
74%              of the X coordinates for the image or scalar known on a regular grid,
75%              or vector of dimension .A for a scaler defined on irregular grid.
76%            .AY: same as .AX along the Y direction
77%            .AName: name of the scalar, ='image' for an image
78
79% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   DATA FLOW  (for run0_Callback) %%%%%%%%%%%%%%%%%%%%:
80%
81%
82% 1) Input filenames are determined by MenuBrowse (first field), MenuBrowse_1
83% (second field), or by the stored file names under  Browse, or as an input of uvmat.
84% 2) These functions call 'display_file_name.m' which detects the file series, and fills the file index boxes
85% 3) Then 'update_rootinfo.m' Updates information about a new field series (indices to scan, timing, calibration from an xml file)
86% 4) Then fields are opened and visualised by the main sub-function 'refresh_field.m'
87% The function first reads the name of the input file from the edit boxes  of the GUI
88% A second input file can be introduced for file comparison
89% It then reads the input file(s) with the appropriate function, read for
90% images, read_civxdata.m for CIVx PIV data, nc2struct for other netcdf
91% files.
92%               Main input open   second input open(_1)        second image (pair animation)
93%            |                 |                             
94%            |                 |                                               
95%                     Field{1}         Field{2}               
96%                                                                         |
97% coord transform (phys.m) or other user defined  fct acting on Field{i}  |
98%                                                                   Field{i}
99%                                                                    |
100% calc_field.m: calculate scalar or other derived fields (vort, div..).
101%
102% sub_field.m: combine the input Field{i} in a single set of fields (vector + scalar):
103%              Field{i=1->3}.X --> UvData.X                          |
104%                                                                    |
105%                                                                 UvData
106%                                                                    |
107% plot histograms of the whole  field
108% proj_field.m: project the set of fields on the current projection objects defined by UvData.Object
109%                                                                    |                                                                          |
110%                                                                ObjectData
111%                                                                    |
112% plot_field.m: plot the projected fields and store them as          |
113% UvData.axes3                                        |
114%                                                                    |
115%                                                                AxeData
116%
117%%%%%%%%%%%%%%    SCALARS: %%%%%%%%%%%%??%%%
118% scalars are displayed either as an image or countour plot, either as a color of
119% velocity vectors. The scalar values in the first case is represented by
120% UvData.Field.A, and by UvData.Field.C in the second case. The corresponding set of X
121% and Y coordinates are represented by UvData.Field.AX and UvData.Field.AY, and .X and
122% .Y for C (the same as velocity vectors). If A is a nxxny matrix (scalar
123% on a regtular grid), then .AX andf.AY contains only two elements, represneting the
124% coordinates of the four image corners. The scalar name is represented by
125% the strings .AName and/or .CName.
126% If the scalar exists in an input open (image or scalar stored under its
127% name in a netcdf open), it is directly read at the level of Field{1}or Field{2}.
128% Else only its name AName is recorded in Field{i}, and its field is then calculated
129%by the fuction calc_scal after the coordinate transform or after projection on an edit_object
130     
131% Properties attached to plotting figures (standard Matlab properties):
132%    'CurrentAxes'= gca or get(gcf,'CurrentAxes');
133%    'CurrentPoint'=get(gcf,'CurrentPoint'): figure coordinates of the point over which the mouse is positioned
134%    'CurrentCharacter'=get(gcf,'CurrentCharacter'): last character typed  over the figure where the mouse is positioned
135%    'WindowButtonMotionFcn': function permanently called by mouse motion over the figure
136%    'KeyPressFcn': function called by pressing a key on the key board
137%    'WindowButtonDownFcn':  function called by pressing the mouse over the  figure
138%    'WindowButtonUpFcn': function called by releasing  the mouse pressure over the  figure
139
140% Properties attached to plotting axes:
141%    'CurrentPoint'=get(gca,'CurrentPoint'); (standard Matlab) same as for the figure, but position in plot coordinates.
142%     AxeData:=get(gca,'UserData');
143%     AxeData.Drawing  = create: create a new object
144%                       = deform: modify an existing object by moving its defining create
145%                      = off: no current drawing action
146%                     = translate: translate an existing object
147%                    = calibration: move a calibration point
148%                    = CheckZoom: isolate a subregion for CheckZoom in=1 if an object is being currently drawn, 0 else (set to 0 by releasing mouse button)
149%            .CurrentOrigin: Origin of a curently drawn edit_object
150%            .CurrentLine: currently drawn menuline (A REVOIR)
151%            .CurrentObject: handle of the currently drawn edit_object
152%            .CurrentRectZoom: current rectangle used for CheckZoom
153
154% Properties attached to projection objects (create, menuline, menuplane...):
155%    'Tag'='proj_object': for all projection objects
156%    ObjectData.Type=...: style of projection object:
157%              .ProjMode
158%              .Coord: defines the position of the object
159%              .XMin,YMin....
160%              .XMax,YMax....
161%              .DX,DY,DZ
162%              .Phi, .Theta, .Psi : Euler angles
163%              .X,.Y,.U,.V.... : field data projected on the object
164%              .IndexObj: index in the list of UvData.Object
165           %during plotting
166%               .plotaxes: handles of the current axes used to plot the  result of field projection on the object
167%               .plothandle: vector of handle(s) of the object graphic represnetation in all the opened plotting axes
168% To each projection object #iobj, corresponds an axis
169% Object{iobj}.plotaxes and nbobj representation graphs  Object{iobj}.plothandles(:) (where nbobj is the
170% nbre of current objects opened in uvmat. Note that Object{iobj}.plothandles(iobj)=[] : an object is not represented in its own projection field;
171
172%------------------------------------------------------------------------
173%------------------------------------------------------------------------
174%  I - MAIN FUNCTION uvmat
175%------------------------------------------------------------------------
176%------------------------------------------------------------------------
177function varargout = uvmat(varargin)
178
179% Begin initialization code - DO NOT EDIT
180gui_Singleton = 1;
181gui_State = struct('gui_Name',          mfilename, ...
182                   'gui_Singleton',     gui_Singleton, ...
183                   'gui_OpeningFcn',    @uvmat_OpeningFcn, ...
184                   'gui_OutputFcn',     @uvmat_OutputFcn, ...
185                   'gui_LayoutFcn',     [], ...
186                   'gui_Callback',      []);
187if nargin && ischar(varargin{1})&& ~isempty(regexp(varargin{1},'_Callback','once'))
188    gui_State.gui_Callback = str2func(varargin{1});
189end
190
191if nargout
192    varargout{1:nargout} = gui_mainfcn(gui_State, varargin{:});
193else
194    gui_mainfcn(gui_State, varargin{:});
195end
196% End initialization code - DO NOT EDIT
197
198%------------------------------------------------------------------------
199% --- Executes just before the GUI uvmat is made visible.
200function uvmat_OpeningFcn(hObject, eventdata, handles, input )
201%------------------------------------------------------------------------
202
203%% Choose default command menuline output for uvmat (standard GUI)
204handles.output = hObject;
205
206%% Update handles structure (standard GUI)
207guidata(hObject, handles);
208
209%% set the position of colorbar and ancillary GUIs:
210set(hObject,'Units','Normalized')
211movegui(hObject,'center')
212UvData.OpenParam.PosColorbar=[0.805 0.022 0.019 0.445];
213UvData.OpenParam.SetObjectOrigin=[-0.05 -0.03]; %position for set_object
214UvData.OpenParam.SetObjectSize=[0.3 0.7];
215UvData.OpenParam.CalOrigin=[0.95 -0.03];%position for geometry_calib (TO IMPROVE)
216UvData.OpenParam.CalSize=[0.28 1];
217UvData.axes3=[];%initiate the record of plotted field
218UvData.axes2=[];
219UvData.axes1=[];
220AxeData.LimEditBox=1; %initialise AxeData
221set(handles.axes3,'UserData',AxeData)
222
223%% set functions for the mouse and keyboard
224set(hObject,'KeyPressFcn',{'keyboard_callback',handles})%set keyboard action function
225set(hObject,'WindowButtonMotionFcn',{'mouse_motion',handles})%set mouse action functio
226set(hObject,'WindowButtonDownFcn',{'mouse_down'})%set mouse click action function
227set(hObject,'WindowButtonUpFcn',{'mouse_up',handles})
228set(hObject,'DeleteFcn',{@closefcn})%
229
230%% refresh projection plane
231set(handles.ListObject,'Value',1)% default: empty projection objectproj_field
232set(handles.ListObject,'String',{'plane'})
233set(handles.ListObject_1,'Value',1)% default: empty projection objectproj_field
234set(handles.ListObject_1,'String',{'plane'})
235set(handles.Fields,'Value',1)
236set(handles.Fields,'string',{''})
237
238%% TRANSFORM menu: builtin fcts
239menu_str={'';'phys';'px';'phys_polar'};
240UvData.OpenParam.NbBuiltin=numel(menu_str); %number of functions
241path_uvmat=fileparts(which('uvmat'));
242addpath (path_uvmat) ; %add the path to UVMAT, (useful in case of change of working directory after civ has been s opened in the working directory)
243addpath(fullfile(path_uvmat,'transform_field'))%add the path to transform functions,
244fct_handle{1,1}=[];
245testexist=zeros(size(menu_str'));%default
246testexist(1)=1;
247for ilist=2:length(menu_str)
248    if exist(menu_str{ilist},'file')
249        fct_handle{ilist,1}=str2func(menu_str{ilist});
250        testexist(ilist)=1;
251    else
252        testexist(ilist)=0;
253    end
254end
255rmpath(fullfile(path_uvmat,'transform_field'))
256
257%% load the list of previously browsed files in menus Open and Open_1
258 dir_perso=prefdir; % path to the directory .matlab for personal data
259 profil_perso=fullfile(dir_perso,'uvmat_perso.mat');% personal data file uvmauvmat_perso.mat' in .matlab
260 if exist(profil_perso,'file')
261      h=load (profil_perso);
262      if isfield(h,'MenuFile')
263          for ifile=1:min(length(h.MenuFile),5)
264              eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',h.MenuFile{ifile});'])
265               eval(['set(handles.MenuFile_' num2str(ifile) '_1,''Label'',h.MenuFile{ifile});'])
266          end
267      end
268      if isfield(h,'transform_fct') && iscell(h.transform_fct)
269         for ilist=1:length(h.transform_fct);
270             if exist(h.transform_fct{ilist},'file')
271                [path,file]=fileparts(h.transform_fct{ilist});
272                addpath(path)
273                h_func=str2func(file);
274                rmpath(path)
275                testexist=[testexist 1];
276             else
277                file='';
278                h_func=[];
279                testexist=[testexist 0];
280             end
281             fct_handle=[fct_handle; {h_func}]; %concatene the list of paths
282             menu_str=[menu_str; {file}];
283         end
284      end
285 end
286menu_str=menu_str(testexist==1);%=menu_str(testexist~=0)
287fct_handle=fct_handle(testexist==1);
288menu_str=[menu_str;{'more...'}];
289set(handles.transform_fct,'String',menu_str)
290set(handles.transform_fct,'UserData',fct_handle)% store the list of path in UserData of ACTION
291
292%% case of an input argument for uvmat
293testinputfield=0;
294inputfile=[];
295Field=[];
296if exist('input','var')
297    if ishandle(handles.UVMAT_title)
298        delete(handles.UVMAT_title)
299    end   
300    if isstruct(input)
301        if isfield(input,'InputFile')
302            inputfile=input.InputFile;
303        end
304        if isfield(input,'TimeIndex')
305            set(handles.i1,num2str(input.TimeIndex))
306        end
307        if isfield(input,'FieldsString')
308            UvData.FieldsString=input.FieldsString;
309        end
310    elseif ischar(input)% file name introduced as input
311           inputfile=input;
312    elseif isnumeric(input)%simple matrix introduced as input
313        sizinput=size(input);
314        if sizinput(1)<=1 || sizinput(2)<=1
315            msgbox_uvmat('ERROR','bad input for uvmat: file name, structure or numerical matrix accepted')
316            return
317        end
318        UvData.Field.ListVarName={'A','coord_y','coord_x'};
319        UvData.Field.VarDimName={{'coord_y','coord_x'},'cord_y','coord_x'};
320        UvData.Field.A=input;
321        UvData.Field.coord_x=[0.5 size(input,2)-0.5];
322        UvData.Field.coord_y=[size(input,1)-0.5 0.5];
323        testinputfield=1;
324    end
325else
326    %% check the path and date of modification of all functions in uvmat
327    path_to_uvmat=which ('uvmat');% check the path detected for source file uvmat
328    [infomsg,date_str,svn_info]=check_files;%check the path of the functions called by uvmat.m   
329    date_str=['last modification: ' date_str];
330    if ishandle(handles.UVMAT_title)
331        set(handles.UVMAT_title,'String',...
332            [{'Copyright  LEGI UMR 5519 /CNRS-UJF-Grenoble INP, 2010'};...
333            {'GNU General Public License'};...
334            {path_to_uvmat};...
335            {date_str};...
336            infomsg]);
337    end
338end
339set(handles.uvmat,'UserData',UvData)
340if ~isempty(inputfile)
341    %%%%% display the input field %%%%%%%
342    display_file_name(handles,inputfile)
343    %%%%%%%
344    testinputfield=1;
345end
346
347%% plot input field if exists
348if testinputfield
349    %delete drawn objects
350    hother=findobj(handles.axes3,'Tag','proj_object');%find all the proj objects
351    for iobj=1:length(hother)
352        delete_object(hother(iobj))
353    end 
354    if isempty(inputfile)
355        errormsg=refresh_field(handles,[],[],[],[],[],[],{Field});
356        set(handles.MenuTools,'Enable','on')
357        set(handles.OBJECT_txt,'Visible','on')
358        set(handles.edit_object,'Visible','on')
359%         set(handles.ListObject_1,'Visible','on')
360        set(handles.frame_object,'Visible','on')
361        if ~isempty(errormsg)
362            msgbox_uvmat('ERROR',errormsg)
363        end
364    end
365end
366
367set_vec_col_bar(handles) %update the display of color code for vectors
368
369%------------------------------------------------------------------------
370% --- Outputs from this function are returned to the command menuline.
371function varargout = uvmat_OutputFcn(hObject, eventdata, handles)
372varargout{1} = handles.output;% the only output argument is the handle to the GUI figure
373
374%------------------------------------------------------------------------
375% --- executed when closing uvmat: delete or desactivate the associated figures if exist
376function closefcn(gcbo,eventdata)
377%------------------------------------------------------------------------
378hh=findobj(allchild(0),'tag','view_field');
379if ~isempty(hh)
380    delete(hh)
381end
382hh=findobj(allchild(0),'tag','geometry_calib');
383if ~isempty(hh)
384    delete(hh)
385end
386hh=findobj(allchild(0),'tag','set_object');
387if ~isempty(hh)
388    hhh=findobj(hh,'tag','PLOT');
389    set(hhh,'enable','off')
390end
391
392%------------------------------------------------------------------------
393%------------------------------------------------------------------------
394%  II - FUNCTIONS FOR INTRODUCING THE INPUT FILES
395% automatically sets the global properties when the rootfile name is introduced
396% then activate the view-field action if selected
397% it is activated either by clicking on the RootPath window or by the
398% browser
399%------------------------------------------------------------------------
400%------------------------------------------------------------------------
401% --- Executes on the menu Open/Browse...
402% search the files, recognize their type according to their name and fill the rootfile input windows
403function MenuBrowse_Callback(hObject, eventdata, handles)
404[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
405oldfile=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
406if isempty(oldfile)||isequal(oldfile,'') %loads the previously stored file name and set it as default in the file_input box
407         dir_perso=prefdir;
408         profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
409         if exist(profil_perso,'file')
410              h=load (profil_perso);
411             if isfield(h,'MenuFile_1')
412                  oldfile=h.MenuFile_1;
413             end
414         end
415end
416[FileName, PathName] = uigetfile({'*.*','All Files(*.*)'},'Pick a file',oldfile);
417fileinput=[PathName FileName];%complete file name
418if ~exist(fileinput,'file')
419    return %abandon of the browser is cancelled
420end
421
422%% display the selected field and related information
423display_file_name( handles,fileinput)
424
425% -----------------------------------------------------------------------
426% --- Open again the file whose name has been recorded in MenuFile_1
427function MenuFile_1_Callback(hObject, eventdata, handles)
428%------------------------------------------------------------------------
429fileinput=get(handles.MenuFile_1,'Label');
430display_file_name( handles,fileinput)
431
432% -----------------------------------------------------------------------
433% --- Open again the file whose name has been recorded in MenuFile_2
434function MenuFile_2_Callback(hObject, eventdata, handles)
435%------------------------------------------------------------------------
436fileinput=get(handles.MenuFile_2,'Label');
437display_file_name(handles,fileinput)
438
439% -----------------------------------------------------------------------
440% --- Open again the file whose name has been recorded in MenuFile_3
441function MenuFile_3_Callback(hObject, eventdata, handles)
442%------------------------------------------------------------------------
443fileinput=get(handles.MenuFile_3,'Label');
444display_file_name(handles,fileinput)
445
446% -----------------------------------------------------------------------
447% --- Open again the file whose name has been recorded in MenuFile_4
448function MenuFile_4_Callback(hObject, eventdata, handles)
449%------------------------------------------------------------------------
450fileinput=get(handles.MenuFile_4,'Label');
451display_file_name(handles,fileinput)
452
453% -----------------------------------------------------------------------
454% --- Open again the file whose name has been recorded in MenuFile_5
455function MenuFile_5_Callback(hObject, eventdata, handles)
456%------------------------------------------------------------------------
457fileinput=get(handles.MenuFile_5,'Label');
458display_file_name(handles,fileinput)
459
460%------------------------------------------------------------------------
461% --- Executes on the menu Open/Browse_1 for the second input field,
462%     search the files, recognize their type according to their name and fill the rootfile input windows
463function MenuBrowse_1_Callback(hObject, eventdata, handles)
464%------------------------------------------------------------------------
465RootPath=get(handles.RootPath,'String');
466[FileName, PathName] = uigetfile({'*.*','All Files(*.*)'},'Pick a file',RootPath);
467fileinput_1=[PathName FileName];%complete file name
468if ~exist(fileinput_1,'file')
469    return %abandon of the browser is cancelled
470end
471
472% refresh the current displayed field
473set(handles.SubField,'Value',1)
474display_file_name(handles,fileinput_1,2)
475
476%update list of recent files in the menubar
477MenuFile_1=fileinput_1;
478MenuFile_2=get(handles.MenuFile_1,'Label');
479MenuFile_3=get(handles.MenuFile_2,'Label');
480MenuFile_4=get(handles.MenuFile_3,'Label');
481MenuFile_5=get(handles.MenuFile_4,'Label');
482set(handles.MenuFile_1,'Label',MenuFile_1)
483set(handles.MenuFile_2,'Label',MenuFile_2)
484set(handles.MenuFile_3,'Label',MenuFile_3)
485set(handles.MenuFile_4,'Label',MenuFile_4)
486set(handles.MenuFile_5,'Label',MenuFile_5)
487set(handles.MenuFile_1_1,'Label',MenuFile_1)
488set(handles.MenuFile_2_1,'Label',MenuFile_2)
489set(handles.MenuFile_3_1,'Label',MenuFile_3)
490set(handles.MenuFile_4_1,'Label',MenuFile_4)
491set(handles.MenuFile_5_1,'Label',MenuFile_5)
492dir_perso=prefdir;
493profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
494if exist(profil_perso,'file')
495    save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5','-append'); %store the file names for future opening of uvmat
496else
497    txt=ver('MATLAB');
498    Release=txt.Release;
499    relnumb=str2double(Release(3:4));
500    if relnumb >= 14
501        save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5','-V6'); %store the file names for future opening of uvmat
502    else
503        save (profil_perso,'MenuFile_1','MenuFile_2','MenuFile_3','MenuFile_4', 'MenuFile_5'); %store the file names for future opening of uvmat
504    end
505end
506
507% -----------------------------------------------------------------------
508% --- Open again as second field the file whose name has been recorded in MenuFile_1
509function MenuFile_1_1_Callback(hObject, eventdata, handles)
510% -----------------------------------------------------------------------
511fileinput_1=get(handles.MenuFile_1_1,'Label');
512set(handles.SubField,'Value',1)
513display_file_name(handles,fileinput_1,2)
514
515% -----------------------------------------------------------------------
516% --- Open again as second field the file whose name has been recorded in MenuFile_2
517function MenuFile_2_1_Callback(hObject, eventdata, handles)
518% -----------------------------------------------------------------------
519fileinput_1=get(handles.MenuFile_2_1,'Label');
520set(handles.SubField,'Value',1)
521display_file_name(handles,fileinput_1,2)
522
523% -----------------------------------------------------------------------
524% --- Open again as second field the file whose name has been recorded in MenuFile_3
525function MenuFile_3_1_Callback(hObject, eventdata, handles)
526% -----------------------------------------------------------------------
527fileinput_1=get(handles.MenuFile_3_1,'Label');
528set(handles.SubField,'Value',1)
529display_file_name(handles,fileinput_1,2)
530
531% -----------------------------------------------------------------------
532% --- Open again as second field the file whose name has been recorded in MenuFile_4
533function MenuFile_4_1_Callback(hObject, eventdata, handles)
534% -----------------------------------------------------------------------
535fileinput_1=get(handles.MenuFile_4_1,'Label');
536set(handles.SubField,'Value',1)
537display_file_name(handles,fileinput_1,2)
538
539% -----------------------------------------------------------------------
540% --- Open again as second field the file whose name has been recorded in MenuFile_5
541function MenuFile_5_1_Callback(hObject, eventdata, handles)
542% -----------------------------------------------------------------------
543fileinput_1=get(handles.MenuFile_5_1,'Label');
544set(handles.SubField,'Value',1)
545display_file_name(handles,fileinput_1,2)
546
547%------------------------------------------------------------------------
548% --- Called by action in RootPath edit box
549function RootPath_Callback(hObject,eventdata,handles)
550%------------------------------------------------------------------------
551% read the current input file name:
552[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
553if ~exist(fullfile(RootPath,SubDir),'dir')
554    msgbox_uvmat('ERROR',['directory ' fullfile(RootPath,SubDir) ' does not exist'])
555    return
556end
557% detect the file type, get the movie object if relevant, and look for the corresponding file series:
558[RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,tild,FileType,MovieObject]=find_file_series(fullfile(RootPath,SubDir),[RootFile FileIndices FileExt]);
559% initiate the input file series and refresh the current field view:
560update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,MovieObject,1);
561
562%-----------------------------------------------------------------------
563% --- Called by action in RootPath_1 edit box
564function RootPath_1_Callback(hObject,eventdata,handles)
565% -----------------------------------------------------------------------
566% update_rootinfo_1(hObject,eventdata,handles)
567[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes_1(handles);
568if ~exist(fullfile(RootPath,SubDir),'dir')
569    msgbox_uvmat('ERROR',['directory ' fullfile(RootPath,SubDir) ' does not exist'])
570    return
571end
572% detect the file type, get the movie object if relevant, and look for the corresponding file series:
573[RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,tild,FileType,MovieObject]=find_file_series(fullfile(RootPath,SubDir),[RootFile FileIndices FileExt]);
574% initiate the input file series and refresh the current field view:
575update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,MovieObject,2);
576
577%------------------------------------------------------------------------
578% --- Called by action in RootFile edit box
579function SubDir_Callback(hObject, eventdata, handles)
580%------------------------------------------------------------------------
581%refresh the menu of input fields
582Fields_Callback(hObject, eventdata, handles);
583% refresh the current field view
584run0_Callback(hObject, eventdata, handles);
585
586%------------------------------------------------------------------------
587% --- Called by action in RootFile edit box
588function RootFile_Callback(hObject, eventdata, handles)
589%------------------------------------------------------------------------
590RootPath_Callback(hObject,eventdata,handles)
591
592%-----------------------------------------------------------------------
593% --- Called by action in RootFile_1 edit box
594function RootFile_1_Callback(hObject, eventdata, handles)
595% -----------------------------------------------------------------------
596RootPath_1_Callback(hObject,eventdata,handles)
597
598%------------------------------------------------------------------------
599% --- Called by action in FileIndex edit box
600function FileIndex_Callback(hObject, eventdata, handles)
601%------------------------------------------------------------------------
602[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
603set(handles.i1,'String',num2str(i1));
604set(handles.i2,'String',num2str(i2));
605set(handles.j1,'String',num2str(j1));
606set(handles.j2,'String',num2str(j2));
607
608% refresh the current field view
609run0_Callback(hObject, eventdata, handles)
610
611%------------------------------------------------------------------------
612% --- Called by action in FileIndex_1 edit box
613function FileIndex_1_Callback(hObject, eventdata, handles)
614%------------------------------------------------------------------------
615run0_Callback(hObject, eventdata, handles)
616
617%------------------------------------------------------------------------
618% --- Called by action in NomType edit box
619function NomType_Callback(hObject, eventdata, handles)
620%------------------------------------------------------------------------
621i1=str2num(get(handles.i1,'String'));
622i2=str2num(get(handles.i2,'String'));
623j1=str2num(get(handles.j1,'String'));
624j2=str2num(get(handles.j2,'String'));
625FileIndex=fullfile_uvmat('','','','',get(handles.NomType,'String'),i1,i2,j1,j2);
626set(handles.FileIndex,'String',FileIndex)
627% refresh the current settings and refresh the field view
628RootPath_Callback(hObject,eventdata,handles)
629
630%------------------------------------------------------------------------
631% --- Called by action in NomType edit box
632function NomType_1_Callback(hObject, eventdata, handles)
633%------------------------------------------------------------------------
634i1=str2num(get(handles.i1,'String'));
635i2=str2num(get(handles.i2,'String'));
636j1=str2num(get(handles.j1,'String'));
637j2=str2num(get(handles.j2,'String'));
638FileIndex=fullfile_uvmat('','','','',get(handles.NomType_1,'String'),i1,i2,j1,j2);
639set(handles.FileIndex_1,'String',FileIndex)
640% refresh the current settings and refresh the field view
641RootPath_1_Callback(hObject,eventdata,handles)
642
643%------------------------------------------------------------------------
644% --- Fills the edit boxes RootPath, RootFile,NomType...from an input file name 'fileinput'
645function display_file_name(handles,fileinput,index)
646%------------------------------------------------------------------------
647%% look for the input file existence
648if ~exist(fileinput,'file')
649    msgbox_uvmat('ERROR',['input file ' fileinput  ' does not exist'])
650    return
651end
652
653%% set the mouse pointer to 'watch'
654set(handles.uvmat,'Pointer','watch')
655set(handles.RootPath,'BackgroundColor',[1 1 0])
656drawnow
657
658%% define the relevant handles for the first field series (index=1) or the second file series (index=2)
659if ~exist('index','var')
660    index=1;
661end
662if index==1
663    handles_RootPath=handles.RootPath;
664    handles_SubDir=handles.SubDir;
665    handles_RootFile=handles.RootFile;
666    handles_FileIndex=handles.FileIndex;
667    handles_NomType=handles.NomType;
668    handles_FileExt=handles.FileExt;
669elseif index==2
670    handles_RootPath=handles.RootPath_1;
671    handles_SubDir=handles.SubDir_1;
672    handles_RootFile=handles.RootFile_1;
673    handles_FileIndex=handles.FileIndex_1;
674    handles_NomType=handles.NomType_1;
675    handles_FileExt=handles.FileExt_1;
676    set(handles.RootPath_1,'Visible','on')
677    set(handles.RootFile_1,'Visible','on')
678    set(handles.SubDir_1,'Visible','on');
679    set(handles.FileIndex_1,'Visible','on');
680    set(handles.FileExt_1,'Visible','on');
681    set(handles.NomType_1,'Visible','on');
682end
683
684%% detect root name, nomenclature and indices in the input file name:
685[FilePath,FileName,FileExt]=fileparts(fileinput);
686% detect the file type, get the movie object if relevant, and look for the corresponding file series:
687% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
688[RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,NomType,FileType,MovieObject,i1,i2,j1,j2]=find_file_series(FilePath,[FileName FileExt]);
689
690%% open the file or fill the GUI uvmat according to the detected file type
691switch FileType
692    case ''
693        msgbox_uvmat('ERROR','invalid input file type')
694    case 'txt'
695        edit(fileinput)
696    case 'figure'                           %display matlab figure
697        hfig=open(fileinput);
698        set(hfig,'WindowButtonMotionFcn','mouse_motion')%set mouse action functio
699        set(hfig,'WindowButtonUpFcn','mouse_up')%set mouse click action function
700        set(hfig,'WindowButtonUpFcn','mouse_down')%set mouse click action function
701    case 'xml'                % edit xml files
702        if ~isempty(regexp(fileinput,'.project.xml$'))
703            datatree_browser(fileinput)
704        else
705            editxml(fileinput);
706        end
707        %             if exist(regexprep(fileinput,'.project.xml$','.link'),'dir')
708        %                 datatree_browser(regexprep(fileinput,'.project.xml$','.link'))
709        %                 check_project=1;
710        %         elseif exist(regexprep(fileinput,'.project.xml$',''),'dir')
711        %                 datatree_browser(regexprep(fileinput,'.project.xml$',''))
712        %                 check_project=1;
713        %             end
714        %         end
715        %         if ~check_project
716        %         editxml(fileinput);
717    case 'xls'
718        editxml(fileinput);
719    otherwise
720        set(handles_RootPath,'String',RootPath);
721        rootname=fullfile(RootPath,SubDir,RootFile);
722        set(handles_SubDir,'String',['/' SubDir]);
723        set(handles_RootFile,'String',['/' RootFile]); %display the separator
724        indices=fileinput(length(rootname)+1:end);
725        indices(end-length(FileExt)+1:end)=[]; %remove extension
726        set(handles_FileIndex,'String',indices);
727        set(handles_NomType,'String',NomType);
728        set(handles_FileExt,'String',FileExt);
729        if index==1
730            % fill file index counters if the first file series is opened
731            set(handles.i1,'String',num2str(i1));
732            set(handles.i2,'String',num2str(i2));
733            set(handles.j1,'String',num2stra(j1,NomType));
734            set(handles.j2,'String',num2stra(j2,NomType));
735        else %read the current field index if the second file series is opened
736            i1=str2num(get(handles.i1,'String'));
737            i2=str2num(get(handles.i2,'String'));
738            j1=stra2num(get(handles.j1,'String'));
739            j2=stra2num(get(handles.j2,'String'));
740        end
741       
742        % synchronise indices of the second  input file if it exists
743        if get(handles.SubField,'Value')==1% if the subfield button is activated, update the field numbers
744            Input=read_GUI(handles.InputFile);
745            if ~isfield(Input,'RootPath_1')||strcmp(Input.RootPath_1,'"')
746                Input.RootPath_1=Input.RootPath;
747            end
748            if ~isfield(Input,'SubDir_1')||strcmp(Input.SubDir_1,'"')
749                Input.SubDir_1=Input.SubDir;
750            end
751            if ~isfield(Input,'RootFile_1')||strcmp(Input.RootFile_1,'"')
752                Input.RootFile_1=Input.RootFile;
753            end
754            if ~isfield(Input,'FileExt_1')||strcmp(Input.FileExt_1,'"')
755                Input.FileExt_1=Input.FileExt;
756            end
757            if ~isfield(Input,'NomType_1')||strcmp(Input.NomType_1,'"')
758                Input.NomType_1=Input.NomType;
759            end
760            %updtate the indices of the second field series to correspond to the newly opened one
761            FileName_1=fullfile_uvmat(Input.RootPath_1,Input.SubDir_1,Input.RootFile_1,Input.FileExt_1,Input.NomType_1,i1,i2,j1,j2);
762            if exist(FileName_1,'file')
763                FileIndex_1=fullfile_uvmat('','','','',Input.NomType_1,i1,i2,j1,j2);
764                set(handles.FileIndex_1,'String',FileIndex_1)
765            else
766                msgbox_uvmat('WARNING','unable to synchronise the indices of the two series')
767            end
768        end
769       
770        %enable other menus
771        set(handles.MenuOpen_1,'Enable','on')
772        set(handles.MenuFile_1_1,'Enable','on')
773        set(handles.MenuFile_2_1,'Enable','on')
774        set(handles.MenuFile_3_1,'Enable','on')
775        set(handles.MenuFile_4_1,'Enable','on')
776        set(handles.MenuFile_5_1,'Enable','on')
777        set(handles.MenuExport,'Enable','on')
778        set(handles.MenuExportFigure,'Enable','on')
779        set(handles.MenuExportMovie,'Enable','on')
780        set(handles.MenuTools,'Enable','on')
781
782        % initiate input file series and refresh the current field view:     
783        update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,MovieObject,index);
784
785end
786
787%% update list of recent files in the menubar and save it for future opening
788MenuFile=[{get(handles.MenuFile_1,'Label')};{get(handles.MenuFile_2,'Label')};...
789    {get(handles.MenuFile_3,'Label')};{get(handles.MenuFile_4,'Label')};{get(handles.MenuFile_5,'Label')}];
790str_find=strcmp(fileinput,MenuFile);
791if isempty(find(str_find,1))
792    MenuFile=[{fileinput};MenuFile];%insert the current file if not already in the list
793end
794for ifile=1:min(length(MenuFile),5)
795    eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',MenuFile{ifile});'])
796    eval(['set(handles.MenuFile_' num2str(ifile) '_1,''Label'',MenuFile{ifile});'])
797end
798dir_perso=prefdir;
799profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
800if exist(profil_perso,'file')
801    save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
802else
803    save (profil_perso,'MenuFile','-V6'); %store the file names for future opening of uvmat
804end
805
806%% set back the mouse pointer to arrow
807set(handles.uvmat,'Pointer','arrow')
808
809
810%------------------------------------------------------------------------
811% --- Update information about a new field series (indices to scan, timing,
812%     calibration from an xml file, then refresh current plots
813function update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,VideoObject,index)
814%------------------------------------------------------------------------
815%% define the relevant handles depending on the index (1=first file series, 2= second file series)
816if ~exist('index','var')
817    index=1;
818end
819if index==1
820    handles_RootPath=handles.RootPath;
821    handles_Fields=handles.Fields;
822elseif index==2
823    handles_RootPath=handles.RootPath_1;
824    handles_Fields=handles.Fields_1;
825end
826
827set(handles_RootPath,'BackgroundColor',[1 1 0])
828drawnow
829set(handles.Fields,'UserData',[])% reinialize data from uvmat opening
830UvData=get(handles.uvmat,'UserData');%huvmat=handles of the uvmat interface
831UvData.NewSeries=1; %flag for run0: begin a new series
832UvData.TestInputFile=1;
833UvData.FileType{index}=FileType;
834UvData.i1_series{index}=i1_series;
835UvData.i2_series{index}=i2_series;
836UvData.j1_series{index}=j1_series;
837UvData.j2_series{index}=j2_series;
838set(handles.FixVelType,'Value',0); %desactivate fixed veltype
839if index==1
840    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
841else
842    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes_1(handles);
843end
844FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
845FileBase=fullfile(RootPath,RootFile);
846if ~exist(FileName,'file')
847   msgbox_uvmat('ERROR',['input file ' FileName ' not found']);
848    return
849end
850% nbfield=[];%default
851% nbfield_j=[];%default
852
853%% read timing and total frame number from the current file (movie files) !! may be overrid by xml file
854XmlData.Time=[];%default
855XmlData.GeometryCalib=[];%default
856TimeUnit='';%default
857Time=[];
858testima=0; %test for image input
859imainfo=[];
860ColorType='falsecolor'; %default
861hhh=[];
862UvData.MovieObject{index}=VideoObject;
863if ~isempty(VideoObject)
864    imainfo=get(VideoObject);
865    testima=1;
866%     nbfield_j=1;
867    TimeUnit='s';
868    if isempty(j1_series); %frame index along i
869        Time=(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate)';
870    else
871    Time=ones(size(i1_series,1),1)*(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate);
872    end
873    %nbfield=imainfo.NumberOfFrames;
874    set(handles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FrameRate) 'ms']);%display the elementary time interval in millisec
875    ColorType='truecolor';
876elseif ~isempty(FileExt(2:end))&&(~isempty(imformats(FileExt(2:end))) || isequal(FileExt,'.vol'))%&& isequal(NomType,'*')% multi-frame image
877    testima=1;
878    if ~isequal(SubDir,'')
879        RootFile=get(handles.RootFile,'String');
880        imainfo=imfinfo([fullfile(RootPath,SubDir,RootFile) FileIndices FileExt]);
881    else
882        imainfo=imfinfo([FileBase FileIndices FileExt]);
883    end
884    ColorType=imainfo.ColorType;%='truecolor' for color images
885    if length(imainfo) >1 %case of image with multiple frames
886       % nbfield=length(imainfo);
887       % nbfield_j=1;
888    end
889end
890if isfield(imainfo,'Width') && isfield(imainfo,'Height')
891    if length(imainfo)>1
892        set(handles.num_Npx,'String',num2str(imainfo(1).Width));%fills nbre of pixels x box
893        set(handles.num_Npy,'String',num2str(imainfo(1).Height));%fills nbre of pixels x box
894    else
895        set(handles.num_Npx,'String',num2str(imainfo.Width));%fills nbre of pixels x box
896        set(handles.num_Npy,'String',num2str(imainfo.Height));%fills nbre of pixels x box
897    end
898else
899    set(handles.num_Npx,'String','');%fills nbre of pixels x box
900    set(handles.num_Npy,'String','');%fills nbre of pixels x box
901end
902set(handles.CheckBW,'Value',strcmp(ColorType,'grayscale'))% select handles.CheckBW if grayscale image
903
904%% read parameters (time, geometric calibration..) from a documentation file (.xml advised)
905XmlFileName=find_imadoc(RootPath,SubDir,RootFile,FileExt);
906[tild,tild,DocExt]=fileparts(XmlFileName);
907warntext='';%default warning message
908NbSlice=1;%default
909set(handles.RootPath,'BackgroundColor',[1 1 1])
910if ~isempty(XmlFileName)
911    set(handles.view_xml,'Visible','on')
912    set(handles.view_xml,'BackgroundColor',[1 1 0])
913    set(handles.view_xml,'String','view .xml')
914    drawnow
915    [XmlDataRead,warntext]=imadoc2struct(XmlFileName);
916    if ~isempty(warntext)
917        msgbox_uvmat('WARNING',warntext)
918    end
919    if isempty(XmlDataRead)
920        set(handles.view_xml,'Visible','off')
921    else
922        set(handles.view_xml,'String',['view ' DocExt])   
923        XmlData=XmlDataRead;
924        if isfield(XmlData,'TimeUnit')
925            if isfield(XmlData,'TimeUnit')&& ~isempty(XmlData.TimeUnit)
926                TimeUnit=XmlData.TimeUnit;
927            end
928        end
929        set(handles.view_xml,'BackgroundColor',[1 1 1])
930        drawnow
931        if isfield(XmlData, 'GeometryCalib') && ~isempty(XmlData.GeometryCalib)
932            if isfield(XmlData.GeometryCalib,'VolumeScan') && isequal(XmlData.GeometryCalib.VolumeScan,'y')
933                set (handles.num_NbSlice,'String','volume')
934            end
935            hgeometry_calib=findobj('tag','geometry_calib');
936            if ~isempty(hgeometry_calib)
937                GUserData=get(hgeometry_calib,'UserData');
938                if ~(isfield(GUserData,'XmlInputFile') && strcmp(GUserData.XmlInputFile,XmlFileName))
939                    answer=msgbox_uvmat('INPUT_Y-N','replace the display of geometry_calib with the new input data?');
940                    if strcmp(answer,'Yes')
941                        geometry_calib(XmlFileName);%diplay the new calibration points and parameters in geometry_calib
942                    end
943                end
944            end
945        end
946    end
947end
948if ~(isfield(XmlData,'Time')&& ~isempty(XmlData.Time))
949    XmlData.Time=Time; %time set by video
950end
951
952%% store last index in handles.lat_i and .last_j
953nbfield=max(max(max(i2_series)));
954if isempty(nbfield)
955    nbfield=max(max(max(i1_series)));
956end
957nbfield_j=max(max(max(j2_series)));
958if isempty(nbfield_j)
959    nbfield_j=max(max(max(j2_series)));
960end
961if ~isempty(XmlData.Time)
962    %transform .Time to a column vector if it is a line vector the nomenclature uses a single index
963    if isequal(size(XmlData.Time,1),1)
964        NomType=get(handles.NomType,'String');
965        XmlData.Time=(XmlData.Time)';
966    end
967end
968last_i_cell=get(handles.last_i,'String');
969if isempty(nbfield)
970    last_i_cell{1}='';
971else
972    last_i_cell{1}=num2str(nbfield);
973end
974set(handles.last_i,'String',last_i_cell)
975last_j_cell=get(handles.last_j,'String');
976if isempty(nbfield_j)
977     last_j_cell{1}='';
978else
979     last_j_cell{1}=num2str(nbfield_j);
980end
981set(handles.last_j,'String',last_j_cell);
982
983%% store geometric calibration in UvData
984if isfield(XmlData,'GeometryCalib')
985    GeometryCalib=XmlData.GeometryCalib;
986    if isempty(GeometryCalib)
987        set(handles.pxcm,'String','')
988        set(handles.pycm,'String','')
989        set(handles.transform_fct,'Value',1); %  no transform by default
990    else
991        if (isfield(GeometryCalib,'R')&& ~isequal(GeometryCalib.R(2,1),0) && ~isequal(GeometryCalib.R(1,2),0)) ||...
992            (isfield(GeometryCalib,'kappa1')&& ~isequal(GeometryCalib.kappa1,0))
993            set(handles.pxcm,'String','var')
994            set(handles.pycm,'String','var')
995        elseif isfield(GeometryCalib,'fx_fy')
996            pixcmx=GeometryCalib.fx_fy(1);%*GeometryCalib.R(1,1)*GeometryCalib.sx/(GeometryCalib.Tz*GeometryCalib.dpx);
997            pixcmy=GeometryCalib.fx_fy(2);%*GeometryCalib.R(2,2)/(GeometryCalib.Tz*GeometryCalib.dpy);
998            set(handles.pxcm,'String',num2str(pixcmx))
999            set(handles.pycm,'String',num2str(pixcmy))
1000        end
1001        if ~get(handles.CheckFixLimits,'Value')
1002            set(handles.transform_fct,'Value',2); % phys transform by default if fixedLimits is off
1003        end
1004        if isfield(GeometryCalib,'SliceCoord')
1005           
1006           siz=size(GeometryCalib.SliceCoord);
1007           if siz(1)>1
1008               NbSlice=siz(1);
1009               set(handles.slices,'Visible','on')
1010               set(handles.slices,'Value',1)
1011           end
1012           if isfield(GeometryCalib,'VolumeScan') && isequal(GeometryCalib.VolumeScan,'y')
1013               set(handles.num_NbSlice,'String','volume')
1014           else
1015               set(handles.num_NbSlice,'String',num2str(NbSlice))
1016           end
1017           slices_Callback([],[], handles)
1018        end           
1019    end
1020end
1021
1022%% update the data attached to the uvmat interface
1023if ~isempty(TimeUnit)
1024    set(handles.time_txt,'String',['time (' TimeUnit ')'])
1025end
1026UvData.TimeUnit=TimeUnit;
1027UvData.XmlData{index}=XmlData;
1028UvData.NewSeries=1;
1029% UvData.MovieObject=MovieObject;
1030
1031%display warning message
1032if ~isequal(warntext,'')
1033    msgbox_uvmat('WARNING',warntext);
1034end
1035
1036%% set default options in menu 'Fields'
1037if ~testima
1038    testcivx=0;
1039    if isfield(UvData,'FieldsString') && isequal(UvData.FieldsString,{'get_field...'})% field menu defined as input (from get_field)
1040        set(handles_Fields,'Value',1)
1041        set(handles_Fields,'String',{'get_field...'})
1042        UvData=rmfield(UvData,'FieldsString');
1043    else
1044        Data=nc2struct(FileName,'ListGlobalAttribute','Conventions','absolut_time_T0','civ');
1045        if strcmp(Data.Conventions,'uvmat/civdata') ||( ~isempty(Data.absolut_time_T0)&& ~isequal(Data.civ,0))%if the new input is Civx
1046            FieldList=calc_field;
1047            set(handles_Fields,'String',[{'image'};FieldList;{'get_field...'}]);%standard menu for civx data
1048            set(handles_Fields,'Value',2) % set menu to 'velocity'
1049            col_vec=FieldList;
1050            col_vec(1)=[];%remove 'velocity' option for vector color (must be a scalar)
1051            testcivx=1;
1052        end
1053        if ~testcivx
1054            set(handles_Fields,'Value',1) % set menu to 'get_field...
1055            set(handles_Fields,'String',{'get_field...'})
1056            col_vec={'get_field...'};
1057        end
1058        set(handles.ColorScalar,'String',col_vec)
1059    end
1060end
1061set(handles.uvmat,'UserData',UvData)
1062
1063%% set index navigation options and refresh plots
1064scan_option='i';%default
1065state_j='off'; %default
1066if index==2
1067    if get(handles.scan_j,'Value')
1068        scan_option='j'; %keep the scan option for the second file series
1069    end
1070    if strcmp(get(handles.j1,'Visible'),'on')
1071        state_j='on';
1072    end
1073end
1074[ref_i,ref_j]=find(i1_series);
1075if ~isempty(j1_series)
1076        state_j='on';
1077        if index==1
1078            if isequal(ref_i,ref_i(1)*ones(size(ref_j)))% if ref_i is always equal to its first vzlue
1079                scan_option='j'; %scan j indext               
1080            end
1081        end
1082end
1083if isequal(scan_option,'i')
1084    diff_ref_i=diff(ref_i,1);
1085    if isempty(diff_ref_i)
1086        diff_ref_i=1;
1087    end
1088    if isequal (diff_ref_i,diff_ref_i(1)*ones(size(diff_ref_i)))
1089        set(handles.increment_scan,'String',num2str(diff_ref_i(1)))
1090    end
1091     set(handles.scan_i,'Value',1)
1092     scan_i_Callback([],[], handles);
1093else
1094    diff_ref_j=diff(ref_j);
1095    if isempty(diff_ref_j)
1096        diff_ref_j=1;
1097    end
1098    if isequal (diff_ref_j,diff_ref_j(1)*ones(size(diff_ref_j)))
1099        set(handles.increment_scan,'String',num2str(diff_ref_j(1)))
1100    end
1101     set(handles.scan_j,'Value',1)
1102     scan_j_Callback([],[], handles);
1103end
1104set(handles.scan_j,'Visible',state_j)
1105set(handles.j1,'Visible',state_j)
1106set(handles.j2,'Visible',state_j)
1107set(handles.last_j,'Visible',state_j);
1108set(handles.frame_j,'Visible',state_j);
1109set(handles.j_text,'Visible',state_j);
1110if ~isempty(i2_series)||~isempty(j2_series)
1111    set(handles.CheckFixPair,'Visible','on')
1112elseif index==1
1113    set(handles.CheckFixPair,'Visible','off')
1114end
1115
1116%% view the field 
1117run0_Callback([],[], handles); %view field
1118mask_test=get(handles.CheckMask,'value');
1119if mask_test
1120    MaskData=get(handles.CheckMask,'UserData');
1121    if isfield(MaskData,'maskhandle') && ishandle(MaskData.maskhandle)
1122          delete(MaskData.maskhandle)    %delete old mask
1123    end
1124    CheckMask_Callback([],[],handles)
1125end
1126
1127%------------------------------------------------------------------------
1128% --- switch file index scanning options scan_i and scan_j in an exclusive way
1129function scan_i_Callback(hObject, eventdata, handles)
1130%------------------------------------------------------------------------
1131if get(handles.scan_i,'Value')==1
1132    set(handles.scan_i,'BackgroundColor',[1 1 0])
1133    set(handles.scan_j,'Value',0)
1134else
1135    set(handles.scan_i,'BackgroundColor',[0.831 0.816 0.784])
1136    set(handles.scan_j,'Value',1)
1137end
1138scan_j_Callback(hObject, eventdata, handles)
1139
1140%------------------------------------------------------------------------
1141% --- switch file index scanning options scan_i and scan_j in an exclusive way
1142function scan_j_Callback(hObject, eventdata, handles)
1143%------------------------------------------------------------------------
1144if get(handles.scan_j,'Value')==1
1145    set(handles.scan_j,'BackgroundColor',[1 1 0])
1146    set(handles.scan_i,'Value',0)
1147    set(handles.scan_i,'BackgroundColor',[0.831 0.816 0.784])
1148%     NomType=get(handles.NomType,'String');
1149%     switch NomType
1150%     case {'_1_1-2','#_ab','%3dab'},% pair with j index
1151%         set(handles.CheckFixPair,'Visible','on')% option fixed pair on/off made visible (choice of avaible pair with buttons + and - if ='off')
1152%     otherwise
1153%         set(handles.CheckFixPair,'Visible','off')
1154%     end
1155else
1156    set(handles.scan_j,'BackgroundColor',[0.831 0.816 0.784])
1157    set(handles.scan_i,'Value',1)
1158    set(handles.scan_i,'BackgroundColor',[1 1 0])
1159    set(handles.CheckFixPair,'Visible','off')
1160end
1161
1162%------------------------------------------------------------------------
1163function i1_Callback(hObject, eventdata, handles)
1164%------------------------------------------------------------------------
1165set(handles.i1,'BackgroundColor',[0.7 0.7 0.7])
1166NomType=get(handles.NomType,'String');
1167i1=stra2num(get(handles.i1,'String'));
1168i2=stra2num(get(handles.i2,'String'));
1169j1=stra2num(get(handles.j1,'String'));
1170j2=stra2num(get(handles.j2,'String'));
1171indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,j2);
1172%indices=name_generator('',num1,num_a,'',NomType,1,num2,num_b,'');
1173set(handles.FileIndex,'String',indices)
1174set(handles.FileIndex,'BackgroundColor',[0.7 0.7 0.7])
1175if get(handles.SubField,'Value')==1
1176    NomType_1=get(handles.NomType_1,'String');
1177    indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,j2);
1178     %indices=name_generator('',num1,num_a,'',NomType_1,1,num2,num_b,'');
1179     set(handles.FileIndex_1,'String',indices)
1180     set(handles.FileIndex_1,'BackgroundColor',[0.7 0.7 0.7])
1181end
1182
1183%------------------------------------------------------------------------
1184function i2_Callback(hObject, eventdata, handles)
1185%------------------------------------------------------------------------
1186set(handles.i2,'BackgroundColor',[0.7 0.7 0.7])
1187i1_Callback(hObject, eventdata, handles)
1188
1189%------------------------------------------------------------------------
1190function j1_Callback(hObject, eventdata, handles)
1191%------------------------------------------------------------------------
1192set(handles.j1,'BackgroundColor',[0.7 0.7 0.7])
1193i1_Callback(hObject, eventdata, handles)
1194
1195%------------------------------------------------------------------------
1196function j2_Callback(hObject, eventdata, handles)
1197%------------------------------------------------------------------------
1198set(handles.j2,'BackgroundColor',[0.7 0.7 0.7])
1199i1_Callback(hObject, eventdata, handles)
1200
1201%------------------------------------------------------------------------
1202function slices_Callback(hObject, eventdata, handles)
1203%------------------------------------------------------------------------
1204if get(handles.slices,'Value')==1
1205    set(handles.slices,'BackgroundColor',[1 1 0])
1206    set(handles.num_NbSlice,'Visible','on')
1207    set(handles.z_text,'Visible','on')
1208    set(handles.z_index,'Visible','on')
1209    num_NbSlice_Callback(hObject, eventdata, handles)
1210else
1211    set(handles.num_NbSlice,'Visible','off')
1212    set(handles.slices,'BackgroundColor',[0.7 0.7 0.7])
1213    set(handles.z_text,'Visible','off')
1214    set(handles.z_index,'Visible','off')
1215    set(handles.masklevel,'Value',1)
1216    set(handles.masklevel,'String',{'1'})
1217end
1218
1219%------------------------------------------------------------------------
1220function num_NbSlice_Callback(hObject, eventdata, handles)
1221%------------------------------------------------------------------------
1222nb_slice_str=get(handles.num_NbSlice,'String');
1223if isequal(nb_slice_str,'volume')
1224    num=stra2num(get(handles.j1,'String'));
1225    last_j=get(handles.last_j,'String');
1226    nbslice=str2double(last_j{1});
1227else
1228    num=str2double(get(handles.i1,'String'));
1229    nbslice=str2double(get(handles.num_NbSlice,'String'));
1230end
1231z=mod(num-1,nbslice)+1;
1232set(handles.z_index,'String',num2str(z))
1233for ilist=1:nbslice
1234    list_index{ilist,1}=num2str(ilist);
1235end   
1236set(handles.masklevel,'String',list_index)
1237set(handles.masklevel,'Value',z)
1238
1239%------------------------------------------------------------------------
1240% --- Executes on button press in view_xml.
1241function view_xml_Callback(hObject, eventdata, handles)
1242%------------------------------------------------------------------------
1243%[FileName,RootPath,FileBase,FileIndices,FileExt]=read_file_boxes(handles);
1244 [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
1245FileBase=fullfile(RootPath,RootFile);
1246option=get(handles.view_xml,'String');
1247if isequal(option,'view .xml')
1248    FileXml=fullfile(RootPath,[SubDir '.xml']);
1249    if ~exist(FileXml,'file')% case of civ files , removes the extension for subdir
1250        FileXml=fullfile(RootPath,[regexprep(SubDir,'\..+$','') '.xml']);
1251    end
1252    heditxml=editxml(FileXml);
1253end
1254
1255%------------------------------------------------------------------------
1256% --- Executes on button press in CheckMask.
1257function CheckMask_Callback(hObject, eventdata, handles)
1258%------------------------------------------------------------------------
1259%case of view mask selection
1260if isequal(get(handles.CheckMask,'Value'),1)
1261     [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
1262     FileBase=fullfile(RootPath,RootFile);
1263    num_i1=stra2num(get(handles.i1,'String'));
1264    num_j1=stra2num(get(handles.j1,'String'));
1265    currentdir=pwd; 
1266    cd(RootPath);
1267    maskfiles=dir('*_*mask_*.png');%look for a mask file
1268    cd(currentdir);%come back to the working directory
1269    mdetect=0;
1270    if ~isempty(maskfiles)
1271        for ilist=1:length(maskfiles)
1272            maskname=maskfiles(ilist).name;% take the first mask file in the list
1273            [tild,tild,tild,tild,tild,tild,tild,MaskExt,Mask_NomType{ilist}]=fileparts_uvmat(maskname);
1274             [tild,Name]=fileparts(maskname);
1275            Namedouble=double(Name);
1276            val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
1277            ind_mask=findstr('mask',Name);
1278            i=ind_mask-1;
1279            while val(i)==0 && i>0
1280                i=i-1;
1281            end
1282            nbmask_str=str2num(Name(i+1:ind_mask-1));
1283            if ~isempty(nbmask_str)
1284                nbslice(ilist)=nbmask_str; % number of different masks (slices)
1285            end
1286        end
1287        if isequal(min(nbslice),max(nbslice))
1288            nbslice=nbslice(1);
1289        else
1290            msgbox_uvmat('ERROR','several inconsistent mask sets coexist in the current image directory')
1291            return
1292        end
1293        if ~isempty(nbslice) && Name(i)=='_'
1294            Mask.Base=[FileBase Name(i:ind_mask+3)];
1295            Mask.NbSlice=nbslice;
1296            num_i1=mod(num_i1-1,nbslice)+1;
1297            Mask.NomType=regexprep(Mask_NomType{1},'0','');%remove '0' in nom type for masks
1298            [RootPath,RootFile]=fileparts(Mask.Base);
1299            maskname=fullfile_uvmat(RootPath,'',RootFile,'.png',Mask.NomType,num_i1,[],num_j1);
1300            %maskname=name_generator(Mask.Base,num_i1,num_j1,'.png',Mask.NomType);%
1301            mdetect=exist(maskname,'file');
1302            if mdetect
1303                set(handles.num_NbSlice,'String',Name(i+1:ind_mask-1));
1304                set(handles.num_NbSlice,'BackgroundColor',[1 1 0])
1305                set(handles.CheckMask,'UserData',Mask);
1306                set(handles.CheckMask,'BackgroundColor',[1 1 0])
1307                if nbslice > 1
1308                    set(handles.slices,'value',1)
1309                    slices_Callback(hObject, eventdata, handles)
1310                end
1311            end
1312        end
1313    end
1314    errormsg=[];%default
1315    if mdetect==0
1316        [FileName, PathName, filterindex] = uigetfile( ...
1317            {'*.png', ' (*.png)';
1318            '*.png',  '.png files '; ...
1319            '*.*', 'All Files (*.*)'}, ...
1320            'Pick a mask file *.png',FileBase);
1321        maskname=fullfile(PathName,FileName);
1322        if ~exist(maskname,'file')
1323            errormsg='no file browsed';
1324        end
1325        [RootDir,SubDir,RootFile,tild,tild,tild,tild,tild,Mask.NomType]=fileparts_uvmat(maskname);
1326        Mask.Base=fullfile(RootDir,SubDir,RootFile);
1327        Mask.NbSlice=1;
1328        set(handles.CheckMask,'UserData',Mask);
1329        set(handles.CheckMask,'BackgroundColor',[1 1 0])
1330    end
1331    if isempty(errormsg)
1332        errormsg=update_mask(handles,num_i1,num_j1);
1333    end
1334    if ~isempty(errormsg)
1335            set(handles.CheckMask,'Value',0)
1336            set(handles.CheckMask,'BackgroundColor',[0.7 0.7 0.7])
1337     end
1338else % desactivate mask display
1339    MaskData=get(handles.CheckMask,'UserData');
1340    if isfield(MaskData,'maskhandle') && ishandle(MaskData.maskhandle)
1341          delete(MaskData.maskhandle)   
1342    end
1343    set(handles.CheckMask,'UserData',[])   
1344    UvData=get(handles.uvmat,'UserData');
1345    if isfield(UvData,'MaskName')
1346        UvData=rmfield(UvData,'MaskName');
1347        set(handles.uvmat,'UserData',UvData)
1348    end
1349    set(handles.CheckMask,'BackgroundColor',[0.7 0.7 0.7])
1350end
1351
1352%------------------------------------------------------------------------
1353function errormsg=update_mask(handles,num_i1,num_j1)
1354%------------------------------------------------------------------------
1355errormsg=[];%default
1356MaskData=get(handles.CheckMask,'UserData');
1357if isfield(MaskData,'maskhandle')&& ishandle(MaskData.maskhandle)
1358    uistack(MaskData.maskhandle,'top');
1359end
1360num_i1_mask=mod(num_i1-1,MaskData.NbSlice)+1;
1361[RootPath,RootFile]=fileparts(MaskData.Base);
1362MaskName=fullfile_uvmat(RootPath,'',RootFile,'.png',MaskData.NomType,num_i1_mask,[],num_j1);
1363UvData=get(handles.uvmat,'UserData');
1364%update mask image if the mask is new
1365if ~ (isfield(UvData,'MaskName') && isequal(UvData.MaskName,MaskName))
1366    UvData.MaskName=MaskName; %update the recorded name on UvData
1367    set(handles.uvmat,'UserData',UvData);
1368    if ~exist(MaskName,'file')
1369        if isfield(MaskData,'maskhandle')&& ishandle(MaskData.maskhandle)
1370            delete(MaskData.maskhandle)   
1371        end
1372    else
1373        %read mask image
1374        Mask.AName='image';
1375        Mask.A=imread(MaskName);
1376        npxy=size(Mask.A);
1377        test_error=0;
1378        if length(npxy)>2
1379            errormsg=[MaskName ' is not a grey scale image'];
1380            return
1381        elseif ~isa(Mask.A,'uint8')
1382            errormsg=[MaskName ' is not a 8 bit grey level image'];
1383            return
1384        end
1385        Mask.AX=[0.5 npxy(2)-0.5];
1386        Mask.AY=[npxy(1)-0.5 0.5 ];
1387        Mask.CoordUnit='pixel';
1388        if isequal(get(handles.slices,'Value'),1)
1389           NbSlice=str2num(get(handles.num_NbSlice,'String'));
1390           num_i1=str2num(get(handles.i1,'String'));
1391           Mask.ZIndex=mod(num_i1-1,NbSlice)+1;
1392        end
1393        %px to phys or other transform on field
1394         menu_transform=get(handles.transform_fct,'String');
1395        choice_value=get(handles.transform_fct,'Value');
1396        transform_name=menu_transform{choice_value};%name of the transform fct  given by the menu 'transform_fct'
1397        transform_list=get(handles.transform_fct,'UserData');
1398        transform=transform_list{choice_value};
1399        if  ~isequal(transform_name,'') && ~isequal(transform_name,'px')
1400            if isfield(UvData,'XmlData') && isfield(UvData.XmlData{1},'GeometryCalib')%use geometry calib recorded from the ImaDoc xml file as first priority
1401                Calib=UvData.XmlData{1}.GeometryCalib;
1402                Mask=transform(Mask,UvData.XmlData{1});
1403            end
1404        end
1405        flagmask=Mask.A < 200;
1406       
1407        %make brown color image
1408        imflag(:,:,1)=0.9*flagmask;
1409        imflag(:,:,2)=0.7*flagmask;
1410        imflag(:,:,3)=zeros(size(flagmask));
1411       
1412        %update mask image
1413        hmask=[]; %default
1414        if isfield(MaskData,'maskhandle')&& ishandle(MaskData.maskhandle)
1415            hmask=MaskData.maskhandle;
1416        end
1417        if ~isempty(hmask)
1418            set(hmask,'CData',imflag)   
1419            set(hmask,'AlphaData',flagmask*0.6)
1420            set(hmask,'XData',Mask.AX);
1421            set(hmask,'YData',Mask.AY);
1422%             uistack(hmask,'top')
1423        else
1424            axes(handles.axes3)
1425            hold on   
1426            size(flagmask)
1427           % MaskData.maskhandle=image(Mask.AX,Mask.AY,imflag,'Tag','mask','HitTest','off','AlphaData',0.6*flagmask);
1428            MaskData.maskhandle=image(Mask.AX,Mask.AY,imflag,'Tag','mask','HitTest','off','AlphaData',0.6*ones(size(flagmask)));
1429%             set(MaskData.maskhandle,'AlphaData',0.6*flagmask)
1430            set(handles.CheckMask,'UserData',MaskData)
1431        end
1432    end
1433end
1434
1435%------------------------------------------------------------------------
1436%------------------------------------------------------------------------
1437% III - MAIN REFRESH FUNCTIONS : 'FRAME PLOT'
1438%------------------------------------------------------------------------
1439
1440%------------------------------------------------------------------------
1441% --- Executes on button press in runplus: make one step forward and call
1442% --- run0. The step forward is along the fields series 1 or 2 depending on
1443% --- the scan_i and scan_j check box (exclusive each other)
1444function runplus_Callback(hObject, eventdata, handles)
1445%------------------------------------------------------------------------
1446set(handles.runplus,'BackgroundColor',[1 1 0])%paint the command button in yellow
1447drawnow
1448%TODO: introduce the option: increment ='*' to move to the next available view
1449increment=str2num(get(handles.increment_scan,'String')); %get the field increment d
1450% if isnan(increment)
1451%     set(handles.increment_scan,'String','1')%default value
1452%     increment=1;
1453% end
1454errormsg=runpm(hObject,eventdata,handles,increment);
1455if ~isempty(errormsg)
1456    msgbox_uvmat('ERROR',errormsg);
1457end
1458set(handles.runplus,'BackgroundColor',[1 0 0])%paint the command button back to red
1459
1460%------------------------------------------------------------------------
1461% --- Executes on button press in runmin: make one step backward and call
1462% --- run0. The step backward is along the fields series 1 or 2 depending on
1463% --- the scan_i and scan_j check box (exclusive each other)
1464function runmin_Callback(hObject, eventdata, handles)
1465%------------------------------------------------------------------------
1466set(handles.runmin,'BackgroundColor',[1 1 0])%paint the command button in yellow
1467drawnow
1468increment=-str2num(get(handles.increment_scan,'String')); %get the field increment d
1469% if isnan(increment)
1470%     set(handles.increment_scan,'String','1')%default value
1471%     increment=1;
1472% end
1473errormsg=runpm(hObject,eventdata,handles,increment);
1474if ~isempty(errormsg)
1475    msgbox_uvmat('ERROR',errormsg);
1476end
1477set(handles.runmin,'BackgroundColor',[1 0 0])%paint the command button back to red
1478
1479%------------------------------------------------------------------------
1480% -- Executes on button press in Movie: make a series of +> steps
1481function Movie_Callback(hObject, eventdata, handles)
1482%------------------------------------------------------------------------
1483set(handles.Movie,'BackgroundColor',[1 1 0])%paint the command button in yellow
1484drawnow
1485increment=str2num(get(handles.increment_scan,'String')); %get the field increment d
1486% if isnan(increment)
1487%     set(handles.increment_scan,'String','1')%default value
1488%     increment=1;
1489% end
1490set(handles.STOP,'Visible','on')
1491set(handles.speed,'Visible','on')
1492set(handles.speed_txt,'Visible','on')
1493set(handles.Movie,'BusyAction','queue')
1494UvData=get(handles.uvmat,'UserData');
1495
1496while get(handles.Movie,'Value')==1 && get(handles.speed,'Value')~=0 && isequal(get(handles.Movie,'BusyAction'),'queue') % enable STOP command
1497        errormsg=runpm(hObject,eventdata,handles,increment);
1498        if ~isempty(errormsg)
1499            set(handles.Movie,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1500            return
1501        end
1502        pause(1.02-get(handles.speed,'Value'))% wait for next image
1503end
1504if isfield(UvData,'aviobj') && ~isempty( UvData.aviobj),
1505    UvData.aviobj=close(UvData.aviobj);
1506   set(handles.uvmat,'UserData',UvData);
1507end
1508set(handles.Movie,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1509
1510%------------------------------------------------------------------------
1511% -- Executes on button press in Movie: make a series of <- steps
1512function MovieBackward_Callback(hObject, eventdata, handles)
1513%------------------------------------------------------------------------
1514set(handles.MovieBackward,'BackgroundColor',[1 1 0])%paint the command button in yellow
1515drawnow
1516increment=-str2num(get(handles.increment_scan,'String')); %get the field increment d
1517set(handles.STOP,'Visible','on')
1518set(handles.speed,'Visible','on')
1519set(handles.speed_txt,'Visible','on')
1520set(handles.MovieBackward,'BusyAction','queue')
1521UvData=get(handles.uvmat,'UserData');
1522
1523while get(handles.MovieBackward,'Value')==1 && get(handles.speed,'Value')~=0 && isequal(get(handles.MovieBackward,'BusyAction'),'queue') % enable STOP command
1524        errormsg=runpm(hObject,eventdata,handles,increment);
1525        if ~isempty(errormsg)
1526            set(handles.MovieBackward,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1527            return
1528        end
1529        pause(1.02-get(handles.speed,'Value'))% wait for next image
1530end
1531if isfield(UvData,'aviobj') && ~isempty( UvData.aviobj),
1532    UvData.aviobj=close(UvData.aviobj);
1533   set(handles.uvmat,'UserData',UvData);
1534end
1535set(handles.MovieBackward,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1536
1537%------------------------------------------------------------------------
1538function STOP_Callback(hObject, eventdata, handles)
1539%------------------------------------------------------------------------
1540set(handles.movie_pair,'BusyAction','Cancel')
1541set(handles.movie_pair,'value',0)
1542set(handles.Movie,'BusyAction','Cancel')
1543set(handles.MovieBackward,'BusyAction','Cancel')
1544set(handles.MenuExportMovie,'BusyAction','Cancel')
1545set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1546set(handles.Movie,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1547set(handles.MovieBackward,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1548
1549%------------------------------------------------------------------------
1550% --- function activated by runplus and run minus
1551function errormsg=runpm(hObject,eventdata,handles,increment)
1552%------------------------------------------------------------------------
1553errormsg='';%default
1554%% check for movie pair status
1555movie_status=get(handles.movie_pair,'Value');
1556if isequal(movie_status,1)
1557    STOP_Callback(hObject, eventdata, handles)%interrupt movie pair if active
1558end
1559
1560%% read the current input file name(s) and field indices
1561InputFile=read_GUI(handles.InputFile);
1562InputFile.RootFile=regexprep(InputFile.RootFile,'^[\\/]|[\\/]$','');%suppress possible / or \ separator at the beginning or the end of the string
1563InputFile.SubDir=regexprep(InputFile.SubDir,'^[\\/]|[\\/]$','');%suppress possible / or \ separator at the beginning or the end of the string
1564FileExt=InputFile.FileExt;
1565NomType=get(handles.NomType,'String');
1566i1=str2num(get(handles.i1,'String'));%read the field indices (for movie, it is not given by the file name)
1567i2=[];%default
1568if strcmp(get(handles.i2,'Visible'),'on')
1569    i2=str2num(get(handles.i2,'String'));
1570end
1571j1=[];
1572if strcmp(get(handles.j1,'Visible'),'on')
1573    j1=stra2num(get(handles.j1,'String'));
1574end
1575j2=j1;
1576if strcmp(get(handles.j2,'Visible'),'on')
1577    j2=stra2num(get(handles.j2,'String'));
1578end
1579sub_value= get(handles.SubField,'Value');
1580if sub_value % a second input file has been entered
1581     [InputFile.RootPath_1,InputFile.SubDir_1,InputFile.RootFile_1,InputFile.FileIndex_1,InputFile.FileExt_1,InputFile.NomType_1]=read_file_boxes_1(handles);   
1582    [tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(InputFile.FileIndex_1);
1583%     InputFile.NomType_1=get(handles.NomType_1,'String');
1584else
1585    filename_1=[];
1586end   
1587
1588%% increment (or decrement) the field indices and update the input filename(s)
1589CheckSearch=0;
1590if isempty(increment)
1591    CheckSearch=1;% search for the next available file
1592    set(handles.CheckFixPair,'Value',0)
1593end
1594CheckFixPair=get(handles.CheckFixPair,'Value')||(isempty(i2)&&isempty(j2));
1595
1596% the pair i1-i2 or j1-j2 is imposed (check box CheckFixPair selected)
1597if CheckFixPair
1598    if get(handles.scan_i,'Value')==1% case of scanning along index i
1599        i1=i1+increment;
1600        i2=i2+increment;
1601        if sub_value
1602            i1_1=i1_1+increment;
1603            i2_1=i2_1+increment;
1604        end
1605    else % case of scanning along index j (burst numbers)
1606        j1=j1+increment;
1607        j2=j2+increment;
1608        if sub_value
1609            j1_1=j1_1+increment;
1610            j2_1=j2_1+increment;
1611        end
1612    end
1613   
1614% the pair i1-i2 or j1-j2 is free (check box CheckFixPair not selected):
1615% the list of existing indices recorded in UvData is used
1616else
1617    UvData=get(handles.uvmat,'UserData');
1618    ref_i=i1;
1619    if ~isempty(i2)
1620        ref_i=floor((i1+i2)/2);% current reference index i
1621    end
1622    ref_j=1;
1623    if ~isempty(j1)
1624        ref_j=j1;
1625        if ~isempty(j2)
1626            ref_j=floor((j1+j2)/2);% current reference index j
1627        end
1628    end
1629    if ~isempty(increment)
1630        if get(handles.scan_i,'Value')==1% case of scanning along index i
1631            ref_i=ref_i+increment;% increment the current reference index i
1632        else % case of scanning along index j (burst numbers)
1633            ref_j=ref_j+increment;% increment the current reference index j if scan_j option is used
1634        end
1635    else % free increment
1636        if isequal(get(handles.runplus,'BackgroundColor'),[1 1 0])% if runplus is activated
1637            step=1;
1638        else
1639            step=-1;
1640        end
1641        if get(handles.scan_i,'Value')==1% case of scanning along index i
1642            ref_i=ref_i+step;
1643            while ref_i>=0  && size(UvData.i1_series{1},1)>=ref_i+1 && UvData.i1_series{1}(ref_i+1,ref_j+1,1)==0
1644                ref_i=ref_i+step;
1645            end
1646        else % case of scanning along index j (burst numbers)
1647            ref_j=ref_j+step;
1648            while ref_j>=0  && size(UvData.i1_series{1},2)>=ref_j+1 && UvData.i1_series{1}(ref_i+1,ref_j+1,1)==0
1649                ref_j=ref_j+step;
1650            end
1651        end
1652    end
1653    if ref_i<0
1654        errormsg='minimum i index reached';
1655    elseif ref_j<0
1656        errormsg='minimum j index reached';
1657    elseif ref_i+1>size(UvData.i1_series{1},1)
1658        errormsg='maximum i index reached';
1659    elseif ref_j+1>size(UvData.i1_series{1},2)
1660        errormsg='maximum j index reached';
1661    end
1662    if ~isempty(errormsg)
1663        return
1664    end
1665    i1_subseries=UvData.i1_series{1}(ref_i+1,ref_j+1,:);
1666    i1_subseries=i1_subseries(i1_subseries>0);
1667    if isempty(i1_subseries)
1668        errormsg='no next file';
1669        return
1670    else
1671        i1=i1_subseries(end);
1672    end
1673    if ~isempty(UvData.i2_series{1})
1674        i2_subseries=UvData.i2_series{1}(ref_i+1,ref_j+1,:);
1675        i2_subseries=i2_subseries(i2_subseries>0);
1676        i2=i2_subseries(end);
1677    end
1678    if ~isempty(UvData.j1_series{1})
1679        j1_subseries=UvData.j1_series{1}(ref_i+1,ref_j+1,:);
1680        j1_subseries=j1_subseries(j1_subseries>0);
1681        j1=j1_subseries(end);
1682    end
1683    if ~isempty(UvData.j2_series{1})
1684        j2_subseries=UvData.j2_series{1}(ref_i+1,ref_j+1,:);
1685        j2_subseries=j2_subseries(j2_subseries>0);
1686        j2=j2_subseries(end);
1687    end 
1688    % case of a second file series
1689    if numel(UvData.i1_series)>=2
1690        i1_subseries=UvData.i1_series{2}(ref_i+1,ref_j+1,:);
1691        i1_subseries=i1_subseries(i1_subseries>0);
1692        i1_1=i1_subseries(end);
1693        if ~isempty(UvData.i2_series{2})
1694            i2_subseries=UvData.i2_series{2}(ref_i+1,ref_j+1,:);
1695            i2_subseries=i2_subseries(i2_subseries>0);
1696            i2_1=i2_subseries(end);
1697        end
1698        if ~isempty(UvData.j1_series{2})
1699            j1_subseries=UvData.j1_series{2}(ref_i+1,ref_j+1,:);
1700            j1_subseries=j1_subseries(j1_subseries>0);
1701            j1_1=j1_subseries(end);
1702        end
1703        if ~isempty(UvData.j2_series{2})
1704            j2_subseries=UvData.j2_series{2}(ref_i+1,ref_j+1,:);
1705            j2_subseries=j2_subseries(j2_subseries>0);
1706            j2_1=j2_subseries(end);
1707        end
1708    end
1709end
1710filename=fullfile_uvmat(InputFile.RootPath,InputFile.SubDir,InputFile.RootFile,FileExt,NomType,i1,i2,j1,j2);
1711if sub_value
1712    filename_1=fullfile_uvmat(InputFile.RootPath_1,InputFile.SubDir_1,InputFile.RootFile_1,InputFile.FileExt_1,InputFile.NomType_1,i1_1,i2_1,j1_1,j2_1);
1713end
1714
1715%% refresh plots
1716errormsg=refresh_field(handles,filename,filename_1,i1,i2,j1,j2);
1717
1718%% update the index counters if the index move is successfull
1719if isempty(errormsg)
1720    set(handles.i1,'String',num2stra(i1,NomType,1));
1721    if isequal(i2,i1)
1722        set(handles.i2,'String','');
1723    else
1724        set(handles.i2,'String',num2stra(i2,NomType,1));
1725    end
1726    set(handles.j1,'String',num2stra(j1,NomType,2));
1727    if isequal(j2,j1)
1728        set(handles.j2,'String','');
1729    else
1730        set(handles.j2,'String',num2stra(j2,NomType,2));
1731    end
1732    indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,j2);
1733    set(handles.FileIndex,'String',indices);
1734    if ~isempty(filename_1)
1735        indices_1=fullfile_uvmat('','','','',InputFile.NomType_1,i1_1,i2_1,j1_1,j2_1);
1736        set(handles.FileIndex_1,'String',indices_1);
1737    end
1738    if isequal(movie_status,1)
1739        set(handles.movie_pair,'Value',1)
1740        movie_pair_Callback(hObject, eventdata, handles); %reactivate moviepair if it was activated
1741    end
1742end
1743
1744%------------------------------------------------------------------------
1745% --- Executes on button press in movie_pair: create an alternating movie with two view
1746function movie_pair_Callback(hObject, eventdata, handles)
1747%------------------------------------------------------------------------
1748%% stop movie action if the movie_pair button is off
1749if ~get(handles.movie_pair,'value')
1750    set(handles.movie_pair,'BusyAction','Cancel')%stop movie pair if button is 'off'
1751    set(handles.i2,'String','')
1752    set(handles.j2,'String','')
1753    return
1754else
1755    set(handles.movie_pair,'BusyAction','queue')
1756end
1757
1758%% initialisation
1759set(handles.movie_pair,'BackgroundColor',[1 1 0])%paint the command button in yellow
1760drawnow
1761list_fields=get(handles.Fields,'String');% list menu fields
1762index_fields=get(handles.Fields,'Value');% selected string index
1763FieldName=list_fields{index_fields}; % selected field
1764UvData=get(handles.uvmat,'UserData');
1765if isequal(FieldName,'image')
1766    test_1=0;
1767    [RootPath,SubDir,RootFile,FileIndices,Ext]=read_file_boxes(handles);
1768    NomType=get(handles.NomType,'String');
1769else
1770    list_fields=get(handles.Fields_1,'String');% list menu fields
1771    index_fields=get(handles.Fields_1,'Value');% selected string index
1772    FieldName=list_fields{index_fields}; % selected field
1773    if isequal(FieldName,'image')
1774        test_1=1;
1775        [RootPath,tild,RootFile,FileIndex_1,Ext,NomType]=read_file_boxes_1(handles);
1776    else
1777        msgbox_uvmat('ERROR','an image or movie must be first introduced as input')
1778        set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1779        set(handles.movie_pair,'Value',0)
1780        return
1781    end
1782end
1783num_i1=str2num(get(handles.i1,'String'));
1784num_j1=stra2num(get(handles.j1,'String'));
1785num_i2=str2num(get(handles.i2,'String'));
1786num_j2=stra2num(get(handles.j2,'String'));
1787if isempty(num_j2)
1788    if isempty(num_i2)   
1789        msgbox_uvmat('ERROR', 'a second image index i2 or j2 is needed to show the pair as a movie')
1790        set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1791         set(handles.movie_pair,'Value',0)
1792        return
1793    else
1794        num_j2=num_j1;%repeat the index i1 by default
1795    end
1796end
1797if isempty(num_i2)
1798    num_i2=num_i1;%repeat the index i1 by default
1799end
1800% imaname_1=name_generator(filebase,num_i2,num_j2,Ext,NomType);
1801imaname_1=fullfile_uvmat(RootPath,SubDir,RootFile,Ext,NomType,num_i2,[],num_j2);
1802if ~exist(imaname_1,'file')
1803      msgbox_uvmat('ERROR',['second input open (-)  ' imaname_1 ' not found']);
1804      set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1805       set(handles.movie_pair,'Value',0)
1806      return
1807end
1808
1809%% read the second image
1810Field.AName='image';
1811if test_1
1812    Field_a=UvData.Field_1;
1813else
1814    Field_a=UvData.Field;
1815end
1816Field_b.AX=Field_a.AX;
1817Field_b.AY=Field_a.AY;
1818% z index
1819nbslice=str2double(get(handles.num_NbSlice,'String'));
1820if ~isempty(nbslice)
1821    Field_b.ZIndex=mod(num_i2-1,nbslice)+1;
1822end
1823Field_b.CoordUnit='pixel';
1824
1825%% determine the input file type
1826if (test_1 && isfield(UvData,'MovieObject')&& numel(UvData.MovieObject>=2))||(~test_1 && ~isempty(UvData.MovieObject{1}))
1827    FileType='movie';
1828elseif isequal(lower(Ext),'.avi')
1829    FileType='avi';
1830elseif isequal(lower(Ext),'.vol')
1831    FileType='vol';
1832else
1833   form=imformats(Ext(2:end));
1834   if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
1835       if isequal(NomType,'*');
1836           FileType='multimage';
1837       else
1838           FileType='image';
1839       end
1840   end
1841end
1842switch FileType
1843        case 'movie'
1844            if test_1
1845                Field_b.A=read(UvData.MovieObject{2},num_i2);
1846            else
1847                Field_b.A=read(UvData.MovieObject{1},num_i2);
1848            end
1849        case 'avi'
1850            mov=aviread(imaname_1,num_i2);
1851            Field_b.A=frame2im(mov(1));
1852        case 'vol'
1853            Field_b.A=imread(imaname_1);
1854        case 'multimage'
1855            Field_b.A=imread(imaname_1,num_i2);
1856        case 'image'
1857            Field_b.A=imread(imaname_1);
1858end
1859if get(handles.slices,'Value')
1860    Field.ZIndex=str2double(get(handles.z_index,'String'));
1861end
1862
1863%px to phys or other transform on field
1864menu_transform=get(handles.transform_fct,'String');
1865choice_value=get(handles.transform_fct,'Value');
1866transform_name=menu_transform{choice_value};%name of the transform fct  given by the menu 'transform_fct'
1867transform_list=get(handles.transform_fct,'UserData');
1868transform=transform_list{choice_value};
1869if  ~isequal(transform_name,'') && ~isequal(transform_name,'px')
1870    if test_1 && isfield(UvData,'XmlData') && numel(UvData.XmlData)==2 && isfield(UvData.XmlData{2},'GeometryCalib')%use geometry calib recorded from the ImaDoc xml file as first priority
1871        Field_a=transform(Field_a,UvData.XmlData{2});%the first field has been stored without transform
1872        Field_b=transform(Field_b,UvData.XmlData{2});
1873    elseif ~test_1 && isfield(UvData,'XmlData') && isfield(UvData.XmlData{1},'GeometryCalib')%use geometry calib
1874        Field_b=transform(Field_b,UvData.XmlData{1});
1875    end
1876end
1877
1878 % make movie until movie speed is set to 0 or STOP is activated
1879hima=findobj(handles.axes3,'Tag','ima');% %handles.axes3 =main plotting window (A GENERALISER)
1880set(handles.STOP,'Visible','on')
1881set(handles.speed,'Visible','on')
1882set(handles.speed_txt,'Visible','on')
1883while get(handles.speed,'Value')~=0 && isequal(get(handles.movie_pair,'BusyAction'),'queue')%isequal(get(handles.run0,'BusyAction'),'queue'); % enable STOP command
1884    % read and plot the series of images in non erase mode
1885    set(hima,'CData',Field_b.A);
1886    pause(1.02-get(handles.speed,'Value'));% wait for next image
1887    set(hima,'CData',Field_a.A);
1888    pause(1.02-get(handles.speed,'Value'));% wait for next image
1889end
1890set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1891 set(handles.movie_pair,'Value',0)
1892
1893%------------------------------------------------------------------------
1894% --- Executes on button press in run0.
1895function run0_Callback(hObject, eventdata, handles)
1896%------------------------------------------------------------------------
1897set(handles.run0,'BackgroundColor',[1 1 0])%paint the command button in yellow
1898drawnow
1899[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
1900filename=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
1901filename_1=[];%default
1902if get(handles.SubField,'Value')
1903    [RootPath_1,SubDir_1,RootFile_1,FileIndices_1,FileExt_1]=read_file_boxes_1(handles);
1904    filename_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndices_1 FileExt_1];
1905end
1906num_i1=stra2num(get(handles.i1,'String'));
1907num_i2=stra2num(get(handles.i2,'String'));
1908num_j1=stra2num(get(handles.j1,'String'));
1909num_j2=stra2num(get(handles.j2,'String'));
1910
1911errormsg=refresh_field(handles,filename,filename_1,num_i1,num_i2,num_j1,num_j2);
1912
1913if ~isempty(errormsg)
1914      msgbox_uvmat('ERROR',errormsg);
1915else
1916    set(handles.i1,'BackgroundColor',[1 1 1])
1917    set(handles.i2,'BackgroundColor',[1 1 1])
1918    set(handles.j1,'BackgroundColor',[1 1 1])
1919    set(handles.j2,'BackgroundColor',[1 1 1])
1920    set(handles.FileIndex,'BackgroundColor',[1 1 1])
1921    set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
1922end   
1923set(handles.run0,'BackgroundColor',[1 0 0])
1924
1925
1926%------------------------------------------------------------------------
1927% --- read the input files and refresh all the plots, including projection.
1928% OUTPUT:
1929%  errormsg: error message char string  =[] by default
1930% INPUT:
1931% filename: first input file (=[] in the absence of input file)
1932% filename_1: second input file (=[] in the asbsenc of secodn input file)
1933% num_i1,num_i2,num_j1,num_j2; frame indices
1934% Field: structure describing an optional input field (then replace the input file)
1935
1936function errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2,Field)
1937%------------------------------------------------------------------------
1938
1939%% initialisation
1940abstime=[];
1941abstime_1=[];
1942dt=[];
1943if ~exist('Field','var')
1944    Field={};
1945end
1946UvData=get(handles.uvmat,'UserData');
1947if ishandle(handles.UVMAT_title) %remove title panel on uvmat
1948    delete(handles.UVMAT_title)
1949end
1950
1951%% determine the main input file information for action
1952FileType=[];%default
1953if ~exist(FileName,'file')
1954    errormsg=['input file ' FileName ' does not exist'];
1955    return
1956end
1957NomType=get(handles.NomType,'String');
1958NomType_1='';
1959if strcmp(get(handles.NomType_1,'Visible'),'on')
1960    NomType_1=get(handles.NomType_1,'String');
1961end
1962% NomType=get(handles.FileIndex,'UserData');
1963%update the z position index
1964nbslice_str=get(handles.num_NbSlice,'String');
1965if isequal(nbslice_str,'volume')%NOT USED
1966    z_index=num_j1;
1967    set(handles.z_index,'String',num2str(z_index))
1968else
1969    nbslice=str2num(nbslice_str);
1970    z_index=mod(num_i1-1,nbslice)+1;
1971    set(handles.z_index,'String',num2str(z_index))
1972end
1973% refresh menu for save_mask if relevant
1974masknumber=get(handles.masklevel,'String');
1975if length(masknumber)>=z_index
1976    set(handles.masklevel,'Value',z_index)
1977end
1978
1979%% read the first input field if a filename has been introduced
1980ParamIn.ColorVar='';%default variable name for vector color
1981frame_index=1;%default
1982if ~isempty(FileName)
1983    FieldName='';%default
1984    VelType='';%default
1985%     FileType=UvData.FileType{1};
1986    switch UvData.FileType{1}
1987        case {'civx','civdata','netcdf'};
1988            list_fields=get(handles.Fields,'String');% list menu fields
1989  %          index_fields=get(handles.Fields,'Value');% selected string index
1990            FieldName= list_fields{get(handles.Fields,'Value')}; % selected field
1991            if ~strcmp(FieldName,'get_field...')
1992                if get(handles.FixVelType,'Value')
1993                    VelTypeList=get(handles.VelType,'String');
1994                    VelType=VelTypeList{get(handles.VelType,'Value')};
1995                end
1996            end
1997            if strcmp(FieldName,'velocity')
1998                list_code=get(handles.ColorCode,'String');% list menu fields
1999                index_code=get(handles.ColorCode,'Value');% selected string index
2000                if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2001                    list_code=get(handles.ColorScalar,'String');% list menu fields
2002                    index_code=get(handles.ColorScalar,'Value');% selected string index
2003                    ParamIn.ColorVar= list_code{index_code}; % selected field
2004                end
2005            end
2006        case {'video','mmreader'}
2007            ParamIn=UvData.MovieObject{1};     
2008            if ~strcmp(NomType,'*')
2009                frame_index=num_j1;%frame index for movies or multimage
2010            else
2011                frame_index=num_i1;
2012            end
2013        case 'multimage'
2014            if ~strcmp(NomType,'*')
2015                frame_index=num_j1;%frame index for movies or multimage
2016            else
2017                frame_index=num_i1;
2018            end
2019        case 'vol' %TODO: update
2020            if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2021                ParamIn.Npy=UvData.XmlData.Npy;
2022                ParamIn.Npx=UvData.XmlData.Npx;
2023            else           
2024                errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2025                return
2026            end
2027    end
2028    if isstruct (ParamIn)
2029    ParamIn.FieldName=FieldName;
2030    ParamIn.VelType=VelType;
2031    ParamIn.GUIName='get_field';
2032    end
2033    [Field{1},ParamOut,errormsg] = read_field(FileName,UvData.FileType{1},ParamIn,frame_index);
2034    if ~isempty(errormsg)
2035        errormsg=['error in reading ' FileName ': ' errormsg];
2036        return
2037    end 
2038    if isfield(ParamOut,'Npx')&& isfield(ParamOut,'Npy')
2039        set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2040        set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2041    end
2042    if isfield(ParamOut,'TimeIndex')% case of time obtained from get_field
2043        set(handles.i1,'String',num2str(ParamOut.TimeIndex))
2044    end
2045    if isfield(ParamOut,'TimeValue')
2046        Field{1}.Time=ParamOut.TimeValue;% case of time obtained from get_field
2047    end
2048end
2049
2050%% choose and read a second field FileName_1 if defined
2051VelType_1=[];%default
2052FieldName_1=[];
2053ParamIn_1=[];
2054ParamOut_1=[];
2055frame_index_1=1;
2056if ~isempty(FileName_1)
2057    if ~exist(FileName_1,'file')
2058        errormsg=['second file ' FileName_1 ' does not exist'];
2059        return
2060    end
2061    Name=FileName_1;
2062    switch UvData.FileType{2}
2063        case {'civx','civdata','netcdf'};
2064            list_fields=get(handles.Fields_1,'String');% list menu fields
2065            FieldName_1= list_fields{get(handles.Fields_1,'Value')}; % selected field
2066            if ~strcmp(FieldName,'get_field...')
2067                if get(handles.FixVelType,'Value')
2068                    VelTypeList=get(handles.VelType_1,'String');
2069                    VelType_1=VelTypeList{get(handles.VelType_1,'Value')};% read the velocity type.
2070                end
2071            end
2072            if strcmp(FieldName_1,'velocity')&& strcmp(get(handles.ColorCode,'Visible'),'on')
2073                list_code=get(handles.ColorCode,'String');% list menu fields
2074                index_code=get(handles.ColorCode,'Value');% selected string index
2075                if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2076                    list_code=get(handles.ColorScalar,'String');% list menu fields
2077                    index_code=get(handles.ColorScalar,'Value');% selected string index
2078                    ParamIn_1.ColorVar= list_code{index_code}; % selected field for vector color display                 
2079                end
2080            end
2081        case {'video','mmreader'}
2082            ParamIn_1=UvData.MovieObject{2};
2083                        if ~strcmp(NomType_1,'*')
2084                frame_index_1=num_j1;%frame index for movies or multimage
2085            else
2086                frame_index_1=num_i1;
2087            end 
2088         case 'multimage'
2089            if ~strcmp(NomType_1,'*')
2090                frame_index_1=num_j1;%frame index for movies or multimage
2091            else
2092                frame_index_1=num_i1;
2093            end   
2094        case 'vol' %TODO: update
2095            if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2096                ParamIn_1.Npy=UvData.XmlData.Npy;
2097                ParamIn_1.Npx=UvData.XmlData.Npx;
2098            else
2099                errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2100                return
2101            end
2102    end
2103    if isequal(get(handles.NomType_1,'Visible'),'on')
2104    NomType_1=get(handles.NomType_1,'String');
2105    else
2106        NomType_1=get(handles.NomType,'String');
2107    end
2108    test_keepdata_1=0;% test for keeping the previous stored data if the input files are unchanged
2109    if ~isequal(NomType_1,'*')%in case of a series of files (not avi movie)
2110        if isfield(UvData,'FileName_1')%&& isfield(UvData,'VelType_1') && isfield(UvData,'FieldName_1')
2111            test_keepdata_1= strcmp(FileName_1,UvData.FileName_1) ;%&& strcmp(FieldName_1,UvData.FieldName_1);
2112        end
2113    end
2114    if test_keepdata_1
2115        Field{2}=UvData.Field_1;% keep the stored field
2116        ParamOut_1=UvData.ParamOut_1;
2117    else
2118        if isempty(ParamIn_1) || isstruct(ParamIn_1)
2119        ParamIn_1.FieldName=FieldName_1;
2120        ParamIn_1.VelType=VelType_1;
2121        ParamIn_1.GUIName='get_field_1';
2122        end
2123        [Field{2},ParamOut_1,errormsg] = read_field(Name,UvData.FileType{2},ParamIn_1,frame_index_1);
2124        if ~isempty(errormsg)
2125            errormsg=['error in reading ' FieldName_1 ' in ' FileName_1 ': ' errormsg];
2126            return
2127        end
2128    end
2129end
2130
2131%% update uvmat interface
2132if isfield(ParamOut,'Npx')
2133    set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2134    set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2135elseif isfield(ParamOut_1,'Npx')
2136    set(handles.num_Npx,'String',num2str(ParamOut_1.Npx));% display image size on the interface
2137    set(handles.num_Npy,'String',num2str(ParamOut_1.Npy));
2138end
2139
2140%% update the display menu for the first velocity type (first menuline)
2141test_veltype=0;
2142% if ~isequal(FileType,'netcdf')|| isequal(FieldName,'get_field...')
2143if (strcmp(UvData.FileType{1},'civx')||strcmp(UvData.FileType{1},'civdata'))&& ~strcmp(FieldName,'get_field...')
2144    test_veltype=1;
2145    set(handles.VelType,'Visible','on')
2146    set(handles.VelType_1,'Visible','on')
2147    set(handles.FixVelType,'Visible','on')
2148    menu=set_veltype_display(ParamOut.CivStage,UvData.FileType{1});
2149    index_menu=strcmp(ParamOut.VelType,menu);%look for VelType in  the menu
2150    index_val=find(index_menu,1);
2151    if isempty(index_val)
2152        index_val=1;
2153    end
2154    set(handles.VelType,'Value',index_val)
2155    if ~get(handles.SubField,'value')
2156        set(handles.VelType,'String',menu)
2157        set(handles.VelType_1,'Value',1)
2158        set(handles.VelType_1,'String',[{''};menu])
2159    end
2160else
2161    set(handles.VelType,'Visible','off')
2162end
2163% display the Fields menu from the input file and pick the selected one:
2164if isstruct(ParamOut)
2165field_index=strcmp(ParamOut.FieldName,ParamOut.FieldList);
2166set(handles.Fields,'String',ParamOut.FieldList); %update the field menu
2167set(handles.Fields,'Value',find(field_index,1))
2168end
2169
2170%% update the display menu for the second velocity type (second menuline)
2171test_veltype_1=0;
2172if isempty(FileName_1)
2173    set(handles.Fields_1,'Value',1); %update the field menu
2174    if isstruct(ParamOut)
2175    set(handles.Fields_1,'String',[{''};ParamOut.FieldList]); %update the field menu
2176    end
2177elseif ~test_keepdata_1
2178    if (~strcmp(UvData.FileType{2},'netcdf')&&~strcmp(UvData.FileType{2},'civdata')&&~strcmp(UvData.FileType{2},'civx'))|| isequal(FieldName_1,'get_field...')
2179        set(handles.VelType_1,'Visible','off')
2180    else
2181        test_veltype_1=1;
2182        set(handles.VelType_1,'Visible','on')
2183        menu=set_veltype_display(ParamOut_1.CivStage);
2184        index_menu=strcmp(ParamOut_1.VelType,menu);
2185        set(handles.VelType_1,'Value',1+find(index_menu,1))
2186        set(handles.VelType_1,'String',[{''};menu])
2187    end
2188    % update the second field menu: the same quantity
2189    if isstruct(ParamOut_1)
2190    set(handles.Fields_1,'String',[{''};ParamOut_1.FieldList]); %update the field menu
2191    % display the Fields menu from the input file and pick the selected one:
2192    field_index=strcmp(ParamOut_1.FieldName,ParamOut_1.FieldList);
2193    set(handles.Fields_1,'Value',find(field_index,1)+1) 
2194    end
2195   
2196end
2197if test_veltype||test_veltype_1
2198     set(handles.FixVelType,'Visible','on')
2199else
2200     set(handles.FixVelType,'Visible','off')
2201end
2202
2203% field_index=strcmp(ParamOut_1.FieldName,ParamOut_1.FieldList);
2204% set(handles.Fields,'String',ParamOut.FieldList); %update the field menu
2205% set(handles.Fields,'Value',find(field_index,1))
2206   
2207%% introduce w as background image by default for a new series (only for nbdim=2)
2208if ~isfield(UvData,'NewSeries')
2209    UvData.NewSeries=1;
2210end
2211%put W as background image by default if NbDim=2:
2212if  UvData.NewSeries && isequal(get(handles.SubField,'Value'),0) && isfield(Field{1},'W') && ~isempty(Field{1}.W) && ~isequal(Field{1}.NbDim,3);
2213        set(handles.SubField,'Value',1);
2214        set(handles.RootPath_1,'String','"')
2215        set(handles.RootFile_1,'String','"')
2216        set(handles.SubDir_1,'String','"');
2217         indices=fullfile_uvmat('','','','',NomType,num_i1,num_i2,num_j1,num_j2);
2218        set(handles.FileIndex_1,'String',indices)
2219        set(handles.FileExt_1,'String','"');
2220        set(handles.Fields_1,'Visible','on');
2221        set(handles.Fields_1,'Visible','on');
2222        set(handles.RootPath_1,'Visible','on')
2223        set(handles.RootFile_1,'Visible','on')
2224        set(handles.SubDir_1,'Visible','on');
2225        set(handles.FileIndex_1,'Visible','on');
2226        set(handles.FileExt_1,'Visible','on');
2227        set(handles.Fields_1,'Visible','on');
2228        Field{1}.AName='w';
2229end           
2230
2231%% display time
2232testimedoc=0;
2233TimeUnit='';
2234if isfield(Field{1},'Time')
2235    abstime=Field{1}.Time;%time read from the netcdf input file
2236end
2237if numel(Field)==2 && isfield(Field{2},'Time')
2238    abstime_1=Field{2}.Time;%time read from the netcdf input file
2239end
2240if isfield(Field{1},'Dt')
2241    dt=Field{1}.Dt;%dt read from the netcdf input file
2242    if isfield(Field{1},'TimeUnit')
2243       TimeUnit=Field{1}.TimeUnit;
2244    end
2245elseif numel(Field)==2 && isfield(Field{2},'Dt')%dt obtained from the second field if not defined in the first
2246    dt=Field{2}.Dt;%dt read from the netcdf input file
2247    if isfield(Field{2},'TimeUnit')
2248       TimeUnit=Field{2}.TimeUnit;
2249    end
2250end
2251% time from xml file overset previous result
2252if isfield(UvData,'XmlData') && isfield(UvData.XmlData{1},'Time')
2253    if isempty(num_i2)||isnan(num_i2)
2254        num_i2=num_i1;
2255    end
2256    if isempty(num_j1)||isnan(num_j1)
2257        num_j1=1;
2258    end
2259    if isempty(num_j2)||isnan(num_j2)
2260        num_j2=num_j1;
2261    end
2262    siz=size(UvData.XmlData{1}.Time);
2263    if ~isempty(num_i1)&& ~isempty(num_i2)&&siz(1)>=max(num_i1,num_i2) && siz(2)>=max(num_j1,num_j2)
2264        abstime=(UvData.XmlData{1}.Time(num_i1,num_j1)+UvData.XmlData{1}.Time(num_i2,num_j2))/2;%overset the time read from files
2265        dt=(UvData.XmlData{1}.Time(num_i2,num_j2)-UvData.XmlData{1}.Time(num_i1,num_j1));
2266        Field{1}.Dt=dt;
2267        if isfield(UvData.XmlData{1},'TimeUnit')
2268            TimeUnit=UvData.XmlData{1}.TimeUnit;
2269        end
2270    end
2271    if numel(UvData.XmlData)==2
2272        [tild,tild,tild,num_i1,num_i2,num_j1,num_j2]=fileparts_uvmat(['xx' get(handles.FileIndex_1,'String') get(handles.FileExt_1,'String')]);
2273        if isempty(num_i2)
2274            num_i2=num_i1;
2275        end
2276        if isempty(num_j1)
2277            num_j1=1;
2278        end
2279        if isempty(num_j2)
2280            num_j2=num_j1;
2281        end
2282        siz=size(UvData.XmlData{2}.Time);
2283        if ~isempty(num_i1) && siz(1)>=max(num_i1,num_i2) && siz(2)>=max(num_j1,num_j2)
2284            abstime_1=(UvData.XmlData{2}.Time(num_i1,num_j1)+UvData.XmlData{2}.Time(num_i2,num_j2))/2;%overset the time read from files
2285            Field{2}.Dt=(UvData.XmlData{2}.Time(num_i2,num_j2)-UvData.XmlData{2}.Time(num_i1,num_j1));
2286        end
2287    end
2288end
2289if ~isequal(numel(abstime),1)
2290    abstime=[];
2291end
2292if ~isequal(numel(abstime_1),1)
2293      abstime_1=[];
2294end 
2295set(handles.abs_time,'String',num2str(abstime,5))
2296set(handles.abs_time_1,'String',num2str(abstime_1,5))
2297% if testimedoc && isfield(UvData,'dt')
2298%     dt=UvData.dt;
2299% end
2300if isempty(dt)||isequal(dt,0)
2301    set(handles.Dt_txt,'String','')
2302else
2303    if  isempty(TimeUnit)
2304        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  10^(-3)'] )
2305    else
2306        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  m' TimeUnit] )
2307    end
2308end
2309
2310
2311%% store the current open names, fields and vel types in uvmat interface
2312UvData.FileName_1=FileName_1;
2313
2314%% apply coordinate transform or other user fct
2315XmlData=[];%default
2316XmlData_1=[];%default
2317if isfield(UvData,'XmlData')%use geometry calib recorded from the ImaDoc xml file as first priority
2318    XmlData=UvData.XmlData{1};
2319    if numel(UvData.XmlData)==2
2320        XmlData_1=UvData.XmlData{2};
2321    end
2322end
2323choice_value=get(handles.transform_fct,'Value');
2324transform_list=get(handles.transform_fct,'UserData');
2325transform=transform_list{choice_value};%selected function handles
2326% z index
2327if ~isempty(FileName)
2328    Field{1}.ZIndex=z_index;
2329end
2330if ~isempty(transform)
2331    if length(Field)>=2
2332        Field{2}.ZIndex=z_index;
2333        [Field{1},Field{2}]=transform(Field{1},XmlData,Field{2},XmlData_1);
2334        if isempty(Field{2})
2335            Field(2)=[];
2336        end
2337    else
2338        Field{1}=transform(Field{1},XmlData);
2339    end
2340end   
2341    %% check whether tps is needed, then calculate tps coefficients if needed
2342check_proj_tps=0;
2343if isfield(UvData,'Object')&& (strcmp(UvData.FileType{1},'civdata')||strcmp(UvData.FileType{1},'civx'))
2344    for iobj=1:numel(UvData.Object)
2345        if isfield(UvData.Object{iobj},'ProjMode')&& strcmp(UvData.Object{iobj}.ProjMode,'filter')
2346            check_proj_tps=1;
2347            break
2348        end
2349    end
2350end
2351check_tps=0;         
2352if strcmp(UvData.FileType{1},'civdata')&&~strcmp(ParamOut.FieldName,'velocity')&&~strcmp(ParamOut.FieldName,'get_field...')
2353       check_tps=1;
2354end
2355if (check_tps ||check_proj_tps)&&~isfield(Field{1},'Coord_tps')
2356    SubDomain=1000; %default, estimated nbre of vectors in a subdomain used for tps
2357    if isfield(Field{1},'SubDomain')
2358        SubDomain=Field{1}.SubDomain;%
2359    end
2360    [Field{1}.SubRange,Field{1}.NbSites,Field{1}.Coord_tps,Field{1}.U_tps,Field{1}.V_tps,tild,U_smooth,V_smooth,W_smooth,FF] =...
2361       filter_tps([Field{1}.X(Field{1}.FF==0) Field{1}.Y(Field{1}.FF==0)],Field{1}.U(Field{1}.FF==0),Field{1}.V(Field{1}.FF==0),[],SubDomain,0);
2362    nbvar=numel(Field{1}.ListVarName);
2363    Field{1}.ListVarName=[Field{1}.ListVarName {'SubRange','NbSites','Coord_tps','U_tps','V_tps'}];
2364    Field{1}.VarDimName=[Field{1}.VarDimName {{'nb_coord','nb_bounds','nb_subdomain'},{'nb_subdomain'},...
2365        {'nb_tps','nb_coord','nb_subdomain'},{'nb_tps','nb_subdomain'},{'nb_tps','nb_subdomain'}}];
2366    Field{1}.VarAttribute{nbvar+3}.Role='coord_tps';
2367    Field{1}.VarAttribute{nbvar+4}.Role='vector_x_tps';
2368    Field{1}.VarAttribute{nbvar+5}.Role='vector_y_tps';
2369    if isfield(Field{1},'ListDimName')%cleaning
2370        Field{1}=rmfield(Field{1},'ListDimName');
2371    end
2372    if isfield(Field{1},'DimValue')%cleaning
2373        Field{1}=rmfield(Field{1},'DimValue');
2374    end
2375end
2376
2377%% calculate scalar
2378if isstruct(ParamOut)&&~strcmp(ParamOut.FieldName,'get_field...')&& (strcmp(UvData.FileType{1},'civdata')||strcmp(UvData.FileType{1},'civx'))...
2379         &&~strcmp(ParamOut.FieldName,'velocity') && ~strcmp(ParamOut.FieldName,'get_field...')
2380    if check_proj_tps
2381        Field{1}.FieldList=[{ParamOut.FieldName} {ParamOut.ColorVar}];
2382    else
2383        Field{1}=calc_field([{ParamOut.FieldName} {ParamOut.ColorVar}],Field{1});
2384    end
2385end
2386if isstruct(ParamOut_1)&& numel(Field)==2 && ~strcmp(ParamOut_1.FieldName,'get_field...')&& ~test_keepdata_1 && (strcmp(UvData.FileType{2},'civdata')||strcmp(UvData.FileType{2},'civx'))...
2387        &&~strcmp(ParamOut_1.FieldName,'velocity') && ~strcmp(ParamOut_1.FieldName,'get_field...')
2388    if check_proj_tps
2389        Field{2}.FieldList=[{ParamOut_1.FieldName} {ParamOut_1.ColorVar}];
2390    else
2391     Field{2}=calc_field([{ParamOut_1.FieldName} {ParamOut_1.ColorVar}],Field{2});
2392    end
2393end
2394
2395%% combine the two input fields (e.g. substract velocity fields)
2396%Field{1}.FieldList=[{ParamOut.FieldName} {ParamOut.ColorVar}];
2397if numel(Field)==2
2398   [UvData.Field,errormsg]=sub_field(Field{1},Field{2}); 
2399   UvData.Field_1=Field{2}; %store the second field for possible use at next RUN
2400   UvData.ParamOut_1=ParamOut_1;
2401else
2402   UvData.Field=Field{1};
2403end
2404if ~isempty(errormsg)
2405    errormsg=['error in uvmat/refresh_field/sub_field:' errormsg];
2406    return
2407end
2408%UvData.Field.FieldList={FieldName}; % TODO: to generalise, used for proj_field with tps interpolation
2409
2410%% analyse input field
2411test_x=0;
2412test_z=0;% test for unstructured z coordinate
2413[errormsg,ListDimName,DimValue,VarDimIndex]=check_field_structure(UvData.Field);% check the input field structure
2414if ~isempty(errormsg)
2415    errormsg=['error in uvmat/refresh_field/check_field_structure: ' errormsg];% display error
2416    return
2417end
2418[CellVarIndex,NbDim,VarType,errormsg]=find_field_indices(UvData.Field);% analyse  the input field structure
2419if ~isempty(errormsg)
2420    errormsg=['error in uvmat/refresh_field/find_field_indices: ' errormsg];% display error
2421    return
2422end
2423[NbDim,imax]=max(NbDim);% spatial dimension of the input field
2424if isfield(UvData.Field,'NbDim')
2425    NbDim=UvData.Field.NbDim;% deal with plane fields containing z coordinates
2426end
2427
2428%% get bounds and mesh (needed for mouse action and to open set_object)
2429if NbDim>1
2430    XName=''; %default
2431    YName='';
2432    %unstructured coordinates
2433    if ~isempty(VarType{imax}.coord_x)&&~isempty(VarType{imax}.coord_y)
2434        XName=UvData.Field.ListVarName{VarType{imax}.coord_x};
2435        YName=UvData.Field.ListVarName{VarType{imax}.coord_y};
2436        %nbvec=length(UvData.Field.(XName));%nbre of measurement points (e.g. vectors)
2437        test_x=1;%test for unstructured coordinates
2438        if ~isempty(VarType{imax}.coord_z)
2439            ZName=UvData.Field.ListVarName{VarType{imax}.coord_z};
2440        else
2441            NbDim=2;
2442        end
2443        %structured coordinate
2444    elseif numel(VarType)>=imax && numel(VarType{imax}.coord)>=NbDim && VarType{imax}.coord(NbDim)>0
2445        XName=UvData.Field.ListVarName{VarType{imax}.coord(NbDim)};
2446        if NbDim> 1 && VarType{imax}.coord(NbDim-1)>0
2447            YName=UvData.Field.ListVarName{VarType{imax}.coord(NbDim-1)}; %structured coordinates
2448        end
2449        % VarIndex=CellVarIndex{imax}; % list of variable indices
2450        DimIndex=VarDimIndex{CellVarIndex{imax}(1)}; %list of dim indices for the variable
2451        nbpoints_x=DimValue(DimIndex(NbDim));
2452        XMax=nbpoints_x;%default
2453        XMin=1;%default
2454    end
2455   
2456    if NbDim==3
2457        if ~test_x
2458            ZName=UvData.Field.ListVarName{VarType{imax}.coord(1)};%structured coordinates in 3D
2459        end
2460        ZMax=max(UvData.Field.(ZName));
2461        ZMin=min(UvData.Field.(ZName));
2462        UvData.Field.ZMax=ZMax;
2463        UvData.Field.ZMin=ZMin;
2464        test_z=1;
2465        if isequal(ZMin,ZMax)%no z dependency
2466            NbDim=2;
2467            test_z=0;
2468        end
2469    end
2470    if ~isempty (XName)
2471        XMax=max(max(UvData.Field.(XName)));
2472        XMin=min(min(UvData.Field.(XName)));
2473        UvData.Field.NbDim=NbDim;
2474        UvData.Field.XMax=XMax;
2475        UvData.Field.XMin=XMin;
2476        if NbDim >1&& ~isempty(YName)
2477            YMax=max(max(UvData.Field.(YName)));
2478            YMin=min(min(UvData.Field.(YName)));
2479            UvData.Field.YMax=YMax;
2480            UvData.Field.YMin=YMin;
2481        end
2482        nbvec=length(UvData.Field.(XName));
2483        if test_x %unstructured coordinates
2484            if test_z
2485                UvData.Field.Mesh=((XMax-XMin)*(YMax-YMin)*(ZMax-ZMin))/nbvec;% volume per vector
2486                UvData.Field.Mesh=(UvData.Field.Mesh)^(1/3);
2487            else
2488                UvData.Field.Mesh=sqrt((XMax-XMin)*(YMax-YMin)/nbvec);%2D
2489            end
2490        end
2491    end
2492    % case of structured coordinates
2493    if ~test_x
2494        DX=(XMax-XMin)/(nbpoints_x-1);
2495        if NbDim >1
2496            nbpoints_y=DimValue(DimIndex(NbDim-1));
2497            if isempty(YName)% if the y coordinate is not expressed, it is taken as the matrix index
2498                DY=1;
2499                UvData.Field.YMax=nbpoints_y;
2500                UvData.Field.YMin=1;
2501            else
2502                DY=(YMax-YMin)/(nbpoints_y-1);
2503            end
2504        end
2505        if NbDim==3
2506            nbpoints_z=DimValue(DimIndex(1));
2507            DZ=(ZMax-ZMin)/(nbpoints_z-1);
2508            UvData.Field.Mesh=(DX*DY*DZ)^(1/3);
2509            UvData.Field.ZMax=ZMax;
2510            UvData.Field.ZMin=ZMin;
2511        else
2512            UvData.Field.Mesh=DX;%sqrt(DX*DY);
2513        end
2514    end
2515    % adjust the mesh to a value 1, 2 , 5 *10^n
2516    ord=10^(floor(log10(UvData.Field.Mesh)));%order of magnitude
2517    if UvData.Field.Mesh/ord>=5
2518        UvData.Field.Mesh=5*ord;
2519    elseif UvData.Field.Mesh/ord>=2
2520        UvData.Field.Mesh=2*ord;
2521    else
2522        UvData.Field.Mesh=ord;
2523    end
2524    % default projection plane
2525    if ~isfield(UvData,'Object')
2526        UvData.Object{1}.Type='plane';%main plotting plane
2527        UvData.Object{1}.ProjMode='projection';%main plotting plane
2528        UvData.Object{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2529        UvData.Object{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2530    end
2531    %% 3D case (menuvolume)
2532    if NbDim==3% && UvData.NewSeries
2533        test_set_object=1;
2534        hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
2535        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
2536        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
2537        if ~isempty(hset_object) %if set_object is detected
2538            delete(hset_object);% delete the GUI set_object if it does not fit
2539        end
2540        if test_set_object% reinitiate the GUI set_object
2541            delete_object(1);% delete the current projection object in the list UvData.Object, delete its graphic representations and update the list displayed in handles.ListObject and 2
2542            UvData.Object{1}.NbDim=NbDim;%test for 3D objects
2543            UvData.Object{1}.RangeZ=UvData.Field.Mesh;%main plotting plane
2544            UvData.Object{1}.Coord(1,3)=(UvData.Field.ZMin+UvData.Field.ZMax)/2;%section at a middle plane chosen
2545            UvData.Object{1}.Angle=[0 0 0];
2546            UvData.Object{1}.HandlesDisplay=plot(0,0,'Tag','proj_object');% A REVOIR
2547            UvData.Object{1}.Name='1-PLANE';
2548            UvData.Object{1}.enable_plot=1;
2549            set_object(UvData.Object{1},handles,ZBounds);
2550            set(handles.ListObject,'Value',1);
2551            set(handles.ListObject,'String',{'1-PLANE'});
2552            set(handles.edit_object,'Value',1)% put the plane in edit mode to enable the z cursor
2553            edit_object_Callback([],[], handles)
2554        end
2555        %multilevel case (single menuplane in a 3D space)
2556    elseif isfield(UvData,'Z')
2557        if isfield(UvData,'CoordType')&& isequal(UvData.CoordType,'phys') && isfield(UvData,'XmlData')
2558            XmlData=UvData.XmlData{1};
2559            if isfield(XmlData,'PlanePos')
2560                UvData.Object{1}.Coord=XmlData.PlanePos(UvData.ZIndex,:);
2561            end
2562            if isfield(XmlData,'PlaneAngle')
2563                siz=size(XmlData.PlaneAngle);
2564                indangle=min(siz(1),UvData.ZIndex);%take first angle if a single angle is defined (translating scanning)
2565                UvData.Object{1}.PlaneAngle=XmlData.PlaneAngle(indangle,:);
2566            end
2567        elseif isfield(UvData,'ZIndex')
2568            UvData.Object{1}.ZObject=UvData.ZIndex;
2569        end
2570    end
2571end
2572
2573testnewseries=UvData.NewSeries;
2574UvData.NewSeries=0;% put to 0 the test for a new field series (set by RootPath_callback)
2575set(handles.uvmat,'UserData',UvData)
2576
2577%% reset the min and max of scalar if only the mask is displayed(TODO: check the need)
2578% if isfield(UvData,'Mask')&& ~isfield(UvData,'A')
2579%     set(handles.num_MinA,'String','0')
2580%     set(handles.num_MaxA,'String','255')
2581% end
2582
2583%% usual 1D (x,y) plots
2584if NbDim<=1
2585    set(handles.Objects,'Visible','off')
2586    set(handles.ListObject_1_title,'Visible','off')
2587    set(handles.ListObject_1,'Visible','off')
2588    [PlotType,PlotParamOut]=plot_field(UvData.Field,handles.axes3,read_GUI(handles.uvmat));
2589    write_plot_param(handles,PlotParamOut) %update the auto plot parameters
2590%     if isfield(Field,'Mesh')&&~isempty(Field.Mesh)
2591%         ObjectData.Mesh=Field.Mesh; % gives an estimated mesh size (useful for mouse action on the plot)
2592%     end
2593   
2594%% 2D or 3D fields are generally projected
2595else
2596    set(handles.Objects,'Visible','on')
2597    set(handles.ListObject_1_title,'Visible','on')
2598    set(handles.ListObject_1,'Visible','on')
2599   
2600    %% Plot the projections on the selected  projection objects
2601    % main projection object (uvmat display)
2602    list_object=get(handles.ListObject_1,'String');
2603    if isequal(list_object,{''})%refresh list of objects if the menu is empty
2604        UvData.Object={[]};
2605        set(handles.ListObject_1,'Value',1)
2606    end
2607    IndexObj(1)=get(handles.ListObject_1,'Value');%selected projection object for main view
2608    if IndexObj(1)> numel(UvData.Object)
2609        IndexObj(1)=1;%select the first object if the selected one does not exist
2610        set(handles.ListObject_1,'Value',1)
2611    end
2612    IndexObj(2)=get(handles.ListObject,'Value');%selected projection object for main view
2613    if isequal(IndexObj(2),IndexObj(1))
2614        IndexObj(2)=[];
2615    end
2616    plot_handles{1}=handles;
2617    if isfield(UvData,'plotaxes')%case of movies
2618        haxes(1)=UvData.plotaxes;
2619    else
2620        haxes(1)=handles.axes3;
2621    end
2622    PlotParam{1}=read_GUI(handles.uvmat);
2623    %default settings if vectors not visible
2624    if ~isfield(PlotParam{1},'Vectors')
2625        PlotParam{1}.Vectors.MaxVec=1;
2626        PlotParam{1}.Vectors.MinVec=0;
2627        PlotParam{1}.Vectors.CheckFixVecColor=1;
2628        PlotParam{1}.Vectors.ColCode1=0.33;
2629        PlotParam{1}.Vectors.ColCode2=0.66;
2630        PlotParam{1}.Vectors.ColorScalar={'ima_cor'};
2631        PlotParam{1}.Vectors.ColorCode= {'rgb'};
2632    end
2633    PosColorbar{1}=UvData.OpenParam.PosColorbar;%prescribe the colorbar position on the uvmat interface
2634   
2635    %% second projection object (view_field display)
2636    if length( IndexObj)>=2
2637        view_field_handle=findobj(allchild(0),'tag','view_field');%handles of the view_field GUI
2638        if ~isempty(view_field_handle)
2639            plot_handles{2}=guidata(view_field_handle);
2640            haxes(2)=plot_handles{2}.axes3;
2641            PlotParam{2}=read_GUI(handles.uvmat);%read plotting parameters on the uvmat interface
2642            PosColorbar{2}='*'; %TODO: deal with colorbar position on view_field
2643        end
2644    end
2645   
2646    %% loop on the projection objects: one or two
2647   
2648    for imap=1:numel(IndexObj)
2649        iobj=IndexObj(imap);
2650        %      if imap==2 || check_proj==0  % field not yet projected) && ~isfield(UvData.Object{iobj},'Type')% case with no projection (only for the first empty object)
2651        % %          [ObjectData,errormsg]=calc_field(UvData.Field.FieldList,UvData.Field);
2652        % %      else
2653        [ObjectData,errormsg]=proj_field(UvData.Field,UvData.Object{iobj});% project field on the object
2654        %      end
2655        if ~isempty(errormsg)
2656            return
2657        end
2658        if testnewseries
2659            PlotParam{imap}.Scalar.CheckBW=[]; %B/W option depends on the input field (image or scalar)
2660            if isfield(ObjectData,'CoordUnit')
2661                PlotParam{imap}.Coordinates.CheckFixAspectRatio=1;% set x and y scaling equal if CoordUnit is defined (common unit for x and y)
2662                PlotParam{imap}.Coordinates.AspectRatio=1; %set aspect ratio to 1
2663            end
2664        end
2665        %use of mask (TODO: check)
2666        if isfield(ObjectData,'NbDim') && isequal(ObjectData.NbDim,2) && isfield(ObjectData,'Mask') && isfield(ObjectData,'A')
2667            flag_mask=double(ObjectData.Mask>200);%=0 for masked regions
2668            AX=ObjectData.AX;%x coordiantes for the scalar field
2669            AY=ObjectData.AY;%y coordinates for the scalar field
2670            MaskX=ObjectData.MaskX;%x coordiantes for the mask
2671            MaskY=ObjectData.MaskY;%y coordiantes for the mask
2672            if ~isequal(MaskX,AX)||~isequal(MaskY,AY)
2673                nxy=size(flag_mask);
2674                sizpx=(ObjectData.MaskX(end)-ObjectData.MaskX(1))/(nxy(2)-1);%size of a mask pixel
2675                sizpy=(ObjectData.MaskY(1)-ObjectData.MaskY(end))/(nxy(1)-1);
2676                x_mask=ObjectData.MaskX(1):sizpx:ObjectData.MaskX(end); % pixel x coordinates for image display
2677                y_mask=ObjectData.MaskY(1):-sizpy:ObjectData.MaskY(end);% pixel x coordinates for image display
2678                %project on the positions of the scalar
2679                npxy=size(ObjectData.A);
2680                dxy(1)=(ObjectData.AY(end)-ObjectData.AY(1))/(npxy(1)-1);%grid mesh in y
2681                dxy(2)=(ObjectData.AX(end)-ObjectData.AX(1))/(npxy(2)-1);%grid mesh in x
2682                xi=ObjectData.AX(1):dxy(2):ObjectData.AX(end);
2683                yi=ObjectData.AY(1):dxy(1):ObjectData.AY(end);
2684                [XI,YI]=meshgrid(xi,yi);% creates the matrix of regular coordinates
2685                flag_mask = interp2(x_mask,y_mask,flag_mask,XI,YI);
2686            end
2687            AClass=class(ObjectData.A);
2688            ObjectData.A=flag_mask.*double(ObjectData.A);
2689            ObjectData.A=feval(AClass,ObjectData.A);
2690            ind_off=[];
2691            if isfield(ObjectData,'ListVarName')
2692                for ilist=1:length(ObjectData.ListVarName)
2693                    if isequal(ObjectData.ListVarName{ilist},'Mask')||isequal(ObjectData.ListVarName{ilist},'MaskX')||isequal(ObjectData.ListVarName{ilist},'MaskY')
2694                        ind_off=[ind_off ilist];
2695                    end
2696                end
2697                ObjectData.ListVarName(ind_off)=[];
2698                VarDimIndex(ind_off)=[];
2699                ind_off=[];
2700                for ilist=1:length(ListDimName)
2701                    if isequal(ListDimName{ilist},'MaskX') || isequal(ListDimName{ilist},'MaskY')
2702                        ind_off=[ind_off ilist];
2703                    end
2704                end
2705                ListDimName(ind_off)=[];
2706                DimValue(ind_off)=[];
2707            end
2708        end
2709        if ~isempty(ObjectData)
2710            PlotType='none'; %default
2711            if imap==2 && isempty(view_field_handle)
2712                view_field(ObjectData)
2713            else
2714                [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
2715                write_plot_param(plot_handles{imap},PlotParamOut) %update the auto plot parameters
2716                if isfield(Field,'Mesh')&&~isempty(Field.Mesh)
2717                    ObjectData.Mesh=Field.Mesh; % gives an estimated mesh size (useful for mouse action on the plot)
2718                end
2719            end
2720%             if isequal(PlotType,'none')
2721%                 hget_field=findobj(allchild(0),'name','get_field');
2722%                 if isempty(hget_field)
2723%                     get_field(FileName)% the projected field cannot be automatically plotted: use get_field to specify the variablesdelete(hget_field)
2724%                 end
2725%                 errormsg='The field defined by get_field cannot be plotted';
2726%                 return
2727%             end
2728        end
2729    end
2730   
2731    %% update the mask
2732    if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
2733        update_mask(handles,num_i1,num_i2);
2734    end
2735   
2736    %% prepare the menus of histograms and plot them (histogram of the whole volume in 3D case)
2737    menu_histo=(UvData.Field.ListVarName)';%list of field variables to be displayed for the menu of histogram display
2738    ind_skip=[];
2739    % nb_histo=1;
2740    Ustring='';
2741    Vstring='';
2742    % suppress coordinates from the histogram menu
2743    for ivar=1:numel(menu_histo)%l loop on field variables:
2744        if isfield(UvData.Field,'VarAttribute') && numel(UvData.Field.VarAttribute)>=ivar && isfield(UvData.Field.VarAttribute{ivar},'Role')
2745            Role=UvData.Field.VarAttribute{ivar}.Role;
2746            switch Role
2747                case {'coord_x','coord_y','coord_z','dimvar'}
2748                    ind_skip=[ind_skip ivar];
2749                case {'vector_x'}
2750                    Ustring=UvData.Field.ListVarName{ivar};
2751                    ind_skip=[ind_skip ivar];
2752                case {'vector_y'}
2753                    Vstring=UvData.Field.ListVarName{ivar};
2754                    ind_skip=[ind_skip ivar];
2755            end
2756        end
2757        DimCell=UvData.Field.VarDimName{ivar};
2758        DimName='';
2759        if ischar(DimCell)
2760            DimName=DimCell;
2761        elseif iscell(DimCell)&& numel(DimCell)==1
2762            DimName=DimCell{1};
2763        end
2764        if strcmp(DimName,menu_histo{ivar})
2765            ind_skip=[ind_skip ivar];
2766        end
2767    end
2768    menu_histo(ind_skip)=[];% remove skipped items
2769    if ~isempty(Ustring)
2770        menu_histo=[{[Ustring ',' Vstring]};menu_histo];% add U, V at the beginning if they exist
2771    end
2772   
2773    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2774    % display menus and plot histograms
2775    test_v=0;
2776    if ~isempty(menu_histo)
2777        set(handles.histo1_menu,'Value',1)
2778        set(handles.histo1_menu,'String',menu_histo)
2779        histo1_menu_Callback(handles.histo1_menu, [], handles)% plot first histogram
2780    end
2781end
2782
2783%------------------------------------------------------------------------
2784function histo1_menu_Callback(hObject, eventdata, handles)
2785%--------------------------------------------
2786%plot first histo
2787%huvmat=get(handles.histo1_menu,'parent');
2788histo_menu=get(handles.histo1_menu,'String');
2789histo_value=get(handles.histo1_menu,'Value');
2790FieldName=histo_menu{histo_value};
2791% update_histo(handles.histo_u,handles.uvmat,FieldName)
2792%
2793% %------------------------------------------------------------------------
2794% function histo2_menu_Callback(hObject, eventdata, handles)
2795% %------------------------------------------------------------------------
2796% %plot second histo
2797% %huvmat=get(handles.histo2_menu,'parent');
2798% histo_menu=get(handles.histo2_menu,'String');
2799% histo_value=get(handles.histo2_menu,'Value');
2800% FieldName=histo_menu{histo_value};
2801% update_histo(handles.histo_v,handles.uvmat,FieldName)
2802%
2803% %------------------------------------------------------------------------
2804% %read the field .Fieldname stored in UvData and plot its histogram
2805% function update_histo(haxes,huvmat,FieldName)
2806%------------------------------------------------------------------------
2807UvData=get(handles.uvmat,'UserData');
2808Field=UvData.Field;
2809r=regexp(FieldName,'(?<var1>.*)(?<sep>,)(?<var2>.*)','names');
2810FieldName_2='';
2811if ~isempty(r)
2812    FieldName=r.var1;
2813    FieldName_2=r.var2;
2814end
2815if ~isfield(UvData.Field,FieldName)
2816    msgbox_uvmat('ERROR',['no field  ' FieldName ' for histogram'])
2817    return
2818end
2819FieldHisto=Field.(FieldName);
2820if isfield(Field,'FF') && ~isempty(Field.FF) && isequal(size(Field.FF),size(FieldHisto))
2821    indsel=find(Field.FF==0);%find values marked as false
2822    if ~isempty(indsel)
2823        FieldHisto=FieldHisto(indsel);
2824        if ~isempty(FieldName_2)
2825            FieldHisto(:,:,2)=Field.(FieldName_2)(indsel);
2826        end
2827    end
2828end
2829if isempty(Field)
2830    msgbox_uvmat('ERROR',['empty field ' FieldName])
2831else
2832    nxy=size(FieldHisto);
2833    Amin=double(min(min(min(FieldHisto))));%min of field value
2834    Amax=double(max(max(max(FieldHisto))));%max of field value
2835    if isequal(Amin,Amax)
2836        cla(handles.histo_u)
2837    else
2838        Histo.ListVarName={FieldName,'histo'};
2839        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2840            Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2841        else
2842            if numel(nxy)==2
2843                Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2844            else
2845                Histo.VarDimName={FieldName,{FieldName,'component'}}; %dimensions for the histogram
2846            end
2847        end
2848        %unit
2849        units=[]; %default
2850        for ivar=1:numel(Field.ListVarName)
2851            if strcmp(Field.ListVarName{ivar},FieldName)
2852                if isfield(Field,'VarAttribute') && numel(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'units')
2853                    units=Field.VarAttribute{ivar}.units;
2854                    break
2855                end
2856            end
2857        end
2858        if ~isempty(units)
2859            Histo.VarAttribute{1}.units=units;
2860        end
2861        eval(['Histo.' FieldName '=linspace(Amin,Amax,50);'])%absissa values for histo
2862        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2863            C=reshape(double(FieldHisto),1,[]);% reshape in a vector
2864            Histo.histo(:,1)=hist(C, Histo.(FieldName));  %calculate histogram
2865        else
2866            for col=1:size(FieldHisto,3)
2867                B=FieldHisto(:,:,col);
2868                C=reshape(double(B),1,nxy(1)*nxy(2));% reshape in a vector
2869                Histo.histo(:,col)=hist(C, Histo.(FieldName));  %calculate histogram
2870            end
2871        end
2872        plot_field(Histo,handles.histo_u);
2873        hlegend=legend;
2874        if isempty(FieldName_2)
2875        set(hlegend,'String',FieldName)
2876        else
2877            set(hlegend,'String',{FieldName;FieldName_2})
2878        end
2879%         hh=get(handles.histo_u,'children');
2880%         get(hh(1))
2881%         get(hh(2))
2882    end
2883end
2884
2885%-------------------------------------------------------------------
2886% --- translate coordinate to matrix index
2887%-------------------------------------------------------------------
2888function [indx,indy]=pos2ind(x0,rangx0,nxy)
2889indx=1+round((nxy(2)-1)*(x0-rangx0(1))/(rangx0(2)-rangx0(1)));% index x of pixel 
2890indy=1+round((nxy(1)-1)*(y12-rangy0(1))/(rangy0(2)-rangy0(1)));% index y of pixel
2891
2892
2893%-------------------------------------------------------------------
2894% --- Executes on button press in 'CheckZoom'.
2895%-------------------------------------------------------------------
2896function CheckZoom_Callback(hObject, eventdata, handles)
2897
2898if (get(handles.CheckZoom,'Value') == 1);
2899    set(handles.CheckZoom,'BackgroundColor',[1 1 0])
2900    set(handles.CheckFixLimits,'Value',1)% propose by default fixed limits for the plotting axes
2901    set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
2902else
2903    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
2904end
2905
2906%-------------------------------------------------------------------
2907% --- Executes on button press in 'CheckFixLimits'.
2908%-------------------------------------------------------------------
2909function CheckFixLimits_Callback(hObject, eventdata, handles)
2910test=get(handles.CheckFixLimits,'Value');
2911if test
2912    set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
2913else
2914    set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
2915    update_plot(handles);
2916end
2917
2918%-------------------------------------------------------------------
2919% --- Executes on button press in CheckFixAspectRatio.
2920function CheckFixAspectRatio_Callback(hObject, eventdata, handles)
2921%-------------------------------------------------------------------
2922if get(handles.CheckFixAspectRatio,'Value')
2923    set(handles.CheckFixAspectRatio,'BackgroundColor',[1 1 0])
2924    update_plot(handles);
2925else
2926    set(handles.CheckFixAspectRatio,'BackgroundColor',[0.7 0.7 0.7])
2927    update_plot(handles);
2928end
2929
2930%-------------------------------------------------------------------
2931function num_AspectRatio_Callback(hObject, eventdata, handles)
2932%-------------------------------------------------------------------
2933set(handles.CheckFixAspectRatio,'Value',1)% select the fixed aspect ratio button
2934set(handles.CheckFixAspectRatio,'BackgroundColor',[1 1 0])% mark in yellow
2935update_plot(handles);
2936%-------------------------------------------------------------------
2937
2938%-------------------------------------------------------------------
2939
2940
2941
2942%-------------------------------------------------------------------
2943%----Executes on button press in 'record': records the current flags of manual correction.
2944%-------------------------------------------------------------------
2945function record_Callback(hObject, eventdata, handles)
2946% [filebase,num_i1,num_j1,num_i2,num_j2,Ext,NomType,SubDir]=read_input_file(handles);
2947[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
2948FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
2949%FileName=read_file_boxes(handles);
2950[erread,message]=fileattrib(FileName);
2951if ~isempty(message) && ~isequal(message.UserWrite,1)
2952     msgbox_uvmat('ERROR',['no writting access to ' FileName])
2953     return
2954end
2955test_civ2=isequal(get(handles.civ2,'BackgroundColor'),[1 1 0]);
2956test_civ1=isequal(get(handles.VelType,'BackgroundColor'),[1 1 0]);
2957if ~test_civ2 && ~test_civ1
2958    msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
2959end
2960if test_civ2
2961    nbname='nb_vectors2';
2962   flagname='vec2_FixFlag';
2963   attrname='fix2';
2964end
2965if test_civ1
2966    nbname='nb_vectors';
2967   flagname='vec_FixFlag';
2968   attrname='fix';
2969end
2970%write fix flags in the netcdf file
2971UvData=get(handles.uvmat,'UserData');
2972hhh=which('netcdf.open');% look for built-in matlab netcdf library
2973if ~isequal(hhh,'')% case of new builtin Matlab netcdf library
2974    nc=netcdf.open(FileName,'NC_WRITE');
2975    netcdf.reDef(nc);
2976    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),attrname,1);
2977    dimid = netcdf.inqDimID(nc,nbname);
2978    try
2979        varid = netcdf.inqVarID(nc,flagname);% look for already existing fixflag variable
2980    catch
2981        varid=netcdf.defVar(nc,flagname,'double',dimid);%create fixflag variable if it does not exist
2982    end
2983    netcdf.endDef(nc);
2984    netcdf.putVar(nc,varid,UvData.axes3.FF);
2985    netcdf.close(nc); 
2986else %old netcdf library
2987    netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2988end
2989
2990%-------------------------------------------------------------------
2991%----Correct the netcdf file, using toolbox (old versions of Matlab).
2992%-------------------------------------------------------------------
2993function netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2994nc=netcdf(FileName,'write'); %open netcdf file
2995result=redef(nc);
2996eval(['nc.' attrname '=1;']);
2997theDim=nc(nbname) ;% get the number of velocity vectors
2998nb_vectors=size(theDim);
2999var_FixFlag=ncvar(flagname,nc);% var_FixFlag will be written as the netcdf variable vec_FixFlag
3000var_FixFlag(1:nb_vectors)=AxeData.FF;%
3001fin=close(nc);
3002
3003%-------------------------------------------------------------------
3004% --- Executes on button press in SubField
3005function SubField_Callback(hObject, eventdata, handles)
3006%-------------------------------------------------------------------
3007UvData=get(handles.uvmat,'UserData');
3008if get(handles.SubField,'Value')==0% if the subfield button is desactivated   
3009    set(handles.RootPath_1,'String','')
3010    set(handles.RootFile_1,'String','')
3011    set(handles.SubDir_1,'String','');
3012    set(handles.FileIndex_1,'String','');
3013    set(handles.FileExt_1,'String','');
3014    set(handles.RootPath_1,'Visible','off')
3015    set(handles.RootFile_1,'Visible','off')
3016    set(handles.SubDir_1,'Visible','off');
3017    set(handles.NomType_1,'Visible','off');
3018    set(handles.abs_time_1,'Visible','off')
3019    set(handles.FileIndex_1,'Visible','off');
3020    set(handles.FileExt_1,'Visible','off');
3021    set(handles.Fields_1,'Value',1);%set to blank state
3022    set(handles.VelType_1,'Value',1);%set to blank state
3023    set(handles.num_Opacity,'String','')% desactivate opacity setting
3024    if ~strcmp(get(handles.VelType,'Visible'),'on')
3025        set(handles.VelType_1,'Visible','off')
3026    end
3027    if isfield(UvData,'XmlData_1')
3028        UvData=rmfield(UvData,'XmlData_1');
3029    end
3030    set(handles.uvmat,'UserData',UvData);
3031    run0_Callback(hObject, eventdata, handles); %run
3032else
3033    MenuBrowse_1_Callback(hObject, eventdata, handles)
3034end
3035
3036%------------------------------------------------------------------------
3037% --- read the data displayed for the input rootfile windows (new): TODO use read_GUI
3038
3039function [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles)
3040%------------------------------------------------------------------------
3041InputFile=read_GUI(handles.InputFile);
3042RootPath=InputFile.RootPath;
3043SubDir=regexprep(InputFile.SubDir,'/|\','');
3044RootFile=regexprep(InputFile.RootFile,'/|\','');
3045FileIndices=InputFile.FileIndex;
3046FileExt=InputFile.FileExt;
3047
3048
3049%------------------------------------------------------------------------
3050% ---- read the data displayed for the second input rootfile windows
3051function [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1,NomType_1]=read_file_boxes_1(handles)
3052%------------------------------------------------------------------------
3053RootPath_1=get(handles.RootPath_1,'String'); % read the data from the file1_input window
3054if isequal(get(handles.RootPath_1,'Visible'),'off') || isequal(RootPath_1,'"')
3055    RootPath_1=get(handles.RootPath,'String');
3056end;
3057SubDir_1=get(handles.SubDir_1,'String');
3058if isequal(get(handles.SubDir_1,'Visible'),'off')|| isequal(SubDir_1,'"')
3059    SubDir_1=get(handles.SubDir,'String');
3060end
3061SubDir_1=regexprep(SubDir_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3062RootFile_1=get(handles.RootFile_1,'String');
3063if isequal(get(handles.RootFile_1,'Visible'),'off') || isequal(RootFile_1,'"')
3064    RootFile_1=get(handles.RootFile,'String');
3065end
3066RootFile_1=regexprep(RootFile_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3067FileIndex_1=get(handles.FileIndex_1,'String');
3068if isequal(get(handles.FileIndex_1,'Visible'),'off')|| isequal(FileIndex_1,'"')
3069    FileIndex_1=get(handles.FileIndex,'String');
3070end
3071FileExt_1=get(handles.FileExt_1,'String');
3072if isequal(get(handles.FileExt_1,'Visible'),'off') || isequal(FileExt_1,'"')
3073    FileExt_1=get(handles.FileExt,'String');%read FileExt by default
3074end
3075NomType_1=get(handles.NomType_1,'String');
3076if isequal(get(handles.NomType_1,'Visible'),'off') || isequal(NomType_1,'"')
3077    NomType_1=get(handles.NomType,'String');%read FileExt by default
3078end
3079%------------------------------------------------------------------------
3080% --- Executes on menu selection Fields
3081function Fields_Callback(hObject, eventdata, handles)
3082%------------------------------------------------------------------------
3083list_fields=get(handles.Fields,'String');% list menu fields
3084index_fields=get(handles.Fields,'Value');% selected string index
3085field= list_fields{index_fields(1)}; % selected string
3086if isequal(field,'get_field...')
3087    set(handles.FixVelType,'visible','off')
3088    set(handles.VelType,'visible','off')
3089    set(handles.VelType_1,'visible','off')
3090    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3091    FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3092    %FileName=read_file_boxes(handles);
3093    hget_field=findobj(allchild(0),'name','get_field');
3094    if ~isempty(hget_field)
3095        delete(hget_field)
3096    end
3097    hget_field=get_field(FileName);
3098    set(hget_field,'Name','get_field')
3099    hhget_field=guidata(hget_field);
3100    set(hhget_field.list_fig,'Value',1)
3101    set(hhget_field.list_fig,'String',{'uvmat'})
3102    set(handles.transform_fct,'Value',1)% no transform by default
3103    set(handles.path_transform,'String','')
3104    return %no action
3105end
3106list_fields=get(handles.Fields_1,'String');% list menu fields
3107index_fields=get(handles.Fields_1,'Value');% selected string index
3108field_1= list_fields{index_fields(1)}; % selected string
3109UvData=get(handles.uvmat,'UserData');
3110
3111%read the rootfile input display
3112[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3113FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3114[tild,tild,tild,i1,i2,j1,j2,tild,NomType]=fileparts_uvmat(['xxx' get(handles.FileIndex,'String') FileExt]);
3115if isequal(field,'image')
3116    if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3117        imagename=UvData.Field.Civ2_ImageA;
3118    elseif isfield(UvData.Field,'Civ1_ImageA')%
3119        imagename=UvData.Field.Civ1_ImageA;
3120    else
3121        SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3122        imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3123    end
3124    if ~exist(imagename,'file')
3125        [FileName,PathName] = uigetfile( ...
3126            {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3127            '*.jpg',' jpeg image files'; ...
3128            '*.png','.png image files'; ...
3129            '*.tif','.tif image files'; ...
3130            '*.avi;*.AVI','.avi movie files'; ...
3131            '*.vol','.volume images (png)'; ...
3132            '*.*',  'All Files (*.*)'}, ...
3133            'Pick an image',imagename);   
3134        imagename=[PathName FileName];
3135    end
3136     % display the selected field and related information
3137    display_file_name(handles,imagename)%display the image
3138    return
3139else
3140    ext=get(handles.FileExt,'String');
3141    if ~isequal(ext,'.nc') %find the new NomType if the previous display was not already a netcdf file
3142        [FileName,PathName] = uigetfile( ...
3143            {'*.nc', ' (*.nc)';
3144            '*.nc',' netcdf files'; ...
3145            '*.*',  'All Files (*.*)'}, ...
3146            'Pick a netcdf file',FileBase);
3147        FullFileName=[PathName FileName];
3148        % display the selected field and related information
3149        display_file_name( handles,FullFileName)
3150        return
3151    end
3152end
3153indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,j2);
3154set(handles.FileIndex,'String',indices)
3155% set(handles.NomType,'String',NomType)
3156
3157%common to Fields_1_Callback
3158if isequal(field,'image')||isequal(field_1,'image')
3159    set(handles.TitleNpx,'Visible','on')% visible npx,pxcm... buttons
3160    set(handles.TitleNpy,'Visible','on')
3161    set(handles.num_Npx,'Visible','on')
3162    set(handles.num_Npy,'Visible','on')
3163else
3164    set(handles.TitleNpx,'Visible','off')% visible npx,pxcm... buttons
3165    set(handles.TitleNpy,'Visible','off')
3166    set(handles.num_Npx,'Visible','off')
3167    set(handles.num_Npy,'Visible','off')
3168end
3169if ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3170    run0_Callback(hObject, eventdata, handles)
3171end
3172
3173%---------------------------------------------------
3174% --- Executes on menu selection Fields
3175function Fields_1_Callback(hObject, eventdata, handles)
3176%-------------------------------------------------
3177%% read input data
3178check_new=~get(handles.SubField,'Value'); %check_new=1 if a second field was not previously entered
3179UvData=get(handles.uvmat,'UserData');
3180if check_new && isfield(UvData,'XmlData')
3181    UvData.XmlData{2}=UvData.XmlData{1};
3182end
3183if isfield(UvData,'Field_1')
3184    UvData=rmfield(UvData,'Field_1');% remove the stored second field (a new one needs to be read)
3185end
3186UvData.FileName_1='';% desactivate the use of a constant second file
3187list_fields=get(handles.Fields,'String');% list menu fields
3188field= list_fields{get(handles.Fields,'Value')}; % selected string
3189list_fields=get(handles.Fields_1,'String');% list menu fields
3190field_1= list_fields{get(handles.Fields_1,'Value')}; % selected string for the second field
3191if isempty(field_1)%||(numel(UvData.FileType)>=2 && strcmp(UvData.FileType{2},'image'))
3192    set(handles.SubField,'Value',0)
3193    SubField_Callback(hObject, eventdata, handles)
3194    return
3195else
3196    set(handles.SubField,'Value',1)%state that a second field is now entered
3197end
3198
3199%% read the rootfile input display
3200[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3201FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
3202[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
3203% set(handles.FileIndex_1,'Visible','on')
3204% set(handles.FileExt_1,'Visible','on')
3205switch field_1
3206    case 'get_field...'
3207        set_veltype_display(0) % no veltype display
3208        hget_field=findobj(allchild(0),'name','get_field_1');
3209        if ~isempty(hget_field)
3210            delete(hget_field)
3211        end
3212        hget_field=get_field(FileName_1);
3213        set(hget_field,'name','get_field_1')
3214        hhget_field=guidata(hget_field);
3215        set(hhget_field.list_fig,'Value',1)
3216        set(hhget_field.list_fig,'String',{'uvmat'})
3217        set(handles.transform_fct,'Value',1)% no transform by default
3218        set(handles.path_transform,'String','')
3219        if check_new
3220            UvData.FileType{2}=UvData.FileType{1};
3221            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3222%             set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3223              set(handles.uvmat,'UserData',UvData)
3224        end
3225    case 'image'
3226        % get the image name corresponding to the current netcdf name (no unique correspondance)
3227        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3228            imagename=UvData.Field.Civ2_ImageA;
3229        elseif isfield(UvData.Field,'Civ1_ImageA')%
3230            imagename=UvData.Field.Civ1_ImageA;
3231        else
3232            SubDirBase=regexprep(SubDir_1,'\..*','');%take the root part of SubDir, before the first dot '.'
3233            imagename=fullfile_uvmat(RootPath_1,SubDirBase,RootFile_1,'.png',get(handles.NomType,'String'),i1,[],j1);
3234        end
3235        if ~exist(imagename,'file') % browse for images if it is not found
3236            [FileName,PathName] = uigetfile( ...
3237                {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3238                '*.jpg',' jpeg image files'; ...
3239                '*.png','.png image files'; ...
3240                '*.tif','.tif image files'; ...
3241                '*.avi;*.AVI','.avi movie files'; ...
3242                '*.vol','.volume images (png)'; ...
3243                '*.*',  'All Files (*.*)'}, ...
3244                'Pick an image',imagename);
3245            imagename=[PathName FileName];
3246        end
3247        if ~ischar(imagename)% quit if the browser has  been closed
3248            set(handles.SubField,'Value',0)
3249        else %valid browser input:  display the selected image
3250            set(handles.TitleNpx,'Visible','on')% visible npx,pxcm... buttons
3251            set(handles.TitleNpy,'Visible','on')
3252            set(handles.num_Npx,'Visible','on')
3253            set(handles.num_Npy,'Visible','on')
3254            display_file_name(handles,imagename,2)%display the imag
3255        end
3256    otherwise
3257        if check_new
3258            UvData.FileType{2}=UvData.FileType{1};
3259            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3260            set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3261        end
3262        if ~isequal(field,'image')
3263            set(handles.TitleNpx,'Visible','off')% visible npx,pxcm... buttons
3264            set(handles.TitleNpy,'Visible','off')
3265            set(handles.num_Npx,'Visible','off')
3266            set(handles.num_Npy,'Visible','off')
3267        end
3268        set(handles.uvmat,'UserData',UvData)
3269        if ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3270            run0_Callback(hObject, eventdata, handles)
3271        end
3272end
3273
3274%------------------------------------------------------------------------
3275% --- set the visibility of relevant velocity type menus:
3276function menu=set_veltype_display(Civ,FileType)
3277%------------------------------------------------------------------------
3278if ~exist('FileType','var')
3279    FileType='civx';
3280end
3281switch FileType
3282    case 'civx'
3283        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3284        if isequal(Civ,0)
3285            imax=0;
3286        elseif isequal(Civ,1) || isequal(Civ,2)
3287            imax=1;
3288        elseif isequal(Civ,3)
3289            imax=3;
3290        elseif isequal(Civ,4) || isequal(Civ,5)
3291            imax=4;
3292        elseif isequal(Civ,6) %patch2
3293            imax=6;
3294        end
3295    case 'civdata'
3296        menu={'civ1';'filter1';'civ2';'filter2'};
3297        if isequal(Civ,0)
3298            imax=0;
3299        elseif isequal(Civ,1) || isequal(Civ,2)
3300            imax=1;
3301        elseif isequal(Civ,3)
3302            imax=2;
3303        elseif isequal(Civ,4) || isequal(Civ,5)
3304            imax=3;
3305        elseif isequal(Civ,6) %patch2
3306            imax=4;
3307        end
3308end
3309menu=menu(1:imax);
3310
3311%------------------------------------------------------------------------
3312% --- Executes on button press in FixVelType.
3313function FixVelType_Callback(hObject, eventdata, handles)
3314%------------------------------------------------------------------------
3315% refresh the current plot if the fixed  veltype is unselected
3316if ~get(handles.FixVelType,'Value')
3317    run0_Callback(hObject, eventdata, handles)
3318end
3319
3320%------------------------------------------------------------------------
3321% --- Executes on button press in VelType.
3322function VelType_Callback(hObject, eventdata, handles)
3323%------------------------------------------------------------------------
3324set(handles.FixVelType,'Value',1)
3325run0_Callback(hObject, eventdata, handles)
3326
3327%------------------------------------------------------------------------
3328% --- Executes on button press in VelType_1.
3329function VelType_1_Callback(hObject, eventdata, handles)
3330%------------------------------------------------------------------------
3331set(handles.FixVelType,'Value',1)% the velocity type is now imposed by the GUI (not automatic)
3332UvData=get(handles.uvmat,'UserData');
3333%refresh field with a second FileName=first file name
3334set(handles.run0,'BackgroundColor',[1 1 0])%paint the command button in yellow
3335drawnow   
3336InputFile=read_GUI(handles.InputFile);
3337[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3338FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3339
3340if isempty(InputFile.VelType_1)
3341        FileName_1='';% we plot the current field without the second field
3342        set(handles.SubField,'Value',0)
3343        SubField_Callback(hObject, eventdata, handles)
3344elseif get(handles.SubField,'Value')% if subfield is already 'on'
3345      [RootPath_1,SubDir_1,RootFile_1,FileIndices_1,FileExt_1]=read_file_boxes_1(handles);
3346     FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndices_1 FileExt_1];
3347else
3348     FileName_1=FileName;% we compare two fields in the same file by default
3349     UvData.FileType{2}=UvData.FileType{1};
3350     set(handles.SubField,'Value',1)
3351end
3352if isfield(UvData,'Field_1')
3353    UvData=rmfield(UvData,'Field_1');% removes the stored second field if it exists
3354end
3355UvData.FileName_1='';% desactivate the use of a constant second file
3356set(handles.uvmat,'UserData',UvData)
3357num_i1=stra2num(get(handles.i1,'String'));
3358num_i2=stra2num(get(handles.i2,'String'));
3359num_j1=stra2num(get(handles.j1,'String'));
3360num_j2=stra2num(get(handles.j2,'String'));
3361
3362errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2);
3363
3364if ~isempty(errormsg)
3365    msgbox_uvmat('ERROR',errormsg);
3366else
3367    set(handles.i1,'BackgroundColor',[1 1 1])
3368    set(handles.i2,'BackgroundColor',[1 1 1])
3369    set(handles.j1,'BackgroundColor',[1 1 1])
3370    set(handles.j2,'BackgroundColor',[1 1 1])
3371    set(handles.FileIndex,'BackgroundColor',[1 1 1])
3372    set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
3373end
3374set(handles.run0,'BackgroundColor',[1 0 0])
3375
3376%-----------------------------------------------
3377% --- reset civ buttons
3378function reset_vel_type(handles_civ0,handle1)
3379for ibutton=1:length(handles_civ0)
3380    set(handles_civ0(ibutton),'BackgroundColor',[0.831 0.816 0.784])
3381    set(handles_civ0(ibutton),'Value',0)
3382end
3383if exist('handle1','var')%handles of selected button
3384        set(handle1,'BackgroundColor',[1 1 0]) 
3385end
3386
3387%-------------------------------------------------------
3388% --- Executes on button press in MENUVOLUME.
3389%-------------------------------------------------------
3390function VOLUME_Callback(hObject, eventdata, handles)
3391%errordlg('command VOL not implemented yet')
3392if ishandle(handles.UVMAT_title)
3393    delete(handles.UVMAT_title)
3394end
3395UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3396if isequal(get(handles.VOLUME,'Value'),1)
3397    set(handles.CheckZoom,'Value',0)
3398    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3399    set(handles.edit_vect,'Value',0)
3400    edit_vect_Callback(hObject, eventdata, handles)
3401    set(handles.edit_object,'Value',0)
3402    set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
3403%     set(handles.cal,'Value',0)
3404%     set(handles.cal,'BackgroundColor',[0 1 0])
3405    set(handles.edit_vect,'Value',0)
3406    edit_vect_Callback(hObject, eventdata, handles)
3407    %initiate set_object GUI
3408    data.Name='VOLUME';
3409    if isfield(UvData,'CoordType')
3410        data.CoordType=UvData.CoordType;
3411    end
3412    if isfield(UvData.Field,'Mesh')&~isempty(UvData.Field.Mesh)
3413        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
3414        data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
3415        data.DX=UvData.Field.Mesh;
3416        data.DY=UvData.Field.Mesh;
3417    elseif isfield(UvData.Field,'AX')&isfield(UvData.Field,'AY')& isfield(UvData.Field,'A')%only image
3418        np=size(UvData.Field.A);
3419        meshx=(UvData.Field.AX(end)-UvData.Field.AX(1))/np(2);
3420        meshy=abs(UvData.Field.AY(end)-UvData.Field.AY(1))/np(1);
3421        data.RangeY=max(meshx,meshy);
3422        data.RangeX=max(meshx,meshy);
3423        data.DX=max(meshx,meshy);
3424    end
3425    data.ParentButton=handles.VOLUME;
3426    PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
3427    [hset_object,UvData.sethandles]=set_object(data,PlotHandles);% call the set_object interface with action on haxes,
3428                                                      % associate the set_object interface handle to the plotting axes
3429    if isfield(UvData.OpenParam,'SetObjectOrigin')                                               
3430    pos_uvmat=get(handles.uvmat,'Position');
3431    pos_set_object(1:2)=UvData.OpenParam.SetObjectOrigin + pos_uvmat(1:2);
3432    pos_set_object(3:4)=UvData.OpenParam.SetObjectSize .* pos_uvmat(3:4); 
3433    set(hset_object,'Position',pos_set_object)
3434    end
3435    UvData.MouseAction='create_object';
3436else
3437    set(handles.VOLUME,'BackgroundColor',[0 1 0])
3438    UvData.MouseAction='none';
3439end
3440set(handles.uvmat,'UserData',UvData)
3441
3442%-------------------------------------------------------
3443function edit_vect_Callback(hObject, eventdata, handles)
3444%-------------------------------------------------------
3445%
3446% UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3447if isequal(get(handles.edit_vect,'Value'),1)
3448    test_civ2=isequal(get(handles.civ2,'BackgroundColor'),[1 1 0]);
3449    test_civ1=isequal(get(handles.VelType,'BackgroundColor'),[1 1 0]);
3450    if ~test_civ2 && ~test_civ1
3451        msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
3452    end
3453    set(handles.record,'Visible','on')
3454    set(handles.edit_vect,'BackgroundColor',[1 1 0])
3455    set(handles.edit_object,'Value',0)
3456    set(handles.CheckZoom,'Value',0)
3457    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3458%     set(handles.create,'Value',0)
3459%     set(handles.create,'BackgroundColor',[0 1 0])
3460    set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
3461    set(gcf,'Pointer','arrow')
3462%     UvData.MouseAction='edit_vect';
3463else
3464    set(handles.record,'Visible','off')
3465    set(handles.edit_vect,'BackgroundColor',[0.7 0.7 0.7])
3466%     UvData.MouseAction='none';
3467end
3468% set(handles.uvmat,'UserData',UvData)
3469
3470%----------------------------------------------
3471function save_mask_Callback(hObject, eventdata, handles)
3472%-----------------------------------------------------------------------
3473UvData=get(handles.uvmat,'UserData');
3474
3475flag=1;
3476npx=size(UvData.Field.A,2);
3477npy=size(UvData.Field.A,1);
3478xi=0.5:npx-0.5;
3479yi=0.5:npy-0.5;
3480[Xi,Yi]=meshgrid(xi,yi);
3481if isfield(UvData,'Object')
3482    for iobj=1:length(UvData.Object)
3483        ObjectData=UvData.Object{iobj};
3484        if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
3485            flagobj=1;
3486            testphys=0; %coordinates in pixels by default
3487            if isfield(ObjectData,'CoordType') && isequal(ObjectData.CoordType,'phys')
3488                if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
3489                    Calib=UvData.XmlData{1}.GeometryCalib;
3490                    testphys=1;
3491                end
3492            end
3493            if isfield(ObjectData,'Coord')& isfield(ObjectData,'Style')
3494                if isequal(ObjectData.Type,'polygon')
3495                    X=ObjectData.Coord(:,1);
3496                    Y=ObjectData.Coord(:,2);
3497                    if testphys
3498                        [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
3499                    end
3500                    flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside                 
3501                elseif isequal(ObjectData.Type,'ellipse')
3502                    if testphys
3503                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3504                    end
3505                    RangeX=max(ObjectData.RangeX);
3506                    RangeY=max(ObjectData.RangeY);
3507                    X2Max=RangeX*RangeX;
3508                    Y2Max=RangeY*RangeY;
3509                    distX=(Xi-ObjectData.Coord(1,1));
3510                    distY=(Yi-ObjectData.Coord(1,2));
3511                    flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
3512                elseif isequal(ObjectData.Type,'rectangle')
3513                    if testphys
3514                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3515                    end
3516                    distX=abs(Xi-ObjectData.Coord(1,1));
3517                    distY=abs(Yi-ObjectData.Coord(1,2));
3518                    flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
3519                end
3520                if isequal(ObjectData.ProjMode,'mask_outside')
3521                    flagobj=~flagobj;
3522                end
3523                flag=flag & flagobj;
3524            end
3525        end
3526    end
3527end
3528% flag=~flag;
3529%mask name
3530RootPath=get(handles.RootPath,'String');
3531RootFile=get(handles.RootFile,'String');
3532RootFile=regexprep(RootFile,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3533filebase=fullfile(RootPath,RootFile);
3534list=get(handles.masklevel,'String');
3535masknumber=num2str(length(list));
3536maskindex=get(handles.masklevel,'Value');
3537mask_name=fullfile_uvmat(RootPath,SubDir,[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
3538%mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
3539imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
3540imflag=flipdim(imflag,1);
3541% imflag=uint8(255*flag);% =0 for flag=0 (vectors=0 when 20<imflag<200)
3542msgbox_uvmat('CONFIRMATION',[mask_name ' saved'])
3543imwrite(imflag,mask_name,'BitDepth',8);
3544
3545%display the mask
3546figure;
3547vec=linspace(0,1,256);%define a linear greyscale colormap
3548map=[vec' vec' vec'];
3549colormap(map)
3550
3551image(imflag);
3552
3553%-------------------------------------------------------------------
3554%-------------------------------------------------------------------
3555%  - FUNCTIONS FOR SETTING PLOTTING PARAMETERS
3556
3557%------------------------------------------------------------------
3558%-------------------------------------------------------------
3559% --- Executes on selection change in transform_fct.
3560function transform_fct_Callback(hObject, eventdata, handles)
3561%-------------------------------------------------------------
3562UvData=get(handles.uvmat,'UserData');
3563menu=get(handles.transform_fct,'String');
3564ind_coord=get(handles.transform_fct,'Value');
3565coord_option=menu{ind_coord};
3566list_transform=get(handles.transform_fct,'UserData');
3567ff=functions(list_transform{end}); 
3568if isequal(coord_option,'more...');
3569    coord_fct='';
3570    prompt = {'Enter the name of the transform function'};
3571    dlg_title = 'user defined transform';
3572    num_lines= 1;
3573    [FileName, PathName] = uigetfile( ...
3574       {'*.m', ' (*.m)';
3575        '*.m',  '.m files '; ...
3576        '*.*', 'All Files (*.*)'}, ...
3577        'Pick a file', ff.file);
3578    if isequal(PathName(end),'/')||isequal(PathName(end),'\')
3579        PathName(end)=[];
3580    end
3581    transform_selected =fullfile(PathName,FileName);
3582    if ~exist(transform_selected,'file')
3583           return
3584    end
3585   [ppp,transform,ext_fct]=fileparts(FileName);% removes extension .m
3586   if ~isequal(ext_fct,'.m')
3587        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
3588        return
3589   end
3590   menu=update_menu(handles.transform_fct,transform);%add the selected fct to the menu
3591   ind_coord=get(handles.transform_fct,'Value');
3592   addpath(PathName)
3593   list_transform{ind_coord}=str2func(transform);% create the function handle corresponding to the newly seleced function
3594   set(handles.transform_fct,'UserData',list_transform)
3595   rmpath(PathName)
3596   % save the new menu in the personal file 'uvmat_perso.mat'
3597   dir_perso=prefdir;%personal Matalb directory
3598   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3599   if exist(profil_perso,'file')
3600       nb_builtin=UvData.OpenParam.NbBuiltin;
3601       for ilist=nb_builtin+1:numel(list_transform)
3602           ff=functions(list_transform{ilist});
3603           transform_fct{ilist-nb_builtin}=ff.file;
3604       end
3605        save (profil_perso,'transform_fct','-append'); %store the root name for future opening of uvmat
3606   end   
3607end
3608
3609%% check the current path to the selected function
3610if isa(list_transform{ind_coord},'function_handle')
3611    func=functions(list_transform{ind_coord});
3612    set(handles.path_transform,'String',fileparts(func.file)); %show the path to the senlected function
3613else
3614    set(handles.path_transform,'String','')
3615end
3616
3617set(handles.CheckFixLimits,'Value',0)
3618set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
3619
3620%% delete drawn objects
3621hother=findobj('Tag','proj_object');%find all the proj objects
3622for iobj=1:length(hother)
3623    delete_object(hother(iobj))
3624end
3625hother=findobj('Tag','DeformPoint');%find all the proj objects
3626for iobj=1:length(hother)
3627    delete_object(hother(iobj))
3628end
3629hh=findobj('Tag','calib_points');
3630if ~isempty(hh)
3631    delete(hh)
3632end
3633hhh=findobj('Tag','calib_marker');
3634if ~isempty(hhh)
3635    delete(hhh)
3636end
3637if isfield(UvData,'Object')
3638     UvData.Object=UvData.Object(1);
3639end
3640set(handles.ListObject,'Value',1)
3641set(handles.ListObject,'String',{'plane'})
3642set(handles.ListObject_1,'Value',1)
3643set(handles.ListObject_1,'String',{'plane'})
3644
3645%delete mask if it is displayed
3646% if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
3647%    UvData=rmfield(UvData,'MaskName'); %will impose mask refresh 
3648% end
3649set(handles.uvmat,'UserData',UvData)
3650run0_Callback(hObject, eventdata, handles)
3651
3652
3653
3654%------------------------------------------------
3655%CALLBACKS FOR PLOTTING PARAMETERS
3656%-------------------------------------------------
3657%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3658% Plot coordinates
3659%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3660%------------------------------------------------------------------------
3661function num_MinX_Callback(hObject, eventdata, handles)
3662%------------------------------------------------------------------------
3663set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3664set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3665update_plot(handles);
3666
3667%------------------------------------------------------------------------
3668function num_MaxX_Callback(hObject, eventdata, handles)
3669%------------------------------------------------------------------------
3670set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3671set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3672update_plot(handles);
3673
3674%------------------------------------------------------------------------
3675function num_MinY_Callback(hObject, eventdata, handles)
3676%------------------------------------------
3677set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3678set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3679update_plot(handles);
3680
3681%------------------------------------------------------------------------
3682function num_MaxY_Callback(hObject, eventdata, handles)
3683%------------------------------------------------------------------------
3684set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3685set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3686update_plot(handles);
3687
3688%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3689% Scalar or image representation
3690%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3691%------------------------------------------------------------------------
3692function num_MinA_Callback(hObject, eventdata, handles)
3693%------------------------------------------
3694set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3695set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3696MinA=str2double(get(handles.num_MinA,'String'));
3697MaxA=str2double(get(handles.num_MaxA,'String'));
3698if MinA>MaxA% switch minA and maxA in case of error
3699    MinA_old=MinA;
3700    MinA=MaxA;
3701    MaxA=MinA_old;
3702    set(handles.num_MinA,'String',num2str(MinA,5));
3703    set(handles.num_MaxA,'String',num2str(MaxA,5));
3704end
3705update_plot(handles);
3706
3707%------------------------------------------------------------------------
3708function num_MaxA_Callback(hObject, eventdata, handles)
3709%------------------------------------------------------------------------
3710set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3711set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3712MinA=str2double(get(handles.num_MinA,'String'));
3713MaxA=str2double(get(handles.num_MaxA,'String'));
3714if MinA>MaxA% switch minA and maxA in case of error
3715        MinA_old=MinA;
3716    MinA=MaxA;
3717    MaxA=MinA_old;
3718    set(handles.num_MinA,'String',num2str(MinA,5));
3719    set(handles.num_MaxA,'String',num2str(MaxA,5));
3720end
3721update_plot(handles);
3722
3723%------------------------------------------------------------------------
3724function CheckFixScalar_Callback(hObject, eventdata, handles)
3725%------------------------------------------------------------------------
3726test=get(handles.CheckFixScalar,'Value');
3727if test
3728    set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3729else
3730    set(handles.CheckFixScalar,'BackgroundColor',[0.7 0.7 0.7])
3731    update_plot(handles);
3732end
3733
3734%-------------------------------------------------------------------
3735function CheckBW_Callback(hObject, eventdata, handles)
3736%-------------------------------------------------------------------
3737update_plot(handles);
3738
3739%-------------------------------------------------------------------
3740function num_Opacity_Callback(hObject, eventdata, handles)
3741update_plot(handles);
3742%-------------------------------------------------------------------
3743
3744%-------------------------------------------------------------------
3745function ListContour_Callback(hObject, eventdata, handles)
3746%-------------------------------------------------------------------
3747val=get(handles.ListContour,'Value');
3748if val==2
3749    set(handles.interval_txt,'Visible','on')
3750    set(handles.num_IncrA,'Visible','on')
3751else
3752    set(handles.interval_txt,'Visible','off')
3753    set(handles.num_IncrA,'Visible','off')
3754end
3755update_plot(handles);
3756
3757%-------------------------------------------------------------------
3758function num_IncrA_Callback(hObject, eventdata, handles)
3759%-------------------------------------------------------------------
3760update_plot(handles);
3761
3762
3763%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3764% Vector representation
3765%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3766%-------------------------------------------------------------------
3767function CheckHideWarning_Callback(hObject, eventdata, handles)
3768%-------------------------------------------------------------------
3769update_plot(handles);
3770
3771%-------------------------------------------------------------------
3772function CheckHideFalse_Callback(hObject, eventdata, handles)
3773%-------------------------------------------------------------------
3774update_plot(handles);
3775
3776%-------------------------------------------------------------------
3777function num_VecScale_Callback(hObject, eventdata, handles)
3778%-------------------------------------------------------------------
3779set(handles.CheckFixVectors,'Value',1);
3780set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3781update_plot(handles);
3782
3783%-------------------------------------------------------------------
3784function CheckFixVectors_Callback(hObject, eventdata, handles)
3785%-------------------------------------------------------------------
3786test=get(handles.CheckFixVectors,'Value');
3787if test
3788    set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3789else
3790    update_plot(handles);
3791    %set(handles.num_VecScale,'String',num2str(ScalOut.num_VecScale,3))
3792    set(handles.CheckFixVectors,'BackgroundColor',[0.7 0.7 0.7])
3793end
3794
3795%------------------------------------------------------------------------
3796% --- Executes on selection change in CheckDecimate4 (nb_vec/4).
3797function CheckDecimate4_Callback(hObject, eventdata, handles)
3798%------------------------------------------------------------------------
3799update_plot(handles);
3800
3801%------------------------------------------------------------------------
3802% --- Executes on selection change in ColorCode menu
3803function ColorCode_Callback(hObject, eventdata, handles)
3804%------------------------------------------------------------------------
3805% edit the choice for color code
3806update_color_code_boxes(handles);
3807update_plot(handles);
3808
3809%------------------------------------------------------------------------
3810function update_color_code_boxes(handles)
3811%------------------------------------------------------------------------
3812list_code=get(handles.ColorCode,'String');% list menu fields
3813colcode= list_code{get(handles.ColorCode,'Value')}; % selected field
3814enable_slider='off';%default
3815enable_bounds='off';%default
3816enable_scalar='off';%default
3817switch colcode
3818    case {'rgb','bgr'}
3819        enable_slider='on';
3820        enable_bounds='on';
3821        enable_scalar='on';
3822    case '64 colors'
3823        enable_bounds='on';
3824        enable_scalar='on';
3825end
3826set(handles.Slider1,'Visible',enable_slider)
3827set(handles.Slider2,'Visible', enable_slider)
3828set(handles.num_ColCode1,'Visible',enable_slider)
3829set(handles.num_ColCode2,'Visible',enable_slider)
3830set(handles.TitleColCode1,'Visible',enable_slider)
3831set(handles.TitleColCode2,'Visible',enable_slider)
3832set(handles.CheckFixVecColor,'Visible',enable_bounds)
3833set(handles.num_MinVec,'Visible',enable_bounds)
3834set(handles.num_MaxVec,'Visible',enable_bounds)
3835set(handles.ColorScalar,'Visible',enable_scalar)
3836set_vec_col_bar(handles)
3837
3838%------------------------------------------------------------------
3839% --- Executes on selection change in ColorScalar: choice of the color code.
3840function ColorScalar_Callback(hObject, eventdata, handles)
3841%------------------------------------------------------------------
3842% edit the choice for color code
3843list_scalar=get(handles.ColorScalar,'String');% list menu fields
3844col_scalar= list_scalar{get(handles.ColorScalar,'Value')}; % selected field
3845if isequal(col_scalar,'ima_cor')
3846    set(handles.CheckFixVecColor,'Value',1)%fixed scale by default
3847    ColorCode='rgb';
3848    set(handles.num_MinVec,'String','0')
3849    set(handles.num_MaxVec,'String','1')
3850    set(handles.num_ColCode1,'String','0.333')
3851    set(handles.num_ColCode2,'String','0.666')
3852else
3853    set(handles.CheckFixVecColor,'Value',0)%auto scale between min,max by default
3854    ColorCode='64 colors';
3855end
3856ColorCodeList=get(handles.ColorCode,'String');
3857ichoice=find(strcmp(ColorCode,ColorCodeList),1);
3858set(handles.ColorCode,'Value',ichoice)% set color code in the menu
3859
3860update_color_code_boxes(handles);
3861%replot the current graph
3862run0_Callback(hObject, eventdata, handles)
3863
3864%----------------------------------------------------------------
3865% -- Executes on slider movement to set the color code
3866%
3867function Slider1_Callback(hObject, eventdata, handles)
3868%------------------------------------------------------------------
3869slider1=get(handles.Slider1,'Value');
3870min_val=str2num(get(handles.num_MinVec,'String'));
3871max_val=str2num(get(handles.num_MaxVec,'String'));
3872col=min_val+(max_val-min_val)*slider1;
3873set(handles.num_ColCode1,'String',num2str(col))
3874if(get(handles.Slider2,'Value') < col)%move also the second slider at the same value if needed
3875    set(handles.Slider2,'Value',col)
3876    set(handles.num_ColCode2,'String',num2str(col))
3877end
3878set_vec_col_bar(handles)
3879update_plot(handles);
3880
3881%----------------------------------------------------------------
3882% Executes on slider movement to set the color code
3883%----------------------------------------------------------------
3884function Slider2_Callback(hObject, eventdata, handles)
3885slider2=get(handles.Slider2,'Value');
3886min_val=str2num(get(handles.num_MinVec,'String'));
3887max_val=str2num(get(handles.num_MaxVec,'String'));
3888col=min_val+(max_val-min_val)*slider2;
3889set(handles.num_ColCode2,'String',num2str(col))
3890if(get(handles.Slider1,'Value') > col)%move also the first slider at the same value if needed
3891    set(handles.Slider1,'Value',col)
3892    set(handles.num_ColCode1,'String',num2str(col))
3893end
3894set_vec_col_bar(handles)
3895update_plot(handles);
3896
3897%----------------------------------------------------------------
3898% --- Execute on return carriage on the edit box corresponding to slider 1
3899%----------------------------------------------------------------
3900function num_ColCode1_Callback(hObject, eventdata, handles)
3901set_vec_col_bar(handles)
3902update_plot(handles);
3903
3904%----------------------------------------------------------------
3905% --- Execute on return carriage on the edit box corresponding to slider 2
3906%----------------------------------------------------------------
3907function num_ColCode2_Callback(hObject, eventdata, handles)
3908set_vec_col_bar(handles)
3909update_plot(handles);
3910%------------------------------------------------------------------------
3911%-------------------------------------------------------
3912% --- Executes on button press in CheckFixVecColor.
3913%-------------------------------------------------------
3914function VecColBar_Callback(hObject, eventdata, handles)
3915set_vec_col_bar(handles)
3916
3917%------------------------------------------------------------------------
3918% --- Executes on button press in CheckFixVecColor.
3919function CheckFixVecColor_Callback(hObject, eventdata, handles)
3920%------------------------------------------------------------------------
3921if ~get(handles.CheckFixVecColor,'Value')
3922    update_plot(handles);
3923end
3924
3925%------------------------------------------------------------------------
3926% --- Executes on selection change in num_MaxVec.
3927function num_MinVec_Callback(hObject, eventdata, handles)
3928%------------------------------------------------------------------------
3929max_vec_Callback(hObject, eventdata, handles)
3930
3931%------------------------------------------------------------------------
3932% --- Executes on selection change in num_MaxVec.
3933function num_MaxVec_Callback(hObject, eventdata, handles)
3934%------------------------------------------------------------------------
3935set(handles.CheckFixVecColor,'Value',1)
3936CheckFixVecColor_Callback(hObject, eventdata, handles)
3937min_val=str2num(get(handles.num_MinVec,'String'));
3938max_val=str2num(get(handles.num_MaxVec,'String'));
3939slider1=get(handles.Slider1,'Value');
3940slider2=get(handles.Slider2,'Value');
3941colcode1=min_val+(max_val-min_val)*slider1;
3942colcode2=min_val+(max_val-min_val)*slider2;
3943set(handles.num_ColCode1,'String',num2str(colcode1))
3944set(handles.num_ColCode2,'String',num2str(colcode2))
3945update_plot(handles);
3946
3947%------------------------------------------------------------------------
3948% --- update the display of color code for vectors (on vecColBar)
3949function set_vec_col_bar(handles)
3950%------------------------------------------------------------------------
3951%get the image of the color display button 'VecColBar' in pixels
3952set(handles.VecColBar,'Unit','pixel');
3953pos_vert=get(handles.VecColBar,'Position');
3954set(handles.VecColBar,'Unit','Normalized');
3955width=ceil(pos_vert(3));
3956height=ceil(pos_vert(4));
3957
3958%get slider indications
3959list=get(handles.ColorCode,'String');
3960ichoice=get(handles.ColorCode,'Value');
3961colcode.ColorCode=list{ichoice};
3962colcode.MinVec=str2num(get(handles.num_MinVec,'String'));
3963colcode.MaxVec=str2num(get(handles.num_MaxVec,'String'));
3964test3color=strcmp(colcode.ColorCode,'rgb') || strcmp(colcode.ColorCode,'bgr');
3965if test3color
3966    colcode.ColCode1=str2num(get(handles.num_ColCode1,'String'));
3967    colcode.ColCode2=str2num(get(handles.num_ColCode2,'String'));
3968end
3969vec_C=colcode.MinVec+(colcode.MaxVec-colcode.MinVec)*(0.5:width-0.5)/width;%sample of vec_C values from min to max
3970[colorlist,col_vec]=set_col_vec(colcode,vec_C);
3971oneheight=ones(1,height);
3972A1=colorlist(col_vec,1)*oneheight;
3973A2=colorlist(col_vec,2)*oneheight;
3974A3=colorlist(col_vec,3)*oneheight;
3975A(:,:,1)=A1';
3976A(:,:,2)=A2';
3977A(:,:,3)=A3';
3978set(handles.VecColBar,'Cdata',A)
3979
3980%-------------------------------------------------------------------
3981function update_plot(handles)
3982%-------------------------------------------------------------------
3983UvData=get(handles.uvmat,'UserData');
3984AxeData=UvData.axes3;% retrieve the current plotted data
3985PlotParam=read_GUI(handles.uvmat);
3986[tild,PlotParamOut]= plot_field(AxeData,handles.axes3,PlotParam);
3987write_plot_param(handles,PlotParamOut); %update the auto plot parameters
3988
3989%------------------------------------------------------------------------
3990%------------------------------------------------------------------------
3991%   SELECTION AND EDITION OF PROJECTION OBJECTS
3992%------------------------------------------------------------------------
3993%------------------------------------------------------------------------
3994
3995% --- Executes on selection change in ListObject_1.
3996function ListObject_1_Callback(hObject, eventdata, handles)
3997list_str=get(handles.ListObject,'String');
3998UvData=get(handles.uvmat,'UserData');
3999ObjectData=UvData.Object{get(handles.ListObject_1,'Value')};
4000
4001%% update the projection plot on uvmat
4002ProjData= proj_field(UvData.Field,ObjectData);%project the current input field on object ObjectData
4003plot_field(ProjData,handles.axes3,read_GUI(handles.uvmat));% plot the projected field;
4004%replot all the objects within the new projected field
4005for IndexObj=1:numel(list_str)
4006    IndexObj
4007        hobject=UvData.Object{IndexObj}.DisplayHandle.uvmat
4008        if isempty(hobject) || ~ishandle(hobject)
4009            hobject=handles.axes3
4010        end
4011        if isequal(IndexObj,get(handles.ListObject,'Value'))
4012            objectcolor='m'; %paint in magenta the currently selected object in ListObject
4013        else
4014            objectcolor='b';
4015        end
4016        UvData.Object{IndexObj}.DisplayHandle.uvmat=plot_object(UvData.Object{IndexObj},ObjectData,hobject,objectcolor);%draw the object in uvmat     
4017end
4018set(handles.uvmat,'UserData',UvData)
4019
4020%% display the object parameters if the GUI set_object is already opened
4021if ~get(handles.ViewObject,'Value')
4022    ZBounds=0; % default
4023    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4024        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4025        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4026    end
4027    ObjectData.Name=list_str{get(handles.ListObject_1,'Value')};
4028    set_object(ObjectData,[],ZBounds);
4029    set(handles.ViewObject,'Value',1)% show that the selected object in ListObject_1 is currently visualised
4030end
4031
4032%  desactivate the edit object mode
4033set(handles.edit_object,'Value',0)
4034set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7])
4035
4036%------------------------------------------------------------------------
4037% --- Executes on selection change in ListObject.
4038function ListObject_Callback(hObject, eventdata, handles)
4039%------------------------------------------------------------------------
4040list_str=get(handles.ListObject,'String');
4041IndexObj=get(handles.ListObject,'Value');%present object selection
4042
4043%% The object  is displayed in set_object if this GUI is already opened
4044UvData=get(handles.uvmat,'UserData');
4045ObjectData=UvData.Object{IndexObj};
4046hset_object=findobj(allchild(0),'tag','set_object');
4047if ~isempty(hset_object)
4048    ZBounds=0; % default
4049    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4050        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4051        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4052    end
4053    ObjectData.Name=list_str{IndexObj};
4054    set_object(ObjectData,[],ZBounds);
4055    set(handles.ViewField,'Value',1)% show that the selected object in ListObject is currently visualised
4056end
4057
4058%%  desactivate the edit object mode
4059set(handles.edit_object,'Value',0)
4060set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7])
4061
4062%% update the  plot on view_field if view_field is already openened
4063hview_field=findobj(allchild(0),'tag','view_field');
4064if isempty(hview_field)
4065    hhview_field.axes3=[];
4066else
4067    Data=get(hview_field,'UserData');
4068    hhview_field=guidata(hview_field);
4069    ProjData= proj_field(UvData.Field,ObjectData);%project the current interface field on ObjectData
4070    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.axes3,read_GUI(hview_field));%read plotting parameters on the uvmat interfachhview_fiel
4071    write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4072    haxes=findobj(hview_field,'tag','axes3');
4073    pos=get(hview_field,'Position'); 
4074    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4075        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4076        pos_table=get(h_TableDisplay,'Position');
4077        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4078        drawnow% needed to change position before the next command
4079        set(hview_field,'UserData',Data);% restore the previously stored GUI position after GUI resizing
4080    else
4081        set(hview_field,'Position',Data.GUISize)% return to the previously stored GUI position and size
4082    end
4083end
4084
4085%% update the color of the graphic object representation: the selected object in magenta, others in blue
4086update_object_color(handles.axes3,hhview_field.axes3,UvData.Object{IndexObj}.DisplayHandle.uvmat)
4087
4088%------------------------------------------------------------------------
4089%--- update the color representation of objects (indicating the selected ones)
4090function update_object_color(axes_uvmat,axes_view_field,DisplayHandle)
4091%------------------------------------------------------------------------
4092if isempty(axes_view_field)% case with no view_field plot
4093hother=[findobj(axes_uvmat,'Tag','proj_object');findobj(axes_uvmat,'Tag','DeformPoint')];%find all the proj object and deform point representations
4094else
4095hother=[findobj(axes_uvmat,'Tag','proj_object') ;findobj(axes_view_field,'Tag','proj_object');... %find all the proj object representations
4096findobj(axes_uvmat,'Tag','DeformPoint'); findobj(axes_view_field,'Tag','DeformPoint')];%find all the deform point representations
4097end
4098for iobj=1:length(hother)
4099    if isequal(get(hother(iobj),'Type'),'rectangle')||isequal(get(hother(iobj),'Type'),'patch')
4100        set(hother(iobj),'EdgeColor','b')
4101        if isequal(get(hother(iobj),'FaceColor'),'m')
4102            set(hother(iobj),'FaceColor','b')
4103        end
4104    elseif isequal(get(hother(iobj),'Type'),'image')
4105        Acolor=get(hother(iobj),'CData');
4106        Acolor(:,:,1)=zeros(size(Acolor,1),size(Acolor,2));
4107        set(hother(iobj),'CData',Acolor);
4108    else
4109        set(hother(iobj),'Color','b')
4110    end
4111    set(hother(iobj),'Selected','off')
4112end
4113if ishandle(DisplayHandle)
4114    linetype=get(DisplayHandle,'Type');
4115    if isequal(linetype,'line')
4116        set(DisplayHandle,'Color','m'); %set the selected object to magenta color
4117    elseif isequal(linetype,'rectangle')
4118        set(DisplayHandle,'EdgeColor','m'); %set the selected object to magenta color
4119    elseif isequal(linetype,'patch')
4120        set(DisplayHandle,'FaceColor','m'); %set the selected object to magenta color
4121    end
4122    SubObjectData=get(DisplayHandle,'UserData');
4123    if isfield(SubObjectData,'SubObject') & ishandle(SubObjectData.SubObject)
4124        for iobj=1:length(SubObjectData.SubObject)
4125            hsub=SubObjectData.SubObject(iobj);
4126            if isequal(get(hsub,'Type'),'rectangle')
4127                set(hsub,'EdgeColor','m'); %set the selected object to magenta color
4128            elseif isequal(get(hsub,'Type'),'image')
4129                Acolor=get(hsub,'CData');
4130                Acolor(:,:,1)=Acolor(:,:,3);
4131                set(hsub,'CData',Acolor);
4132            else
4133                set(hsub,'Color','m')
4134            end
4135        end
4136    end
4137    if isfield(SubObjectData,'DeformPoint') & ishandle(SubObjectData.DeformPoint)
4138        set(SubObjectData.DeformPoint,'Color','m')
4139    end
4140end
4141
4142%-------------------------------------------------------------------
4143% --- Executes on selection change in edit_object.
4144function edit_object_Callback(hObject, eventdata, handles)
4145%-------------------------------------------------------------------
4146UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4147hset_object=findobj(allchild(0),'Tag','set_object');
4148if get(handles.edit_object,'Value')
4149    set(handles.edit_object,'BackgroundColor',[1,1,0]) 
4150    %suppress the other options
4151    set(handles.CheckZoom,'Value',0)
4152    CheckZoom_Callback(hObject, eventdata, handles)
4153    hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4154    if ishandle(hgeometry_calib)
4155        hhgeometry_calib=guidata(hgeometry_calib);
4156        set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4157        set(hhgeometry_calib.edit_append,'BackgroundColor',[0.7 0.7 0.7])
4158    end
4159    set(handles.ViewObject,'value',1)
4160    ViewObject_Callback(hObject, eventdata, handles)
4161else % desctivate object edit mode
4162    set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4163    if ~isempty(hset_object)% open the
4164        hhset_object=guidata(hset_object);
4165        set(hhset_object.PLOT,'enable','off');
4166        set(get(hset_object,'children'),'enable','inactive')
4167    end
4168end
4169
4170
4171%------------------------------------------------------------------------
4172% --- Executes on button press in ViewObject.
4173function ViewObject_Callback(hObject, eventdata, handles)
4174%------------------------------------------------------------------------
4175check_view=get(handles.ViewObject,'Value');
4176
4177if check_view %activate set_object   
4178    IndexObj=get(handles.ListObject,'Value');
4179    list_object=get(handles.ListObject,'String');
4180    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4181    UvData.Object{IndexObj}.Name=list_object{IndexObj};
4182    if numel(UvData.Object)<IndexObj;% error in UvData
4183        msgbox_uvmat('ERROR','invalid object list')
4184        return
4185    end
4186    ZBounds=0; % default
4187    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4188        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4189        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4190    end
4191%     set(handles.ListObject_1,'Value',IndexObj);%restore ListObject selection after set_object deletion
4192    data=UvData.Object{IndexObj};
4193    if ~isfield(data,'Type')% default plane
4194        data.Type='plane';
4195    end
4196    if isfield(UvData,'Field')
4197        Field=UvData.Field;
4198        if isfield(UvData.Field,'Mesh')&&~isempty(UvData.Field.Mesh)
4199            data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4200            if strcmp(data.Type,'line')||strcmp(data.Type,'polyline')
4201                data.RangeY=UvData.Field.Mesh;
4202            else
4203                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4204            end
4205            data.DX=UvData.Field.Mesh;
4206            data.DY=UvData.Field.Mesh;
4207        end
4208        if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4209            data.Coord=[0 0 0]; %default
4210        end
4211        if isfield(Field,'CoordUnit')
4212            data.CoordUnit=Field.CoordUnit;
4213        end
4214    end
4215    hset_object=set_object(data,[],ZBounds);
4216    hhset_object=guidata(hset_object);
4217    if get(handles.edit_object,'Value')% edit mode
4218        set(hhset_object.PLOT,'Enable','on')
4219        set(get(hset_object,'children'),'enable','on')
4220    else
4221        set(hhset_object.PLOT,'Enable','off')
4222        set(get(hset_object,'children'),'enable','inactive')% deactivate the GUI except SAVE
4223        set(hhset_object.SAVE,'Enable','on')
4224    end
4225else
4226    hset_object=findobj(allchild(0),'tag','set_object');
4227    if ~isempty(hset_object)
4228        delete(hset_object)% delete existing version of set_object
4229    end
4230end
4231 
4232
4233%------------------------------------------------------------------------
4234% --- Executes on button press in ViewField.
4235function ViewField_Callback(hObject, eventdata, handles)
4236%------------------------------------------------------------------------
4237check_view=get(handles.ViewField,'Value');
4238
4239if check_view
4240    IndexObj=get(handles.ListObject,'Value');
4241    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4242    if numel(UvData.Object)<IndexObj(end);% error in UvData
4243        msgbox_uvmat('ERROR','invalid object list')
4244        return
4245    end
4246    ZBounds=0; % default
4247    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4248        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4249        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4250    end
4251    set(handles.ListObject,'Value',IndexObj);%restore ListObject selection after set_object deletion
4252    if ~isfield(UvData.Object{IndexObj(1)},'Type')% default plane
4253        UvData.Object{IndexObj(1)}.Type='plane';
4254    end
4255    list_object=get(handles.ListObject,'String');
4256    UvData.Object{IndexObj(end)}.Name=list_object{IndexObj(end)};
4257   
4258    %% show the projection of the selected object on view_field
4259    ProjData= proj_field(UvData.Field,UvData.Object{IndexObj});%project the current field on ObjectData
4260    hview_field=findobj(allchild(0),'tag','view_field');
4261    if isempty(hview_field)
4262        hview_field=view_field;
4263    end
4264    hhview_field=guidata(hview_field);
4265    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.axes3,read_GUI(hview_field));%read plotting parameters on the GUI view_field);
4266    write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4267    haxes=findobj(hview_field,'tag','axes3');
4268    pos=get(hview_field,'Position');
4269    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4270        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4271        pos_table=get(h_TableDisplay,'Position');
4272        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4273    else
4274        Data=get(hview_field,'UserData');
4275        set(hview_field,'Position',Data.GUISize)% restore the size of view_field for plots
4276    end
4277else
4278    hview_field=findobj(allchild(0),'tag','view_field');
4279    if ~isempty(hview_field)
4280        delete(hview_field)% delete existing version of set_object
4281    end
4282end
4283
4284
4285%------------------------------------------------------------------------
4286% --- Executes on button press in delete_object.
4287function delete_object_Callback(hObject, eventdata, handles)
4288%------------------------------------------------------------------------
4289IndexObj=get(handles.ListObject,'Value');%projection object selected for view_field
4290IndexObj_1=get(handles.ListObject_1,'Value');%projection object selected for uvmat plot
4291if IndexObj>1 && ~isequal(IndexObj,IndexObj_1) % do not delete the object used for the uvmat plot
4292    delete_object(IndexObj)
4293end
4294
4295%------------------------------------------------------------------------
4296%------------------------------------------------------------------------
4297%  II - TOOLS FROM THE UPPER MENU BAR
4298%------------------------------------------------------------------------
4299%------------------------------------------------------------------------
4300
4301%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4302% Export  Menu Callbacks
4303%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4304%------------------------------------------------------------------------
4305% --- Executes on button press in Menu/Export/field in workspace.
4306function MenuExportField_Callback(hObject, eventdata, handles)
4307%------------------------------------------------------------------------
4308global Data_uvmat
4309Data_uvmat=get(handles.uvmat,'UserData');
4310evalin('base','global Data_uvmat')%make CurData global in the workspace
4311display('current field :')
4312evalin('base','Data_uvmat') %display CurData in the workspace
4313commandwindow; %brings the Matlab command window to the front
4314
4315%------------------------------------------------------------------------
4316% --- Executes on button press in Menu/Export/extract figure.
4317function MenuExportFigure_Callback(hObject, eventdata, handles)
4318%------------------------------------------------------------------------
4319% huvmat=get(handles.MenuExport,'parent');
4320hfig=figure;
4321copyobj(handles.axes3,hfig);
4322map=colormap(handles.axes3);
4323colormap(map);%transmit the current colormap to the zoom fig
4324colorbar
4325
4326% %------------------------------------------------------
4327% % --- Executes on button press in Menu/Export/extract figure.
4328% %------------------------------------------------------
4329% function MenuExport_plot_Callback(hObject, eventdata, handles)
4330% huvmat=get(handles.MenuExport_plot,'parent');
4331% UvData=get(huvmat,'UserData');
4332% hfig=figure;
4333% newaxes=copyobj(handles.axes3,hfig);
4334% map=colormap(handles.axes3);
4335% colormap(map);%transmit the current colormap to the zoom fig
4336% colorbar
4337
4338%
4339% % --------------------------------------------------------------------
4340% function Insert_Callback(hObject, eventdata, handles)
4341%
4342
4343%------------------------------------------------------------------------
4344% --------------------------------------------------------------------
4345function MenuExportMovie_Callback(hObject, eventdata, handles)
4346% --------------------------------------------------------------------
4347set(handles.MenuExportMovie,'BusyAction','queue')% activate the button
4348huvmat=get(handles.run0,'parent');
4349UvData=get(huvmat,'UserData');
4350%[xx,xx,FileBase]=read_file_boxes(handles);
4351[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4352FileBase=fullfile(RootPath,RootFile);
4353 %read the current input file name
4354prompt = {'movie file name';'frames per second';'frame resolution (*[512x384] pixels)';'axis position relative to the frame';'total frame number (starting from the current uvmat display)'};
4355dlg_title = 'select properties of the output avi movie';
4356num_lines= 1;
4357def     = {[FileBase '_out.avi'];'10';'1';'[0.03 0.05 0.95 0.92]';'10'};
4358answer = inputdlg(prompt,dlg_title,num_lines,def,'on');
4359aviname=answer{1};
4360fps=str2double(answer{2});
4361% check for existing file with output name aviname
4362if exist(aviname,'file')
4363    backup=aviname;
4364    testexist=2;
4365    while testexist==2
4366        backup=[backup '~'];
4367        testexist=exist(backup,'file');     
4368    end
4369    [success,message]=copyfile(aviname,backup);%make backup of the existing file
4370    if isequal(success,1)
4371        delete(aviname)%delete existing file
4372    else
4373        msgbox_uvmat('ERROR',message)
4374        return
4375    end
4376end
4377%create avi open
4378aviobj=avifile(aviname,'Compression','None','fps',fps);
4379
4380%display first view for tests
4381newfig=figure;
4382newaxes=copyobj(handles.axes3,newfig);%new plotting axes in the new figure
4383set(newaxes,'Tag','movieaxes')
4384nbpix=[512 384]*str2double(answer{3});
4385set(gcf,'Position',[1 1 nbpix])% resolution XVGA
4386set(newaxes,'Position',eval(answer{4}));
4387map=colormap(handles.axes3);
4388colormap(map);%transmit the current colormap to the zoom fig
4389msgbox_uvmat('INPUT_Y-N',{['adjust figure ' num2str(newfig) ' with its matlab edit menu '] ;...
4390        ['then press OK to get the avi movie as a copy of figure ' num2str(newfig) ' display']});
4391UvData.plotaxes=newaxes;% the axis in the new figure becomes the current main plotting axes
4392set(huvmat,'UserData',UvData);
4393increment=str2num(get(handles.increment_scan,'String')); %get the field increment d
4394set(handles.STOP,'Visible','on')
4395set(handles.speed,'Visible','on')
4396set(handles.speed_txt,'Visible','on')
4397set(handles.Movie,'BusyAction','queue')
4398
4399%imin=str2double(get(handles.i1,'String'));
4400imax=str2double(answer{5});
4401% if isfield(UvData,'Time')
4402htitle=get(newaxes,'Title');
4403xlim=get(newaxes,'XLim');
4404ylim=get(newaxes,'YLim');
4405set(htitle,'Position',[xlim(2)+0.07*(xlim(2)-xlim(1)) ylim(2)-0.05*(ylim(2)-ylim(1)) 0])
4406time_str=get(handles.abs_time,'String');
4407set(htitle,'String',['t=' time_str])
4408set(handles.speed,'Value',1)
4409for i=1:imax
4410    if get(handles.speed,'Value')~=0 && isequal(get(handles.MenuExportMovie,'BusyAction'),'queue') % enable STOP command
4411            runpm(hObject,eventdata,handles,increment)% run plus
4412            drawnow
4413            time_str=get(handles.abs_time,'String');
4414            if ishandle(htitle)
4415             set(htitle,'String',['t=' time_str])
4416            end
4417            mov=getframe(newfig);
4418            aviobj=addframe(aviobj,mov);
4419    end
4420end
4421aviobj=close(aviobj);
4422UvData=rmfield(UvData,'plotaxes');
4423%UvData.Object{1}.plotaxes=handles.axes3;
4424set(huvmat,'UserData',UvData);
4425msgbox_uvmat('CONFIRMATION',{['movie ' aviname ' created '];['with ' num2str(imax) ' frames']})
4426
4427
4428%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4429% Projection Objects Menu Callbacks
4430%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4431
4432% -----------------------------------------------------------------------
4433function Menupoints_Callback(hObject, eventdata, handles)
4434%------------------------------------------------------------------------
4435data.Type='points';
4436data.ProjMode='projection';%default
4437data.ProjModeMenu={};% do not restrict ProjMode menus
4438create_object(data,handles)
4439
4440% -----------------------------------------------------------------------
4441function Menuline_Callback(hObject, eventdata, handles)
4442%------------------------------------------------------------------------
4443data.Type='line';
4444data.ProjMode='projection';%default
4445data.ProjModeMenu={};% do not restrict ProjMode menus
4446create_object(data,handles)
4447
4448%------------------------------------------------------------------------
4449function Menupolyline_Callback(hObject, eventdata, handles)
4450%------------------------------------------------------------------------
4451data.Type='polyline';
4452data.ProjMode='projection';%default
4453data.ProjModeMenu={};% do not restrict ProjMode menus
4454create_object(data,handles)
4455
4456%------------------------------------------------------------------------
4457function Menupolygon_Callback(hObject, eventdata, handles)
4458%------------------------------------------------------------------------
4459data.Type='polygon';
4460data.ProjMode='inside';%default
4461data.ProjModeMenu={};% do not restrict ProjMode menus
4462create_object(data,handles)
4463
4464%------------------------------------------------------------------------
4465function Menurectangle_Callback(hObject, eventdata, handles)
4466%------------------------------------------------------------------------
4467data.Type='rectangle';
4468data.ProjMode='inside';%default
4469data.ProjModeMenu={};% do not restrict ProjMode menus
4470create_object(data,handles)
4471
4472%------------------------------------------------------------------------
4473function Menuellipse_Callback(hObject, eventdata, handles)
4474%------------------------------------------------------------------------
4475data.Type='ellipse';
4476data.ProjMode='inside';%default
4477data.ProjModeMenu={};% do not restrict ProjMode menus
4478create_object(data,handles)
4479
4480%------------------------------------------------------------------------
4481function MenuMaskObject_Callback(hObject, eventdata, handles)
4482%------------------------------------------------------------------------
4483data.Type='polygon';
4484data.TypeMenu={'polygon'};
4485data.ProjMode='mask_inside';%default
4486data.ProjModeMenu={'mask_inside';'mask_outside'};
4487create_object(data,handles)
4488
4489%------------------------------------------------------------------------
4490function Menuplane_Callback(hObject, eventdata, handles)
4491%------------------------------------------------------------------------
4492data.Type='plane';
4493data.ProjMode='projection';%default
4494data.ProjModeMenu={};% do not restrict ProjMode menus
4495create_object(data,handles)
4496
4497%------------------------------------------------------------------------
4498function Menuvolume_Callback(hObject, eventdata, handles)
4499%------------------------------------------------------------------------
4500data.Type='volume';
4501data.ProjMode='interp';%default
4502data.ProjModeMenu={};
4503% set(handles.create,'Visible','on')
4504% set(handles.create,'Value',1)
4505% VOLUME_Callback(hObject,eventdata,handles)data.ProjModeMenu={};
4506create_object(data,handles)
4507
4508%------------------------------------------------------------------------
4509% --- generic function used for the creation of a projection object
4510function create_object(data,handles)
4511%------------------------------------------------------------------------
4512% desactivate geometric calibration if opened
4513hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4514if ishandle(hgeometry_calib)
4515    hhgeometry_calib=guidata(hgeometry_calib);
4516    set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4517    set(hhgeometry_calib.edit_append,'BackgroundColor',[0.7 0.7 0.7])
4518end
4519set(handles.edit_object,'Value',0); %suppress the object edit mode
4520set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4521ListObject=get(handles.ListObject,'String');
4522if ~strcmp(ListObject{end},'')
4523    ListObject=[ListObject;{''}]; %append a blank to the list (if nort already done) to indicate the creation of a new object
4524    set(handles.ListObject,'String',ListObject)
4525end
4526IndexObj=length(ListObject);
4527set(handles.ListObject,'Value',IndexObj)
4528UvData=get(handles.uvmat,'UserData');
4529UvData.Object{IndexObj}=[]; %create a new empty object
4530UvData.Object{IndexObj}.DisplayHandle.uvmat=handles.axes3; % axes for plot_object
4531UvData.Object{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4532data.Name=data.Type;% default name=type
4533data.Coord=[0 0]; %default
4534if isfield(UvData,'Field')
4535    Field=UvData.Field;
4536    if isfield(UvData.Field,'Mesh')&&~isempty(UvData.Field.Mesh)
4537        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4538        if strcmp(data.Type,'line')||strcmp(data.Type,'polyline')||strcmp(data.Type,'points')
4539            data.RangeY=UvData.Field.Mesh;
4540        else
4541            data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4542        end
4543        data.DX=UvData.Field.Mesh;
4544        data.DY=UvData.Field.Mesh;
4545    end
4546    if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4547         data.Coord=[0 0 0]; %default
4548    end
4549    if isfield(Field,'CoordUnit')
4550        data.CoordUnit=Field.CoordUnit;
4551    end
4552end
4553if ishandle(handles.UVMAT_title)
4554    delete(handles.UVMAT_title)%delete the initial display of uvmat if no field has been entered
4555end
4556hset_object=set_object(data,handles);% call the set_object interface
4557hhset_object=guidata(hset_object);
4558hchild=get(hset_object,'children');
4559set(hchild,'enable','on')
4560set(handles.uvmat,'UserData',UvData)
4561set(handles.CheckZoom,'Value',0) %desactivate the zoom for object creation by the mouse
4562CheckZoom_Callback(handles.uvmat, [], handles)
4563set(handles.delete_object,'Visible','on')
4564
4565%------------------------------------------------------------------------
4566function MenuBrowseObject_Callback(hObject, eventdata, handles)
4567%------------------------------------------------------------------------
4568%get the object file
4569[FileName, PathName, filterindex] = uigetfile( ...
4570       {'*.xml;*.mat', ' (*.xml,*.mat)';
4571       '*.xml',  '.xml files '; ...
4572        '*.mat',  '.mat matlab files '}, ...
4573        'Pick an xml Object file',get(handles.RootPath,'String'));
4574fileinput=[PathName FileName];%complete file name
4575sizf=size(fileinput);
4576if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
4577
4578%read the file
4579[data,heading]=xml2struct(fileinput);
4580if ~strcmp(heading,'ProjObject')
4581    msgbox_uvmat('WARNING','The xml file does not have the heading ProjObject for projection objects')
4582end
4583[tild,data.Name]=fileparts(FileName);% object name set as file name
4584ListObject=get(handles.ListObject,'String');
4585if ~strcmp(ListObject{end},'')
4586    ListObject=[ListObject;{''}]; %append a blank to the list (if not already done) to indicate the creation of a new object
4587    set(handles.ListObject,'String',ListObject)
4588end
4589IndexObj=length(ListObject);
4590
4591UvData=get(handles.uvmat,'UserData');
4592UvData.Object{IndexObj}=[]; %create a new empty object
4593UvData.Object{IndexObj}.DisplayHandle.uvmat=[]; %no plot handle before plot_field operation
4594UvData.Object{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4595set(handles.uvmat,'UserData',UvData)
4596set(handles.ListObject,'Value',IndexObj)
4597hset_object=set_object(data);% call the set_object interface
4598set(get(hset_object,'children'),'enable','on')% enable edit action on elements on GUI set_object
4599set(handles.edit_object,'Value',0); %suppress the object edit mode
4600set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4601set(handles.delete_object,'Visible','on')
4602
4603
4604%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4605% MenuEdit Callbacks
4606%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4607%------------------------------------------------------------------------
4608function MenuEditObject_Callback(hObject, eventdata, handles)
4609%------------------------------------------------------------------------
4610set(handles.edit_object,'Value',1)
4611edit_Callback(hObject, eventdata, handles)
4612
4613%------------------------------------------------------------------------
4614function MenuEditVectors_Callback(hObject, eventdata, handles)
4615%------------------------------------------------------------------------
4616set(handles.edit_vect,'Visible','on')
4617set(handles.edit_vect,'Value',1)
4618edit_vect_Callback(hObject, eventdata, handles)
4619
4620%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4621% MenuTools Callbacks
4622%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4623%------------------------------------------------------------------------
4624function MenuCalib_Callback(hObject, eventdata, handles)
4625%------------------------------------------------------------------------
4626
4627UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4628
4629%suppress competing options
4630set(handles.CheckZoom,'Value',0)
4631set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
4632set(handles.ListObject,'Value',1)     
4633% initiate display of GUI geometry_calib
4634data=[]; %default
4635if isfield(UvData,'CoordType')
4636    data.CoordType=UvData.CoordType;
4637end
4638pos=get(handles.uvmat,'Position');
4639pos(1)=pos(1)+pos(3)-0.311+0.04; %0.311= width of the geometry_calib interface (units relative to the srcreen)
4640pos(2)=pos(2)-0.02;
4641[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4642FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4643set(handles.view_xml,'Backgroundcolor',[1 1 0])%indicate the reading of the current xml file by geometry_calib
4644if isfield(UvData.OpenParam,'CalOrigin')
4645    pos_uvmat=get(handles.uvmat,'Position');
4646    pos_cal(1)=pos_uvmat(1)+UvData.OpenParam.CalOrigin(1)*pos_uvmat(3);
4647    pos_cal(2)=pos_uvmat(2)+UvData.OpenParam.CalOrigin(2)*pos_uvmat(4);
4648    pos_cal(3:4)=UvData.OpenParam.CalSize .* pos_uvmat(3:4);
4649end
4650geometry_calib(FileName,pos_cal);% call the geometry_calib interface   
4651set(handles.view_xml,'Backgroundcolor',[1 1 1])%indicate the end of reading of the current xml file by geometry_calib
4652set(handles.MenuCalib,'checked','on')% indicate that MenuCalib is activated, test used by mouse action
4653
4654%------------------------------------------------------------------------
4655function MenuMask_Callback(hObject, eventdata, handles)
4656%------------------------------------------------------------------------
4657UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4658ListObj=UvData.Object;
4659select=zeros(1,numel(ListObj));
4660for iobj=1:numel(ListObj);
4661    if strcmp(ListObj{iobj}.ProjMode,'mask_inside')||strcmp(ListObj{iobj}.ProjMode,'mask_outside')
4662        select(iobj)=1;
4663    end
4664end
4665val=find(select);
4666if isempty(val)
4667    msgbox_uvmat('ERROR','polygons must be first created by Projection object/mask polygon in the menu bar');
4668    return
4669else
4670%     set(handles.ListObject,'Max',2);%allow multiple selection
4671    set(handles.ListObject,'Value',val);
4672    flag=1;
4673    npx=size(UvData.Field.A,2);
4674    npy=size(UvData.Field.A,1);
4675    xi=0.5:npx-0.5;
4676    yi=0.5:npy-0.5;
4677    [Xi,Yi]=meshgrid(xi,yi);
4678    if isfield(UvData,'Object')
4679        for iobj=1:length(UvData.Object)
4680            ObjectData=UvData.Object{iobj};
4681            if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
4682                flagobj=1;
4683                testphys=0; %coordinates in pixels by default
4684                if isfield(ObjectData,'CoordUnit') && ~isequal(ObjectData.CoordUnit,'pixel')
4685                    if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
4686                        Calib=UvData.XmlData{1}.GeometryCalib;
4687                        testphys=1;
4688                    end
4689                end
4690                if isfield(ObjectData,'Coord')&& isfield(ObjectData,'Type')
4691                    if isequal(ObjectData.Type,'polygon')
4692                        X=ObjectData.Coord(:,1);
4693                        Y=ObjectData.Coord(:,2);
4694                        if testphys
4695                            [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
4696                        end
4697                        flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside
4698                    elseif isequal(ObjectData.Type,'ellipse')
4699                        if testphys
4700                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4701                        end
4702                        RangeX=max(ObjectData.RangeX);
4703                        RangeY=max(ObjectData.RangeY);
4704                        X2Max=RangeX*RangeX;
4705                        Y2Max=RangeY*RangeY;
4706                        distX=(Xi-ObjectData.Coord(1,1));
4707                        distY=(Yi-ObjectData.Coord(1,2));
4708                        flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
4709                    elseif isequal(ObjectData.Type,'rectangle')
4710                        if testphys
4711                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4712                        end
4713                        distX=abs(Xi-ObjectData.Coord(1,1));
4714                        distY=abs(Yi-ObjectData.Coord(1,2));
4715                        flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
4716                    end
4717                    if isequal(ObjectData.ProjMode,'mask_outside')
4718                        flagobj=~flagobj;
4719                    end
4720                    flag=flag & flagobj;
4721                end
4722            end
4723        end
4724    end
4725    %mask name
4726    RootPath=get(handles.RootPath,'String');
4727    SubDir=get(handles.SubDir,'String');
4728    RootFile=get(handles.RootFile,'String');
4729    if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
4730        RootFile(1)=[];
4731    end
4732   % filebase=fullfile(RootPath,RootFile);
4733    list=get(handles.masklevel,'String');
4734    masknumber=num2str(length(list));
4735    maskindex=get(handles.masklevel,'Value');
4736   % mask_name=fullfile_uvmat(RootPath,'',[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
4737    mask_name=fullfile_uvmat(RootPath,[SubDir '.mask'],'mask','.png','_1',maskindex);
4738    imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
4739    imflag=flipdim(imflag,1);
4740
4741    %display the mask
4742    hfigmask=figure;
4743    set(hfigmask,'Name','mask image')
4744    vec=linspace(0,1,256);%define a linear greyscale colormap
4745    map=[vec' vec' vec'];
4746    colormap(map)
4747    image(imflag);
4748    answer=msgbox_uvmat('INPUT_TXT','mask file name:', mask_name);
4749    if ~strcmp(answer,'Cancel')
4750        mask_dir=fileparts(answer);
4751        if ~exist(mask_dir,'dir')
4752            [xx,msg1]=mkdir(mask_dir);
4753            if ~strcmp(msg1,'')
4754                errormsg=['cannot create ' mask_dir ': ' msg1];%error message for directory creation
4755                return
4756            end
4757        end
4758        imwrite(imflag,answer,'BitDepth',8);
4759    end
4760    set(handles.ListObject,'Value',1)
4761end
4762
4763%------------------------------------------------------------------------
4764%-- open the GUI set_grid.fig to create grid
4765function MenuGrid_Callback(hObject, eventdata, handles)
4766%------------------------------------------------------------------------
4767%suppress the other options if grid is chosen
4768set(handles.edit_vect,'Value',0)
4769edit_vect_Callback(hObject, eventdata, handles)
4770set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
4771set(handles.ListObject,'Value',1)     
4772
4773%prepare display of the set_grid GUI
4774[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4775FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4776CoordList=get(handles.transform_fct,'String');
4777val=get(handles.transform_fct,'Value');
4778set_grid(FileName,CoordList{val});% call the set_object interface
4779
4780
4781%------------------------------------------------------------------------
4782function MenuRuler_Callback(hObject, eventdata, handles)
4783%------------------------------------------------------------------------
4784set(handles.CheckZoom,'Value',0)
4785CheckZoom_Callback(handles.uvmat, [], handles)
4786set(handles.MenuRuler,'checked','on')
4787UvData=get(handles.uvmat,'UserData');
4788UvData.MouseAction='ruler';
4789set(handles.uvmat,'UserData',UvData);
4790
4791%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4792% MenuRun Callbacks
4793%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4794
4795%------------------------------------------------------------------------
4796% open the GUI 'series'
4797function MenuSeries_Callback(hObject, eventdata, handles)
4798%------------------------------------------------------------------------
4799series; %first display of the GUI to fill waiting time
4800[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4801param.FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4802if isequal(get(handles.SubField,'Value'),1)
4803    [RootPath_1,SubDir_1,RootFile_1,FileIndices_1,FileExt_1]=read_file_boxes_1(handles);
4804    FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndices_1 FileExt_1];
4805    if ~isequal(FileName_1,param.FileName)
4806        param.FileName_1=FileName_1;
4807    end
4808end
4809param.NomType=get(handles.NomType,'String');
4810param.NomType_1=get(handles.NomType_1,'String');
4811param.CheckFixPair=get(handles.CheckFixPair,'Value');
4812huvmat=get(handles.MenuSeries,'parent');
4813UvData=get(huvmat,'UserData');
4814if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'Time')
4815    param.Time=UvData.XmlData{1}.Time;
4816end
4817if isequal(get(handles.scan_i,'Value'),1)
4818    param.incr_i=str2num(get(handles.increment_scan,'String'));
4819elseif isequal(get(handles.scan_j,'Value'),1)
4820    param.incr_j=str2num(get(handles.increment_scan,'String'));
4821end
4822param.list_fields=get(handles.Fields,'String');% list menu fields
4823param.list_fields(1)=[]; %suppress  'image' option
4824param.index_fields=get(handles.Fields,'Value');% selected string index
4825if param.index_fields>1
4826    param.index_fields=param.index_fields-1;
4827end
4828param.list_fields_1=get(handles.Fields_1,'String');% list menu fields
4829param.list_fields_1(1)=[]; %suppress  'image' option
4830param.index_fields_1=get(handles.Fields_1,'Value')-1;% selected string index
4831if param.index_fields_1>1
4832    param.index_fields_1=param.index_fields_1-1;
4833end
4834param.menu_coord_str=get(handles.transform_fct,'String');
4835param.menu_coord_val=get(handles.transform_fct,'Value');
4836series(param); %run the series interface
4837
4838%------------------------------------------------------------------------
4839% -- open the GUI civ.fig for PIV
4840function MenuPIV_Callback(hObject, eventdata, handles)
4841%------------------------------------------------------------------------
4842 [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4843 FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4844civ(FileName);% interface de civ(not in the uvmat file)
4845
4846% --------------------------------------------------------------------
4847function MenuHelp_Callback(hObject, eventdata, handles)
4848% --------------------------------------------------------------------
4849path_to_uvmat=which ('uvmat');% check the path of uvmat
4850pathelp=fileparts(path_to_uvmat);
4851helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
4852if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
4853else
4854    addpath (fullfile(pathelp,'uvmat_doc'))
4855    web(helpfile);
4856end
4857
Note: See TracBrowser for help on using the repository browser.