source: trunk/src/uvmat.m @ 484

Last change on this file since 484 was 484, checked in by sommeria, 9 years ago

bugs removed for windows OS

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