source: trunk/src/uvmat.m @ 493

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

fix the the way to deal with filter fields using tps
fix the main projection plane in uvmat

File size: 206.7 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'))
2361    if isfield(Field{1},'Coord_tps')
2362        Field{1}.FieldList=[{ParamOut.FieldName} {ParamOut.ColorVar}];
2363    else
2364    Field{1}=calc_field([{ParamOut.FieldName} {ParamOut.ColorVar}],Field{1});
2365    end
2366end
2367if 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'))...
2368        &&~strcmp(ParamOut_1.FieldName,'velocity') && ~strcmp(ParamOut_1.FieldName,'get_field...')
2369    if isfield(Field{2},'Coord_tps')
2370        Field{2}.FieldList=[{ParamOut_1.FieldName} {ParamOut_1.ColorVar}];
2371    else
2372     Field{2}=calc_field([{ParamOut_1.FieldName} {ParamOut_1.ColorVar}],Field{2});
2373    end
2374end
2375
2376%% combine the two input fields (e.g. substract velocity fields)
2377%Field{1}.FieldList=[{ParamOut.FieldName} {ParamOut.ColorVar}];
2378if numel(Field)==2
2379   [UvData.Field,errormsg]=sub_field(Field{1},Field{2}); 
2380   UvData.Field_1=Field{2}; %store the second field for possible use at next RUN
2381   UvData.ParamOut_1=ParamOut_1;
2382else
2383   UvData.Field=Field{1};
2384end
2385if ~isempty(errormsg)
2386    errormsg=['error in uvmat/refresh_field/sub_field:' errormsg];
2387    return
2388end
2389%UvData.Field.FieldList={FieldName}; % TODO: to generalise, used for proj_field with tps interpolation
2390
2391%% analyse input field
2392test_x=0;
2393test_z=0;% test for unstructured z coordinate
2394[errormsg,ListDimName,DimValue,VarDimIndex]=check_field_structure(UvData.Field);% check the input field structure
2395if ~isempty(errormsg)
2396    errormsg=['error in uvmat/refresh_field/check_field_structure: ' errormsg];% display error
2397    return
2398end
2399[CellVarIndex,NbDim,VarType,errormsg]=find_field_indices(UvData.Field);% analyse  the input field structure
2400if ~isempty(errormsg)
2401    errormsg=['error in uvmat/refresh_field/find_field_indices: ' errormsg];% display error
2402    return
2403end
2404[NbDim,imax]=max(NbDim);% spatial dimension of the input field
2405if isfield(UvData.Field,'NbDim')
2406    NbDim=UvData.Field.NbDim;% deal with plane fields containing z coordinates
2407end
2408
2409%% get bounds and mesh (needed for mouse action and to open set_object)
2410if NbDim>1
2411    XName=''; %default
2412    YName='';
2413    %unstructured coordinates
2414    if ~isempty(VarType{imax}.coord_x)&&~isempty(VarType{imax}.coord_y)
2415        XName=UvData.Field.ListVarName{VarType{imax}.coord_x};
2416        YName=UvData.Field.ListVarName{VarType{imax}.coord_y};
2417        %nbvec=length(UvData.Field.(XName));%nbre of measurement points (e.g. vectors)
2418        test_x=1;%test for unstructured coordinates
2419        if ~isempty(VarType{imax}.coord_z)
2420            ZName=UvData.Field.ListVarName{VarType{imax}.coord_z};
2421        else
2422            NbDim=2;
2423        end
2424        %structured coordinate
2425    elseif numel(VarType)>=imax && numel(VarType{imax}.coord)>=NbDim && VarType{imax}.coord(NbDim)>0
2426        XName=UvData.Field.ListVarName{VarType{imax}.coord(NbDim)};
2427        if NbDim> 1 && VarType{imax}.coord(NbDim-1)>0
2428            YName=UvData.Field.ListVarName{VarType{imax}.coord(NbDim-1)}; %structured coordinates
2429        end
2430        % VarIndex=CellVarIndex{imax}; % list of variable indices
2431        DimIndex=VarDimIndex{CellVarIndex{imax}(1)}; %list of dim indices for the variable
2432        nbpoints_x=DimValue(DimIndex(NbDim));
2433        XMax=nbpoints_x;%default
2434        XMin=1;%default
2435    end
2436   
2437    if NbDim==3
2438        if ~test_x
2439            ZName=UvData.Field.ListVarName{VarType{imax}.coord(1)};%structured coordinates in 3D
2440        end
2441        ZMax=max(UvData.Field.(ZName));
2442        ZMin=min(UvData.Field.(ZName));
2443        UvData.Field.ZMax=ZMax;
2444        UvData.Field.ZMin=ZMin;
2445        test_z=1;
2446        if isequal(ZMin,ZMax)%no z dependency
2447            NbDim=2;
2448            test_z=0;
2449        end
2450    end
2451    if ~isempty (XName)
2452        XMax=max(max(UvData.Field.(XName)));
2453        XMin=min(min(UvData.Field.(XName)));
2454        UvData.Field.NbDim=NbDim;
2455        UvData.Field.XMax=XMax;
2456        UvData.Field.XMin=XMin;
2457        if NbDim >1&& ~isempty(YName)
2458            YMax=max(max(UvData.Field.(YName)));
2459            YMin=min(min(UvData.Field.(YName)));
2460            UvData.Field.YMax=YMax;
2461            UvData.Field.YMin=YMin;
2462        end
2463        nbvec=length(UvData.Field.(XName));
2464        if test_x %unstructured coordinates
2465            if test_z
2466                UvData.Field.Mesh=((XMax-XMin)*(YMax-YMin)*(ZMax-ZMin))/nbvec;% volume per vector
2467                UvData.Field.Mesh=(UvData.Field.Mesh)^(1/3);
2468            else
2469                UvData.Field.Mesh=sqrt((XMax-XMin)*(YMax-YMin)/nbvec);%2D
2470            end
2471        end
2472    end
2473    % case of structured coordinates
2474    if ~test_x
2475        DX=(XMax-XMin)/(nbpoints_x-1);
2476        if NbDim >1
2477            nbpoints_y=DimValue(DimIndex(NbDim-1));
2478            if isempty(YName)% if the y coordinate is not expressed, it is taken as the matrix index
2479                DY=1;
2480                UvData.Field.YMax=nbpoints_y;
2481                UvData.Field.YMin=1;
2482            else
2483                DY=(YMax-YMin)/(nbpoints_y-1);
2484            end
2485        end
2486        if NbDim==3
2487            nbpoints_z=DimValue(DimIndex(1));
2488            DZ=(ZMax-ZMin)/(nbpoints_z-1);
2489            UvData.Field.Mesh=(DX*DY*DZ)^(1/3);
2490            UvData.Field.ZMax=ZMax;
2491            UvData.Field.ZMin=ZMin;
2492        else
2493            UvData.Field.Mesh=DX;%sqrt(DX*DY);
2494        end
2495    end
2496    % adjust the mesh to a value 1, 2 , 5 *10^n
2497    ord=10^(floor(log10(UvData.Field.Mesh)));%order of magnitude
2498    if UvData.Field.Mesh/ord>=5
2499        UvData.Field.Mesh=5*ord;
2500    elseif UvData.Field.Mesh/ord>=2
2501        UvData.Field.Mesh=2*ord;
2502    else
2503        UvData.Field.Mesh=ord;
2504    end
2505    % default projection plane
2506    if ~isfield(UvData,'Object')
2507        UvData.Object{1}.Type='plane';%main plotting plane
2508        UvData.Object{1}.ProjMode='projection';%main plotting plane
2509        UvData.Object{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2510        UvData.Object{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2511    end
2512    %% 3D case (menuvolume)
2513    if NbDim==3% && UvData.NewSeries
2514        test_set_object=1;
2515        hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
2516        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
2517        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
2518        if ~isempty(hset_object) %if set_object is detected
2519            delete(hset_object);% delete the GUI set_object if it does not fit
2520        end
2521        if test_set_object% reinitiate the GUI set_object
2522            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
2523            UvData.Object{1}.NbDim=NbDim;%test for 3D objects
2524            UvData.Object{1}.RangeZ=UvData.Field.Mesh;%main plotting plane
2525            UvData.Object{1}.Coord(1,3)=(UvData.Field.ZMin+UvData.Field.ZMax)/2;%section at a middle plane chosen
2526            UvData.Object{1}.Angle=[0 0 0];
2527            UvData.Object{1}.HandlesDisplay=plot(0,0,'Tag','proj_object');% A REVOIR
2528            UvData.Object{1}.Name='1-PLANE';
2529            UvData.Object{1}.enable_plot=1;
2530            set_object(UvData.Object{1},handles,ZBounds);
2531            set(handles.ListObject,'Value',1);
2532            set(handles.ListObject,'String',{'1-PLANE'});
2533            set(handles.edit_object,'Value',1)% put the plane in edit mode to enable the z cursor
2534            edit_object_Callback([],[], handles)
2535        end
2536        %multilevel case (single menuplane in a 3D space)
2537    elseif isfield(UvData,'Z')
2538        if isfield(UvData,'CoordType')&& isequal(UvData.CoordType,'phys') && isfield(UvData,'XmlData')
2539            XmlData=UvData.XmlData{1};
2540            if isfield(XmlData,'PlanePos')
2541                UvData.Object{1}.Coord=XmlData.PlanePos(UvData.ZIndex,:);
2542            end
2543            if isfield(XmlData,'PlaneAngle')
2544                siz=size(XmlData.PlaneAngle);
2545                indangle=min(siz(1),UvData.ZIndex);%take first angle if a single angle is defined (translating scanning)
2546                UvData.Object{1}.PlaneAngle=XmlData.PlaneAngle(indangle,:);
2547            end
2548        elseif isfield(UvData,'ZIndex')
2549            UvData.Object{1}.ZObject=UvData.ZIndex;
2550        end
2551    end
2552end
2553
2554testnewseries=UvData.NewSeries;
2555UvData.NewSeries=0;% put to 0 the test for a new field series (set by RootPath_callback)
2556set(handles.uvmat,'UserData',UvData)
2557
2558%% reset the min and max of scalar if only the mask is displayed(TODO: check the need)
2559% if isfield(UvData,'Mask')&& ~isfield(UvData,'A')
2560%     set(handles.num_MinA,'String','0')
2561%     set(handles.num_MaxA,'String','255')
2562% end
2563
2564%% usual 1D (x,y) plots
2565if NbDim<=1
2566    set(handles.Objects,'Visible','off')
2567    set(handles.ListObject_1_title,'Visible','off')
2568    set(handles.ListObject_1,'Visible','off')
2569    [PlotType,PlotParamOut]=plot_field(UvData.Field,handles.axes3,read_GUI(handles.uvmat));
2570    write_plot_param(handles,PlotParamOut) %update the auto plot parameters
2571%     if isfield(Field,'Mesh')&&~isempty(Field.Mesh)
2572%         ObjectData.Mesh=Field.Mesh; % gives an estimated mesh size (useful for mouse action on the plot)
2573%     end
2574   
2575%% 2D or 3D fields are generally projected
2576else
2577    set(handles.Objects,'Visible','on')
2578    set(handles.ListObject_1_title,'Visible','on')
2579    set(handles.ListObject_1,'Visible','on')
2580   
2581    %% Plot the projections on the selected  projection objects
2582    % main projection object (uvmat display)
2583    list_object=get(handles.ListObject_1,'String');
2584    if isequal(list_object,{''})%refresh list of objects if the menu is empty
2585        UvData.Object={[]};
2586        set(handles.ListObject_1,'Value',1)
2587    end
2588    IndexObj(1)=get(handles.ListObject_1,'Value');%selected projection object for main view
2589    if IndexObj(1)> numel(UvData.Object)
2590        IndexObj(1)=1;%select the first object if the selected one does not exist
2591        set(handles.ListObject_1,'Value',1)
2592    end
2593    IndexObj(2)=get(handles.ListObject,'Value');%selected projection object for main view
2594    if isequal(IndexObj(2),IndexObj(1))
2595        IndexObj(2)=[];
2596    end
2597    plot_handles{1}=handles;
2598    if isfield(UvData,'plotaxes')%case of movies
2599        haxes(1)=UvData.plotaxes;
2600    else
2601        haxes(1)=handles.axes3;
2602    end
2603    PlotParam{1}=read_GUI(handles.uvmat);
2604    %default settings if vectors not visible
2605    if ~isfield(PlotParam{1},'Vectors')
2606        PlotParam{1}.Vectors.MaxVec=1;
2607        PlotParam{1}.Vectors.MinVec=0;
2608        PlotParam{1}.Vectors.CheckFixVecColor=1;
2609        PlotParam{1}.Vectors.ColCode1=0.33;
2610        PlotParam{1}.Vectors.ColCode2=0.66;
2611        PlotParam{1}.Vectors.ColorScalar={'ima_cor'};
2612        PlotParam{1}.Vectors.ColorCode= {'rgb'};
2613    end
2614    PosColorbar{1}=UvData.OpenParam.PosColorbar;%prescribe the colorbar position on the uvmat interface
2615   
2616    %% second projection object (view_field display)
2617    if length( IndexObj)>=2
2618        view_field_handle=findobj(allchild(0),'tag','view_field');%handles of the view_field GUI
2619        if ~isempty(view_field_handle)
2620            plot_handles{2}=guidata(view_field_handle);
2621            haxes(2)=plot_handles{2}.axes3;
2622            PlotParam{2}=read_GUI(handles.uvmat);%read plotting parameters on the uvmat interface
2623            PosColorbar{2}='*'; %TODO: deal with colorbar position on view_field
2624        end
2625    end
2626   
2627    %% loop on the projection objects: one or two
2628   
2629    for imap=1:numel(IndexObj)
2630        iobj=IndexObj(imap);
2631        %      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)
2632        % %          [ObjectData,errormsg]=calc_field(UvData.Field.FieldList,UvData.Field);
2633        % %      else
2634        [ObjectData,errormsg]=proj_field(UvData.Field,UvData.Object{iobj});% project field on the object
2635        %      end
2636        if ~isempty(errormsg)
2637            return
2638        end
2639        if testnewseries
2640            PlotParam{imap}.Scalar.CheckBW=[]; %B/W option depends on the input field (image or scalar)
2641            if isfield(ObjectData,'CoordUnit')
2642                PlotParam{imap}.Coordinates.CheckFixAspectRatio=1;% set x and y scaling equal if CoordUnit is defined (common unit for x and y)
2643                PlotParam{imap}.Coordinates.AspectRatio=1; %set aspect ratio to 1
2644            end
2645        end
2646        %use of mask (TODO: check)
2647        if isfield(ObjectData,'NbDim') && isequal(ObjectData.NbDim,2) && isfield(ObjectData,'Mask') && isfield(ObjectData,'A')
2648            flag_mask=double(ObjectData.Mask>200);%=0 for masked regions
2649            AX=ObjectData.AX;%x coordiantes for the scalar field
2650            AY=ObjectData.AY;%y coordinates for the scalar field
2651            MaskX=ObjectData.MaskX;%x coordiantes for the mask
2652            MaskY=ObjectData.MaskY;%y coordiantes for the mask
2653            if ~isequal(MaskX,AX)||~isequal(MaskY,AY)
2654                nxy=size(flag_mask);
2655                sizpx=(ObjectData.MaskX(end)-ObjectData.MaskX(1))/(nxy(2)-1);%size of a mask pixel
2656                sizpy=(ObjectData.MaskY(1)-ObjectData.MaskY(end))/(nxy(1)-1);
2657                x_mask=ObjectData.MaskX(1):sizpx:ObjectData.MaskX(end); % pixel x coordinates for image display
2658                y_mask=ObjectData.MaskY(1):-sizpy:ObjectData.MaskY(end);% pixel x coordinates for image display
2659                %project on the positions of the scalar
2660                npxy=size(ObjectData.A);
2661                dxy(1)=(ObjectData.AY(end)-ObjectData.AY(1))/(npxy(1)-1);%grid mesh in y
2662                dxy(2)=(ObjectData.AX(end)-ObjectData.AX(1))/(npxy(2)-1);%grid mesh in x
2663                xi=ObjectData.AX(1):dxy(2):ObjectData.AX(end);
2664                yi=ObjectData.AY(1):dxy(1):ObjectData.AY(end);
2665                [XI,YI]=meshgrid(xi,yi);% creates the matrix of regular coordinates
2666                flag_mask = interp2(x_mask,y_mask,flag_mask,XI,YI);
2667            end
2668            AClass=class(ObjectData.A);
2669            ObjectData.A=flag_mask.*double(ObjectData.A);
2670            ObjectData.A=feval(AClass,ObjectData.A);
2671            ind_off=[];
2672            if isfield(ObjectData,'ListVarName')
2673                for ilist=1:length(ObjectData.ListVarName)
2674                    if isequal(ObjectData.ListVarName{ilist},'Mask')||isequal(ObjectData.ListVarName{ilist},'MaskX')||isequal(ObjectData.ListVarName{ilist},'MaskY')
2675                        ind_off=[ind_off ilist];
2676                    end
2677                end
2678                ObjectData.ListVarName(ind_off)=[];
2679                VarDimIndex(ind_off)=[];
2680                ind_off=[];
2681                for ilist=1:length(ListDimName)
2682                    if isequal(ListDimName{ilist},'MaskX') || isequal(ListDimName{ilist},'MaskY')
2683                        ind_off=[ind_off ilist];
2684                    end
2685                end
2686                ListDimName(ind_off)=[];
2687                DimValue(ind_off)=[];
2688            end
2689        end
2690        if ~isempty(ObjectData)
2691            PlotType='none'; %default
2692            if imap==2 && isempty(view_field_handle)
2693                view_field(ObjectData)
2694            else
2695                [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
2696                write_plot_param(plot_handles{imap},PlotParamOut) %update the auto plot parameters
2697                if isfield(Field,'Mesh')&&~isempty(Field.Mesh)
2698                    ObjectData.Mesh=Field.Mesh; % gives an estimated mesh size (useful for mouse action on the plot)
2699                end
2700            end
2701            if isequal(PlotType,'none')
2702                hget_field=findobj(allchild(0),'name','get_field');
2703                if isempty(hget_field)
2704                    get_field(FileName)% the projected field cannot be automatically plotted: use get_field to specify the variablesdelete(hget_field)
2705                end
2706                errormsg='The field defined by get_field cannot be plotted';
2707                return
2708            end
2709        end
2710    end
2711   
2712    %% update the mask
2713    if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
2714        update_mask(handles,num_i1,num_i2);
2715    end
2716   
2717    %% prepare the menus of histograms and plot them (histogram of the whole volume in 3D case)
2718    menu_histo=(UvData.Field.ListVarName)';%list of field variables to be displayed for the menu of histogram display
2719    ind_skip=[];
2720    % nb_histo=1;
2721    Ustring='';
2722    Vstring='';
2723    % suppress coordinates from the histogram menu
2724    for ivar=1:numel(menu_histo)%l loop on field variables:
2725        if isfield(UvData.Field,'VarAttribute') && numel(UvData.Field.VarAttribute)>=ivar && isfield(UvData.Field.VarAttribute{ivar},'Role')
2726            Role=UvData.Field.VarAttribute{ivar}.Role;
2727            switch Role
2728                case {'coord_x','coord_y','coord_z','dimvar'}
2729                    ind_skip=[ind_skip ivar];
2730                case {'vector_x'}
2731                    Ustring=UvData.Field.ListVarName{ivar};
2732                    ind_skip=[ind_skip ivar];
2733                case {'vector_y'}
2734                    Vstring=UvData.Field.ListVarName{ivar};
2735                    ind_skip=[ind_skip ivar];
2736            end
2737        end
2738        DimCell=UvData.Field.VarDimName{ivar};
2739        DimName='';
2740        if ischar(DimCell)
2741            DimName=DimCell;
2742        elseif iscell(DimCell)&& numel(DimCell)==1
2743            DimName=DimCell{1};
2744        end
2745        if strcmp(DimName,menu_histo{ivar})
2746            ind_skip=[ind_skip ivar];
2747        end
2748    end
2749    menu_histo(ind_skip)=[];% remove skipped items
2750    if ~isempty(Ustring)
2751        menu_histo=[{[Ustring ',' Vstring]};menu_histo];% add U, V at the beginning if they exist
2752    end
2753   
2754    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2755    % display menus and plot histograms
2756    test_v=0;
2757    if ~isempty(menu_histo)
2758        set(handles.histo1_menu,'Value',1)
2759        set(handles.histo1_menu,'String',menu_histo)
2760        histo1_menu_Callback(handles.histo1_menu, [], handles)% plot first histogram
2761    end
2762end
2763
2764%------------------------------------------------------------------------
2765function histo1_menu_Callback(hObject, eventdata, handles)
2766%--------------------------------------------
2767%plot first histo
2768%huvmat=get(handles.histo1_menu,'parent');
2769histo_menu=get(handles.histo1_menu,'String');
2770histo_value=get(handles.histo1_menu,'Value');
2771FieldName=histo_menu{histo_value};
2772% update_histo(handles.histo_u,handles.uvmat,FieldName)
2773%
2774% %------------------------------------------------------------------------
2775% function histo2_menu_Callback(hObject, eventdata, handles)
2776% %------------------------------------------------------------------------
2777% %plot second histo
2778% %huvmat=get(handles.histo2_menu,'parent');
2779% histo_menu=get(handles.histo2_menu,'String');
2780% histo_value=get(handles.histo2_menu,'Value');
2781% FieldName=histo_menu{histo_value};
2782% update_histo(handles.histo_v,handles.uvmat,FieldName)
2783%
2784% %------------------------------------------------------------------------
2785% %read the field .Fieldname stored in UvData and plot its histogram
2786% function update_histo(haxes,huvmat,FieldName)
2787%------------------------------------------------------------------------
2788UvData=get(handles.uvmat,'UserData');
2789Field=UvData.Field;
2790r=regexp(FieldName,'(?<var1>.*)(?<sep>,)(?<var2>.*)','names');
2791FieldName_2='';
2792if ~isempty(r)
2793    FieldName=r.var1;
2794    FieldName_2=r.var2;
2795end
2796if ~isfield(UvData.Field,FieldName)
2797    msgbox_uvmat('ERROR',['no field  ' FieldName ' for histogram'])
2798    return
2799end
2800FieldHisto=Field.(FieldName);
2801if isfield(Field,'FF') && ~isempty(Field.FF) && isequal(size(Field.FF),size(FieldHisto))
2802    indsel=find(Field.FF==0);%find values marked as false
2803    if ~isempty(indsel)
2804        FieldHisto=FieldHisto(indsel);
2805        if ~isempty(FieldName_2)
2806            FieldHisto(:,:,2)=Field.(FieldName_2)(indsel);
2807        end
2808    end
2809end
2810if isempty(Field)
2811    msgbox_uvmat('ERROR',['empty field ' FieldName])
2812else
2813    nxy=size(FieldHisto);
2814    Amin=double(min(min(min(FieldHisto))));%min of field value
2815    Amax=double(max(max(max(FieldHisto))));%max of field value
2816    if isequal(Amin,Amax)
2817        cla(handles.histo_u)
2818    else
2819        Histo.ListVarName={FieldName,'histo'};
2820        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2821            Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2822        else
2823            if numel(nxy)==2
2824                Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2825            else
2826                Histo.VarDimName={FieldName,{FieldName,'component'}}; %dimensions for the histogram
2827            end
2828        end
2829        %unit
2830        units=[]; %default
2831        for ivar=1:numel(Field.ListVarName)
2832            if strcmp(Field.ListVarName{ivar},FieldName)
2833                if isfield(Field,'VarAttribute') && numel(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'units')
2834                    units=Field.VarAttribute{ivar}.units;
2835                    break
2836                end
2837            end
2838        end
2839        if ~isempty(units)
2840            Histo.VarAttribute{1}.units=units;
2841        end
2842        eval(['Histo.' FieldName '=linspace(Amin,Amax,50);'])%absissa values for histo
2843        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2844            C=reshape(double(FieldHisto),1,[]);% reshape in a vector
2845            Histo.histo(:,1)=hist(C, Histo.(FieldName));  %calculate histogram
2846        else
2847            for col=1:size(FieldHisto,3)
2848                B=FieldHisto(:,:,col);
2849                C=reshape(double(B),1,nxy(1)*nxy(2));% reshape in a vector
2850                Histo.histo(:,col)=hist(C, Histo.(FieldName));  %calculate histogram
2851            end
2852        end
2853        plot_field(Histo,handles.histo_u);
2854        hlegend=legend;
2855        if isempty(FieldName_2)
2856        set(hlegend,'String',FieldName)
2857        else
2858            set(hlegend,'String',{FieldName;FieldName_2})
2859        end
2860%         hh=get(handles.histo_u,'children');
2861%         get(hh(1))
2862%         get(hh(2))
2863    end
2864end
2865
2866%-------------------------------------------------------------------
2867% --- translate coordinate to matrix index
2868%-------------------------------------------------------------------
2869function [indx,indy]=pos2ind(x0,rangx0,nxy)
2870indx=1+round((nxy(2)-1)*(x0-rangx0(1))/(rangx0(2)-rangx0(1)));% index x of pixel 
2871indy=1+round((nxy(1)-1)*(y12-rangy0(1))/(rangy0(2)-rangy0(1)));% index y of pixel
2872
2873
2874%-------------------------------------------------------------------
2875% --- Executes on button press in 'CheckZoom'.
2876%-------------------------------------------------------------------
2877function CheckZoom_Callback(hObject, eventdata, handles)
2878
2879if (get(handles.CheckZoom,'Value') == 1);
2880    set(handles.CheckZoom,'BackgroundColor',[1 1 0])
2881    set(handles.CheckFixLimits,'Value',1)% propose by default fixed limits for the plotting axes
2882    set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
2883else
2884    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
2885end
2886
2887%-------------------------------------------------------------------
2888% --- Executes on button press in 'CheckFixLimits'.
2889%-------------------------------------------------------------------
2890function CheckFixLimits_Callback(hObject, eventdata, handles)
2891test=get(handles.CheckFixLimits,'Value');
2892if test
2893    set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
2894else
2895    set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
2896    update_plot(handles);
2897end
2898
2899%-------------------------------------------------------------------
2900% --- Executes on button press in CheckFixAspectRatio.
2901function CheckFixAspectRatio_Callback(hObject, eventdata, handles)
2902%-------------------------------------------------------------------
2903if get(handles.CheckFixAspectRatio,'Value')
2904    set(handles.CheckFixAspectRatio,'BackgroundColor',[1 1 0])
2905    update_plot(handles);
2906else
2907    set(handles.CheckFixAspectRatio,'BackgroundColor',[0.7 0.7 0.7])
2908    update_plot(handles);
2909end
2910
2911%-------------------------------------------------------------------
2912function num_AspectRatio_Callback(hObject, eventdata, handles)
2913%-------------------------------------------------------------------
2914set(handles.CheckFixAspectRatio,'Value',1)% select the fixed aspect ratio button
2915set(handles.CheckFixAspectRatio,'BackgroundColor',[1 1 0])% mark in yellow
2916update_plot(handles);
2917%-------------------------------------------------------------------
2918
2919%-------------------------------------------------------------------
2920
2921
2922
2923%-------------------------------------------------------------------
2924%----Executes on button press in 'record': records the current flags of manual correction.
2925%-------------------------------------------------------------------
2926function record_Callback(hObject, eventdata, handles)
2927% [filebase,num_i1,num_j1,num_i2,num_j2,Ext,NomType,SubDir]=read_input_file(handles);
2928[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
2929FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
2930%FileName=read_file_boxes(handles);
2931[erread,message]=fileattrib(FileName);
2932if ~isempty(message) && ~isequal(message.UserWrite,1)
2933     msgbox_uvmat('ERROR',['no writting access to ' FileName])
2934     return
2935end
2936test_civ2=isequal(get(handles.civ2,'BackgroundColor'),[1 1 0]);
2937test_civ1=isequal(get(handles.VelType,'BackgroundColor'),[1 1 0]);
2938if ~test_civ2 && ~test_civ1
2939    msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
2940end
2941if test_civ2
2942    nbname='nb_vectors2';
2943   flagname='vec2_FixFlag';
2944   attrname='fix2';
2945end
2946if test_civ1
2947    nbname='nb_vectors';
2948   flagname='vec_FixFlag';
2949   attrname='fix';
2950end
2951%write fix flags in the netcdf file
2952UvData=get(handles.uvmat,'UserData');
2953hhh=which('netcdf.open');% look for built-in matlab netcdf library
2954if ~isequal(hhh,'')% case of new builtin Matlab netcdf library
2955    nc=netcdf.open(FileName,'NC_WRITE');
2956    netcdf.reDef(nc);
2957    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),attrname,1);
2958    dimid = netcdf.inqDimID(nc,nbname);
2959    try
2960        varid = netcdf.inqVarID(nc,flagname);% look for already existing fixflag variable
2961    catch
2962        varid=netcdf.defVar(nc,flagname,'double',dimid);%create fixflag variable if it does not exist
2963    end
2964    netcdf.endDef(nc);
2965    netcdf.putVar(nc,varid,UvData.axes3.FF);
2966    netcdf.close(nc); 
2967else %old netcdf library
2968    netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2969end
2970
2971%-------------------------------------------------------------------
2972%----Correct the netcdf file, using toolbox (old versions of Matlab).
2973%-------------------------------------------------------------------
2974function netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2975nc=netcdf(FileName,'write'); %open netcdf file
2976result=redef(nc);
2977eval(['nc.' attrname '=1;']);
2978theDim=nc(nbname) ;% get the number of velocity vectors
2979nb_vectors=size(theDim);
2980var_FixFlag=ncvar(flagname,nc);% var_FixFlag will be written as the netcdf variable vec_FixFlag
2981var_FixFlag(1:nb_vectors)=AxeData.FF;%
2982fin=close(nc);
2983
2984%-------------------------------------------------------------------
2985% --- Executes on button press in SubField
2986function SubField_Callback(hObject, eventdata, handles)
2987%-------------------------------------------------------------------
2988UvData=get(handles.uvmat,'UserData');
2989if get(handles.SubField,'Value')==0% if the subfield button is desactivated   
2990    set(handles.RootPath_1,'String','')
2991    set(handles.RootFile_1,'String','')
2992    set(handles.SubDir_1,'String','');
2993    set(handles.FileIndex_1,'String','');
2994    set(handles.FileExt_1,'String','');
2995    set(handles.RootPath_1,'Visible','off')
2996    set(handles.RootFile_1,'Visible','off')
2997    set(handles.SubDir_1,'Visible','off');
2998    set(handles.NomType_1,'Visible','off');
2999    set(handles.abs_time_1,'Visible','off')
3000    set(handles.FileIndex_1,'Visible','off');
3001    set(handles.FileExt_1,'Visible','off');
3002    set(handles.Fields_1,'Value',1);%set to blank state
3003    set(handles.VelType_1,'Value',1);%set to blank state
3004    set(handles.num_Opacity,'String','')% desactivate opacity setting
3005    if ~strcmp(get(handles.VelType,'Visible'),'on')
3006        set(handles.VelType_1,'Visible','off')
3007    end
3008    if isfield(UvData,'XmlData_1')
3009        UvData=rmfield(UvData,'XmlData_1');
3010    end
3011    set(handles.uvmat,'UserData',UvData);
3012    run0_Callback(hObject, eventdata, handles); %run
3013else
3014    MenuBrowse_1_Callback(hObject, eventdata, handles)
3015end
3016
3017%------------------------------------------------------------------------
3018% --- read the data displayed for the input rootfile windows (new): TODO use read_GUI
3019
3020function [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles)
3021%------------------------------------------------------------------------
3022InputFile=read_GUI(handles.InputFile);
3023RootPath=InputFile.RootPath;
3024SubDir=regexprep(InputFile.SubDir,'/|\','');
3025RootFile=regexprep(InputFile.RootFile,'/|\','');
3026FileIndices=InputFile.FileIndex;
3027FileExt=InputFile.FileExt;
3028
3029
3030%------------------------------------------------------------------------
3031% ---- read the data displayed for the second input rootfile windows
3032function [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1,NomType_1]=read_file_boxes_1(handles)
3033%------------------------------------------------------------------------
3034RootPath_1=get(handles.RootPath_1,'String'); % read the data from the file1_input window
3035if isequal(get(handles.RootPath_1,'Visible'),'off') || isequal(RootPath_1,'"')
3036    RootPath_1=get(handles.RootPath,'String');
3037end;
3038SubDir_1=get(handles.SubDir_1,'String');
3039if isequal(get(handles.SubDir_1,'Visible'),'off')|| isequal(SubDir_1,'"')
3040    SubDir_1=get(handles.SubDir,'String');
3041end
3042SubDir_1=regexprep(SubDir_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3043RootFile_1=get(handles.RootFile_1,'String');
3044if isequal(get(handles.RootFile_1,'Visible'),'off') || isequal(RootFile_1,'"')
3045    RootFile_1=get(handles.RootFile,'String');
3046end
3047RootFile_1=regexprep(RootFile_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3048FileIndex_1=get(handles.FileIndex_1,'String');
3049if isequal(get(handles.FileIndex_1,'Visible'),'off')|| isequal(FileIndex_1,'"')
3050    FileIndex_1=get(handles.FileIndex,'String');
3051end
3052FileExt_1=get(handles.FileExt_1,'String');
3053if isequal(get(handles.FileExt_1,'Visible'),'off') || isequal(FileExt_1,'"')
3054    FileExt_1=get(handles.FileExt,'String');%read FileExt by default
3055end
3056NomType_1=get(handles.NomType_1,'String');
3057if isequal(get(handles.NomType_1,'Visible'),'off') || isequal(NomType_1,'"')
3058    NomType_1=get(handles.NomType,'String');%read FileExt by default
3059end
3060%------------------------------------------------------------------------
3061% --- Executes on menu selection Fields
3062function Fields_Callback(hObject, eventdata, handles)
3063%------------------------------------------------------------------------
3064list_fields=get(handles.Fields,'String');% list menu fields
3065index_fields=get(handles.Fields,'Value');% selected string index
3066field= list_fields{index_fields(1)}; % selected string
3067if isequal(field,'get_field...')
3068    set(handles.FixVelType,'visible','off')
3069    set(handles.VelType,'visible','off')
3070    set(handles.VelType_1,'visible','off')
3071    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3072    FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3073    %FileName=read_file_boxes(handles);
3074    hget_field=findobj(allchild(0),'name','get_field');
3075    if ~isempty(hget_field)
3076        delete(hget_field)
3077    end
3078    hget_field=get_field(FileName);
3079    set(hget_field,'Name','get_field')
3080    hhget_field=guidata(hget_field);
3081    set(hhget_field.list_fig,'Value',1)
3082    set(hhget_field.list_fig,'String',{'uvmat'})
3083    set(handles.transform_fct,'Value',1)% no transform by default
3084    set(handles.path_transform,'String','')
3085    return %no action
3086end
3087list_fields=get(handles.Fields_1,'String');% list menu fields
3088index_fields=get(handles.Fields_1,'Value');% selected string index
3089field_1= list_fields{index_fields(1)}; % selected string
3090UvData=get(handles.uvmat,'UserData');
3091
3092%read the rootfile input display
3093[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3094FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3095[tild,tild,tild,i1,i2,j1,j2,tild,NomType]=fileparts_uvmat(['xxx' get(handles.FileIndex,'String') FileExt]);
3096if isequal(field,'image')
3097    SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3098    imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3099    if ~exist(imagename,'file')
3100        [FileName,PathName] = uigetfile( ...
3101            {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3102            '*.jpg',' jpeg image files'; ...
3103            '*.png','.png image files'; ...
3104            '*.tif','.tif image files'; ...
3105            '*.avi;*.AVI','.avi movie files'; ...
3106            '*.vol','.volume images (png)'; ...
3107            '*.*',  'All Files (*.*)'}, ...
3108            'Pick an image',imagename);   
3109        imagename=[PathName FileName];
3110    end
3111     % display the selected field and related information
3112    display_file_name(handles,imagename)%display the image
3113    return
3114else
3115    ext=get(handles.FileExt,'String');
3116    if ~isequal(ext,'.nc') %find the new NomType if the previous display was not already a netcdf file
3117        [FileName,PathName] = uigetfile( ...
3118            {'*.nc', ' (*.nc)';
3119            '*.nc',' netcdf files'; ...
3120            '*.*',  'All Files (*.*)'}, ...
3121            'Pick a netcdf file',FileBase);
3122        FullFileName=[PathName FileName];
3123        % display the selected field and related information
3124        display_file_name( handles,FullFileName)
3125        return
3126    end
3127end
3128indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,j2);
3129set(handles.FileIndex,'String',indices)
3130% set(handles.NomType,'String',NomType)
3131
3132%common to Fields_1_Callback
3133if isequal(field,'image')||isequal(field_1,'image')
3134    set(handles.TitleNpx,'Visible','on')% visible npx,pxcm... buttons
3135    set(handles.TitleNpy,'Visible','on')
3136    set(handles.num_Npx,'Visible','on')
3137    set(handles.num_Npy,'Visible','on')
3138else
3139    set(handles.TitleNpx,'Visible','off')% visible npx,pxcm... buttons
3140    set(handles.TitleNpy,'Visible','off')
3141    set(handles.num_Npx,'Visible','off')
3142    set(handles.num_Npy,'Visible','off')
3143end
3144if ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3145    run0_Callback(hObject, eventdata, handles)
3146end
3147
3148%---------------------------------------------------
3149% --- Executes on menu selection Fields
3150function Fields_1_Callback(hObject, eventdata, handles)
3151%-------------------------------------------------
3152%% read input data
3153check_new=~get(handles.SubField,'Value'); %check_new=1 if a second field was not previously entered
3154UvData=get(handles.uvmat,'UserData');
3155if check_new && isfield(UvData,'XmlData')
3156    UvData.XmlData{2}=UvData.XmlData{1};
3157end
3158if isfield(UvData,'Field_1')
3159    UvData=rmfield(UvData,'Field_1');% remove the stored second field (a new one needs to be read)
3160end
3161UvData.FileName_1='';% desactivate the use of a constant second file
3162list_fields=get(handles.Fields,'String');% list menu fields
3163field= list_fields{get(handles.Fields,'Value')}; % selected string
3164list_fields=get(handles.Fields_1,'String');% list menu fields
3165field_1= list_fields{get(handles.Fields_1,'Value')}; % selected string for the second field
3166if isempty(field_1)%||(numel(UvData.FileType)>=2 && strcmp(UvData.FileType{2},'image'))
3167    set(handles.SubField,'Value',0)
3168    SubField_Callback(hObject, eventdata, handles)
3169    return
3170else
3171    set(handles.SubField,'Value',1)%state that a second field is now entered
3172end
3173
3174%% read the rootfile input display
3175[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3176FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
3177[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
3178% set(handles.FileIndex_1,'Visible','on')
3179% set(handles.FileExt_1,'Visible','on')
3180switch field_1
3181    case 'get_field...'
3182        set_veltype_display(0) % no veltype display
3183        hget_field=findobj(allchild(0),'name','get_field_1');
3184        if ~isempty(hget_field)
3185            delete(hget_field)
3186        end
3187        hget_field=get_field(FileName_1);
3188        set(hget_field,'name','get_field_1')
3189        hhget_field=guidata(hget_field);
3190        set(hhget_field.list_fig,'Value',1)
3191        set(hhget_field.list_fig,'String',{'uvmat'})
3192        set(handles.transform_fct,'Value',1)% no transform by default
3193        set(handles.path_transform,'String','')
3194        if check_new
3195            UvData.FileType{2}=UvData.FileType{1};
3196            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3197%             set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3198              set(handles.uvmat,'UserData',UvData)
3199        end
3200    case 'image'
3201        % guess the image name corresponding to the current netcdf name (no unique correspondance)
3202        SubDirBase=regexprep(SubDir_1,'\..*','');%take the root part of SubDir, before the first dot '.'
3203        imagename=fullfile_uvmat(RootPath_1,SubDirBase,RootFile_1,'.png',get(handles.NomType,'String'),i1,[],j1);
3204        if ~exist(imagename,'file') % browse for images if it is not found
3205            [FileName,PathName] = uigetfile( ...
3206                {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3207                '*.jpg',' jpeg image files'; ...
3208                '*.png','.png image files'; ...
3209                '*.tif','.tif image files'; ...
3210                '*.avi;*.AVI','.avi movie files'; ...
3211                '*.vol','.volume images (png)'; ...
3212                '*.*',  'All Files (*.*)'}, ...
3213                'Pick an image',imagename);
3214            imagename=[PathName FileName];
3215        end
3216        if ~ischar(imagename)% quit if the browser has  been closed
3217            set(handles.SubField,'Value',0)
3218        else %valid browser input:  display the selected image
3219            set(handles.TitleNpx,'Visible','on')% visible npx,pxcm... buttons
3220            set(handles.TitleNpy,'Visible','on')
3221            set(handles.num_Npx,'Visible','on')
3222            set(handles.num_Npy,'Visible','on')
3223            display_file_name(handles,imagename,2)%display the imag
3224        end
3225    otherwise
3226        if check_new
3227            UvData.FileType{2}=UvData.FileType{1};
3228            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3229            set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3230        end
3231        if ~isequal(field,'image')
3232            set(handles.TitleNpx,'Visible','off')% visible npx,pxcm... buttons
3233            set(handles.TitleNpy,'Visible','off')
3234            set(handles.num_Npx,'Visible','off')
3235            set(handles.num_Npy,'Visible','off')
3236        end
3237        set(handles.uvmat,'UserData',UvData)
3238        if ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3239            run0_Callback(hObject, eventdata, handles)
3240        end
3241end
3242
3243%------------------------------------------------------------------------
3244% --- set the visibility of relevant velocity type menus:
3245function menu=set_veltype_display(Civ,FileType)
3246%------------------------------------------------------------------------
3247if ~exist('FileType','var')
3248    FileType='civx';
3249end
3250switch FileType
3251    case 'civx'
3252        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3253        if isequal(Civ,0)
3254            imax=0;
3255        elseif isequal(Civ,1) || isequal(Civ,2)
3256            imax=1;
3257        elseif isequal(Civ,3)
3258            imax=3;
3259        elseif isequal(Civ,4) || isequal(Civ,5)
3260            imax=4;
3261        elseif isequal(Civ,6) %patch2
3262            imax=6;
3263        end
3264    case 'civdata'
3265        menu={'civ1';'filter1';'civ2';'filter2'};
3266        if isequal(Civ,0)
3267            imax=0;
3268        elseif isequal(Civ,1) || isequal(Civ,2)
3269            imax=1;
3270        elseif isequal(Civ,3)
3271            imax=2;
3272        elseif isequal(Civ,4) || isequal(Civ,5)
3273            imax=3;
3274        elseif isequal(Civ,6) %patch2
3275            imax=4;
3276        end
3277end
3278menu=menu(1:imax);
3279
3280%------------------------------------------------------------------------
3281% --- Executes on button press in FixVelType.
3282function FixVelType_Callback(hObject, eventdata, handles)
3283%------------------------------------------------------------------------
3284% refresh the current plot if the fixed  veltype is unselected
3285if ~get(handles.FixVelType,'Value')
3286    run0_Callback(hObject, eventdata, handles)
3287end
3288
3289%------------------------------------------------------------------------
3290% --- Executes on button press in VelType.
3291function VelType_Callback(hObject, eventdata, handles)
3292%------------------------------------------------------------------------
3293set(handles.FixVelType,'Value',1)
3294run0_Callback(hObject, eventdata, handles)
3295
3296%------------------------------------------------------------------------
3297% --- Executes on button press in VelType_1.
3298function VelType_1_Callback(hObject, eventdata, handles)
3299%------------------------------------------------------------------------
3300set(handles.FixVelType,'Value',1)% the velocity type is now imposed by the GUI (not automatic)
3301UvData=get(handles.uvmat,'UserData');
3302%refresh field with a second FileName=first file name
3303set(handles.run0,'BackgroundColor',[1 1 0])%paint the command button in yellow
3304drawnow   
3305InputFile=read_GUI(handles.InputFile);
3306[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3307FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3308
3309if isempty(InputFile.VelType_1)
3310        FileName_1='';% we plot the current field without the second field
3311        set(handles.SubField,'Value',0)
3312        SubField_Callback(hObject, eventdata, handles)
3313elseif get(handles.SubField,'Value')% if subfield is already 'on'
3314      [RootPath_1,SubDir_1,RootFile_1,FileIndices_1,FileExt_1]=read_file_boxes_1(handles);
3315     FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndices_1 FileExt_1];
3316else
3317     FileName_1=FileName;% we compare two fields in the same file by default
3318     UvData.FileType{2}=UvData.FileType{1};
3319     set(handles.SubField,'Value',1)
3320end
3321if isfield(UvData,'Field_1')
3322    UvData=rmfield(UvData,'Field_1');% removes the stored second field if it exists
3323end
3324UvData.FileName_1='';% desactivate the use of a constant second file
3325set(handles.uvmat,'UserData',UvData)
3326num_i1=stra2num(get(handles.i1,'String'));
3327num_i2=stra2num(get(handles.i2,'String'));
3328num_j1=stra2num(get(handles.j1,'String'));
3329num_j2=stra2num(get(handles.j2,'String'));
3330
3331errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2);
3332
3333if ~isempty(errormsg)
3334    msgbox_uvmat('ERROR',errormsg);
3335else
3336    set(handles.i1,'BackgroundColor',[1 1 1])
3337    set(handles.i2,'BackgroundColor',[1 1 1])
3338    set(handles.j1,'BackgroundColor',[1 1 1])
3339    set(handles.j2,'BackgroundColor',[1 1 1])
3340    set(handles.FileIndex,'BackgroundColor',[1 1 1])
3341    set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
3342end
3343set(handles.run0,'BackgroundColor',[1 0 0])
3344
3345%-----------------------------------------------
3346% --- reset civ buttons
3347function reset_vel_type(handles_civ0,handle1)
3348for ibutton=1:length(handles_civ0)
3349    set(handles_civ0(ibutton),'BackgroundColor',[0.831 0.816 0.784])
3350    set(handles_civ0(ibutton),'Value',0)
3351end
3352if exist('handle1','var')%handles of selected button
3353        set(handle1,'BackgroundColor',[1 1 0]) 
3354end
3355
3356%-------------------------------------------------------
3357% --- Executes on button press in MENUVOLUME.
3358%-------------------------------------------------------
3359function VOLUME_Callback(hObject, eventdata, handles)
3360%errordlg('command VOL not implemented yet')
3361if ishandle(handles.UVMAT_title)
3362    delete(handles.UVMAT_title)
3363end
3364UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3365if isequal(get(handles.VOLUME,'Value'),1)
3366    set(handles.CheckZoom,'Value',0)
3367    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3368    set(handles.edit_vect,'Value',0)
3369    edit_vect_Callback(hObject, eventdata, handles)
3370    set(handles.edit_object,'Value',0)
3371    set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
3372%     set(handles.cal,'Value',0)
3373%     set(handles.cal,'BackgroundColor',[0 1 0])
3374    set(handles.edit_vect,'Value',0)
3375    edit_vect_Callback(hObject, eventdata, handles)
3376    %initiate set_object GUI
3377    data.Name='VOLUME';
3378    if isfield(UvData,'CoordType')
3379        data.CoordType=UvData.CoordType;
3380    end
3381    if isfield(UvData.Field,'Mesh')&~isempty(UvData.Field.Mesh)
3382        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
3383        data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
3384        data.DX=UvData.Field.Mesh;
3385        data.DY=UvData.Field.Mesh;
3386    elseif isfield(UvData.Field,'AX')&isfield(UvData.Field,'AY')& isfield(UvData.Field,'A')%only image
3387        np=size(UvData.Field.A);
3388        meshx=(UvData.Field.AX(end)-UvData.Field.AX(1))/np(2);
3389        meshy=abs(UvData.Field.AY(end)-UvData.Field.AY(1))/np(1);
3390        data.RangeY=max(meshx,meshy);
3391        data.RangeX=max(meshx,meshy);
3392        data.DX=max(meshx,meshy);
3393    end
3394    data.ParentButton=handles.VOLUME;
3395    PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
3396    [hset_object,UvData.sethandles]=set_object(data,PlotHandles);% call the set_object interface with action on haxes,
3397                                                      % associate the set_object interface handle to the plotting axes
3398    if isfield(UvData.OpenParam,'SetObjectOrigin')                                               
3399    pos_uvmat=get(handles.uvmat,'Position');
3400    pos_set_object(1:2)=UvData.OpenParam.SetObjectOrigin + pos_uvmat(1:2);
3401    pos_set_object(3:4)=UvData.OpenParam.SetObjectSize .* pos_uvmat(3:4); 
3402    set(hset_object,'Position',pos_set_object)
3403    end
3404    UvData.MouseAction='create_object';
3405else
3406    set(handles.VOLUME,'BackgroundColor',[0 1 0])
3407    UvData.MouseAction='none';
3408end
3409set(handles.uvmat,'UserData',UvData)
3410
3411%-------------------------------------------------------
3412function edit_vect_Callback(hObject, eventdata, handles)
3413%-------------------------------------------------------
3414%
3415% UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3416if isequal(get(handles.edit_vect,'Value'),1)
3417    test_civ2=isequal(get(handles.civ2,'BackgroundColor'),[1 1 0]);
3418    test_civ1=isequal(get(handles.VelType,'BackgroundColor'),[1 1 0]);
3419    if ~test_civ2 && ~test_civ1
3420        msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
3421    end
3422    set(handles.record,'Visible','on')
3423    set(handles.edit_vect,'BackgroundColor',[1 1 0])
3424    set(handles.edit_object,'Value',0)
3425    set(handles.CheckZoom,'Value',0)
3426    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3427%     set(handles.create,'Value',0)
3428%     set(handles.create,'BackgroundColor',[0 1 0])
3429    set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
3430    set(gcf,'Pointer','arrow')
3431%     UvData.MouseAction='edit_vect';
3432else
3433    set(handles.record,'Visible','off')
3434    set(handles.edit_vect,'BackgroundColor',[0.7 0.7 0.7])
3435%     UvData.MouseAction='none';
3436end
3437% set(handles.uvmat,'UserData',UvData)
3438
3439%----------------------------------------------
3440function save_mask_Callback(hObject, eventdata, handles)
3441%-----------------------------------------------------------------------
3442UvData=get(handles.uvmat,'UserData');
3443
3444flag=1;
3445npx=size(UvData.Field.A,2);
3446npy=size(UvData.Field.A,1);
3447xi=0.5:npx-0.5;
3448yi=0.5:npy-0.5;
3449[Xi,Yi]=meshgrid(xi,yi);
3450if isfield(UvData,'Object')
3451    for iobj=1:length(UvData.Object)
3452        ObjectData=UvData.Object{iobj};
3453        if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
3454            flagobj=1;
3455            testphys=0; %coordinates in pixels by default
3456            if isfield(ObjectData,'CoordType') && isequal(ObjectData.CoordType,'phys')
3457                if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
3458                    Calib=UvData.XmlData{1}.GeometryCalib;
3459                    testphys=1;
3460                end
3461            end
3462            if isfield(ObjectData,'Coord')& isfield(ObjectData,'Style')
3463                if isequal(ObjectData.Type,'polygon')
3464                    X=ObjectData.Coord(:,1);
3465                    Y=ObjectData.Coord(:,2);
3466                    if testphys
3467                        [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
3468                    end
3469                    flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside                 
3470                elseif isequal(ObjectData.Type,'ellipse')
3471                    if testphys
3472                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3473                    end
3474                    RangeX=max(ObjectData.RangeX);
3475                    RangeY=max(ObjectData.RangeY);
3476                    X2Max=RangeX*RangeX;
3477                    Y2Max=RangeY*RangeY;
3478                    distX=(Xi-ObjectData.Coord(1,1));
3479                    distY=(Yi-ObjectData.Coord(1,2));
3480                    flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
3481                elseif isequal(ObjectData.Type,'rectangle')
3482                    if testphys
3483                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3484                    end
3485                    distX=abs(Xi-ObjectData.Coord(1,1));
3486                    distY=abs(Yi-ObjectData.Coord(1,2));
3487                    flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
3488                end
3489                if isequal(ObjectData.ProjMode,'mask_outside')
3490                    flagobj=~flagobj;
3491                end
3492                flag=flag & flagobj;
3493            end
3494        end
3495    end
3496end
3497% flag=~flag;
3498%mask name
3499RootPath=get(handles.RootPath,'String');
3500RootFile=get(handles.RootFile,'String');
3501RootFile=regexprep(RootFile,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3502filebase=fullfile(RootPath,RootFile);
3503list=get(handles.masklevel,'String');
3504masknumber=num2str(length(list));
3505maskindex=get(handles.masklevel,'Value');
3506mask_name=fullfile_uvmat(RootPath,SubDir,[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
3507%mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
3508imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
3509imflag=flipdim(imflag,1);
3510% imflag=uint8(255*flag);% =0 for flag=0 (vectors=0 when 20<imflag<200)
3511msgbox_uvmat('CONFIRMATION',[mask_name ' saved'])
3512imwrite(imflag,mask_name,'BitDepth',8);
3513
3514%display the mask
3515figure;
3516vec=linspace(0,1,256);%define a linear greyscale colormap
3517map=[vec' vec' vec'];
3518colormap(map)
3519
3520image(imflag);
3521
3522%-------------------------------------------------------------------
3523%-------------------------------------------------------------------
3524%  - FUNCTIONS FOR SETTING PLOTTING PARAMETERS
3525
3526%------------------------------------------------------------------
3527%-------------------------------------------------------------
3528% --- Executes on selection change in transform_fct.
3529function transform_fct_Callback(hObject, eventdata, handles)
3530%-------------------------------------------------------------
3531UvData=get(handles.uvmat,'UserData');
3532menu=get(handles.transform_fct,'String');
3533ind_coord=get(handles.transform_fct,'Value');
3534coord_option=menu{ind_coord};
3535list_transform=get(handles.transform_fct,'UserData');
3536ff=functions(list_transform{end}); 
3537if isequal(coord_option,'more...');
3538    coord_fct='';
3539    prompt = {'Enter the name of the transform function'};
3540    dlg_title = 'user defined transform';
3541    num_lines= 1;
3542    [FileName, PathName] = uigetfile( ...
3543       {'*.m', ' (*.m)';
3544        '*.m',  '.m files '; ...
3545        '*.*', 'All Files (*.*)'}, ...
3546        'Pick a file', ff.file);
3547    if isequal(PathName(end),'/')||isequal(PathName(end),'\')
3548        PathName(end)=[];
3549    end
3550    transform_selected =fullfile(PathName,FileName);
3551    if ~exist(transform_selected,'file')
3552           return
3553    end
3554   [ppp,transform,ext_fct]=fileparts(FileName);% removes extension .m
3555   if ~isequal(ext_fct,'.m')
3556        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
3557        return
3558   end
3559   menu=update_menu(handles.transform_fct,transform);%add the selected fct to the menu
3560   ind_coord=get(handles.transform_fct,'Value');
3561   addpath(PathName)
3562   list_transform{ind_coord}=str2func(transform);% create the function handle corresponding to the newly seleced function
3563   set(handles.transform_fct,'UserData',list_transform)
3564   rmpath(PathName)
3565   % save the new menu in the personal file 'uvmat_perso.mat'
3566   dir_perso=prefdir;%personal Matalb directory
3567   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3568   if exist(profil_perso,'file')
3569       nb_builtin=UvData.OpenParam.NbBuiltin;
3570       for ilist=nb_builtin+1:numel(list_transform)
3571           ff=functions(list_transform{ilist});
3572           transform_fct{ilist-nb_builtin}=ff.file;
3573       end
3574        save (profil_perso,'transform_fct','-append'); %store the root name for future opening of uvmat
3575   end   
3576end
3577
3578%% check the current path to the selected function
3579if isa(list_transform{ind_coord},'function_handle')
3580    func=functions(list_transform{ind_coord});
3581    set(handles.path_transform,'String',fileparts(func.file)); %show the path to the senlected function
3582else
3583    set(handles.path_transform,'String','')
3584end
3585
3586set(handles.CheckFixLimits,'Value',0)
3587set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
3588
3589%% delete drawn objects
3590hother=findobj('Tag','proj_object');%find all the proj objects
3591for iobj=1:length(hother)
3592    delete_object(hother(iobj))
3593end
3594hother=findobj('Tag','DeformPoint');%find all the proj objects
3595for iobj=1:length(hother)
3596    delete_object(hother(iobj))
3597end
3598hh=findobj('Tag','calib_points');
3599if ~isempty(hh)
3600    delete(hh)
3601end
3602hhh=findobj('Tag','calib_marker');
3603if ~isempty(hhh)
3604    delete(hhh)
3605end
3606if isfield(UvData,'Object')
3607     UvData.Object=UvData.Object(1);
3608end
3609set(handles.ListObject,'Value',1)
3610set(handles.ListObject,'String',{'plane'})
3611set(handles.ListObject_1,'Value',1)
3612set(handles.ListObject_1,'String',{'plane'})
3613
3614%delete mask if it is displayed
3615% if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
3616%    UvData=rmfield(UvData,'MaskName'); %will impose mask refresh 
3617% end
3618set(handles.uvmat,'UserData',UvData)
3619run0_Callback(hObject, eventdata, handles)
3620
3621
3622
3623%------------------------------------------------
3624%CALLBACKS FOR PLOTTING PARAMETERS
3625%-------------------------------------------------
3626%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3627% Plot coordinates
3628%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3629%------------------------------------------------------------------------
3630function num_MinX_Callback(hObject, eventdata, handles)
3631%------------------------------------------------------------------------
3632set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3633set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3634update_plot(handles);
3635
3636%------------------------------------------------------------------------
3637function num_MaxX_Callback(hObject, eventdata, handles)
3638%------------------------------------------------------------------------
3639set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3640set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3641update_plot(handles);
3642
3643%------------------------------------------------------------------------
3644function num_MinY_Callback(hObject, eventdata, handles)
3645%------------------------------------------
3646set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3647set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3648update_plot(handles);
3649
3650%------------------------------------------------------------------------
3651function num_MaxY_Callback(hObject, eventdata, handles)
3652%------------------------------------------------------------------------
3653set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3654set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3655update_plot(handles);
3656
3657%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3658% Scalar or image representation
3659%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3660%------------------------------------------------------------------------
3661function num_MinA_Callback(hObject, eventdata, handles)
3662%------------------------------------------
3663set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3664set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3665MinA=str2double(get(handles.num_MinA,'String'));
3666MaxA=str2double(get(handles.num_MaxA,'String'));
3667if MinA>MaxA% switch minA and maxA in case of error
3668    MinA_old=MinA;
3669    MinA=MaxA;
3670    MaxA=MinA_old;
3671    set(handles.num_MinA,'String',num2str(MinA,5));
3672    set(handles.num_MaxA,'String',num2str(MaxA,5));
3673end
3674update_plot(handles);
3675
3676%------------------------------------------------------------------------
3677function num_MaxA_Callback(hObject, eventdata, handles)
3678%------------------------------------------------------------------------
3679set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3680set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3681MinA=str2double(get(handles.num_MinA,'String'));
3682MaxA=str2double(get(handles.num_MaxA,'String'));
3683if MinA>MaxA% switch minA and maxA in case of error
3684        MinA_old=MinA;
3685    MinA=MaxA;
3686    MaxA=MinA_old;
3687    set(handles.num_MinA,'String',num2str(MinA,5));
3688    set(handles.num_MaxA,'String',num2str(MaxA,5));
3689end
3690update_plot(handles);
3691
3692%------------------------------------------------------------------------
3693function CheckFixScalar_Callback(hObject, eventdata, handles)
3694%------------------------------------------------------------------------
3695test=get(handles.CheckFixScalar,'Value');
3696if test
3697    set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3698else
3699    set(handles.CheckFixScalar,'BackgroundColor',[0.7 0.7 0.7])
3700    update_plot(handles);
3701end
3702
3703%-------------------------------------------------------------------
3704function CheckBW_Callback(hObject, eventdata, handles)
3705%-------------------------------------------------------------------
3706update_plot(handles);
3707
3708%-------------------------------------------------------------------
3709function num_Opacity_Callback(hObject, eventdata, handles)
3710update_plot(handles);
3711%-------------------------------------------------------------------
3712
3713%-------------------------------------------------------------------
3714function ListContour_Callback(hObject, eventdata, handles)
3715%-------------------------------------------------------------------
3716val=get(handles.ListContour,'Value');
3717if val==2
3718    set(handles.interval_txt,'Visible','on')
3719    set(handles.num_IncrA,'Visible','on')
3720else
3721    set(handles.interval_txt,'Visible','off')
3722    set(handles.num_IncrA,'Visible','off')
3723end
3724update_plot(handles);
3725
3726%-------------------------------------------------------------------
3727function num_IncrA_Callback(hObject, eventdata, handles)
3728%-------------------------------------------------------------------
3729update_plot(handles);
3730
3731
3732%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3733% Vector representation
3734%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3735%-------------------------------------------------------------------
3736function CheckHideWarning_Callback(hObject, eventdata, handles)
3737%-------------------------------------------------------------------
3738update_plot(handles);
3739
3740%-------------------------------------------------------------------
3741function CheckHideFalse_Callback(hObject, eventdata, handles)
3742%-------------------------------------------------------------------
3743update_plot(handles);
3744
3745%-------------------------------------------------------------------
3746function num_VecScale_Callback(hObject, eventdata, handles)
3747%-------------------------------------------------------------------
3748set(handles.CheckFixVectors,'Value',1);
3749set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3750update_plot(handles);
3751
3752%-------------------------------------------------------------------
3753function CheckFixVectors_Callback(hObject, eventdata, handles)
3754%-------------------------------------------------------------------
3755test=get(handles.CheckFixVectors,'Value');
3756if test
3757    set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3758else
3759    update_plot(handles);
3760    %set(handles.num_VecScale,'String',num2str(ScalOut.num_VecScale,3))
3761    set(handles.CheckFixVectors,'BackgroundColor',[0.7 0.7 0.7])
3762end
3763
3764%------------------------------------------------------------------------
3765% --- Executes on selection change in CheckDecimate4 (nb_vec/4).
3766function CheckDecimate4_Callback(hObject, eventdata, handles)
3767%------------------------------------------------------------------------
3768update_plot(handles);
3769
3770%------------------------------------------------------------------------
3771% --- Executes on selection change in ColorCode menu
3772function ColorCode_Callback(hObject, eventdata, handles)
3773%------------------------------------------------------------------------
3774% edit the choice for color code
3775update_color_code_boxes(handles);
3776update_plot(handles);
3777
3778%------------------------------------------------------------------------
3779function update_color_code_boxes(handles)
3780%------------------------------------------------------------------------
3781list_code=get(handles.ColorCode,'String');% list menu fields
3782colcode= list_code{get(handles.ColorCode,'Value')}; % selected field
3783enable_slider='off';%default
3784enable_bounds='off';%default
3785enable_scalar='off';%default
3786switch colcode
3787    case {'rgb','bgr'}
3788        enable_slider='on';
3789        enable_bounds='on';
3790        enable_scalar='on';
3791    case '64 colors'
3792        enable_bounds='on';
3793        enable_scalar='on';
3794end
3795set(handles.Slider1,'Visible',enable_slider)
3796set(handles.Slider2,'Visible', enable_slider)
3797set(handles.num_ColCode1,'Visible',enable_slider)
3798set(handles.num_ColCode2,'Visible',enable_slider)
3799set(handles.TitleColCode1,'Visible',enable_slider)
3800set(handles.TitleColCode2,'Visible',enable_slider)
3801set(handles.CheckFixVecColor,'Visible',enable_bounds)
3802set(handles.num_MinVec,'Visible',enable_bounds)
3803set(handles.num_MaxVec,'Visible',enable_bounds)
3804set(handles.ColorScalar,'Visible',enable_scalar)
3805set_vec_col_bar(handles)
3806
3807%------------------------------------------------------------------
3808% --- Executes on selection change in ColorScalar: choice of the color code.
3809function ColorScalar_Callback(hObject, eventdata, handles)
3810%------------------------------------------------------------------
3811% edit the choice for color code
3812list_scalar=get(handles.ColorScalar,'String');% list menu fields
3813col_scalar= list_scalar{get(handles.ColorScalar,'Value')}; % selected field
3814if isequal(col_scalar,'ima_cor')
3815    set(handles.CheckFixVecColor,'Value',1)%fixed scale by default
3816    ColorCode='rgb';
3817    set(handles.num_MinVec,'String','0')
3818    set(handles.num_MaxVec,'String','1')
3819    set(handles.num_ColCode1,'String','0.333')
3820    set(handles.num_ColCode2,'String','0.666')
3821else
3822    set(handles.CheckFixVecColor,'Value',0)%auto scale between min,max by default
3823    ColorCode='64 colors';
3824end
3825ColorCodeList=get(handles.ColorCode,'String');
3826ichoice=find(strcmp(ColorCode,ColorCodeList),1);
3827set(handles.ColorCode,'Value',ichoice)% set color code in the menu
3828
3829update_color_code_boxes(handles);
3830%replot the current graph
3831run0_Callback(hObject, eventdata, handles)
3832
3833%----------------------------------------------------------------
3834% -- Executes on slider movement to set the color code
3835%
3836function Slider1_Callback(hObject, eventdata, handles)
3837%------------------------------------------------------------------
3838slider1=get(handles.Slider1,'Value');
3839min_val=str2num(get(handles.num_MinVec,'String'));
3840max_val=str2num(get(handles.num_MaxVec,'String'));
3841col=min_val+(max_val-min_val)*slider1;
3842set(handles.num_ColCode1,'String',num2str(col))
3843if(get(handles.Slider2,'Value') < col)%move also the second slider at the same value if needed
3844    set(handles.Slider2,'Value',col)
3845    set(handles.num_ColCode2,'String',num2str(col))
3846end
3847set_vec_col_bar(handles)
3848update_plot(handles);
3849
3850%----------------------------------------------------------------
3851% Executes on slider movement to set the color code
3852%----------------------------------------------------------------
3853function Slider2_Callback(hObject, eventdata, handles)
3854slider2=get(handles.Slider2,'Value');
3855min_val=str2num(get(handles.num_MinVec,'String'));
3856max_val=str2num(get(handles.num_MaxVec,'String'));
3857col=min_val+(max_val-min_val)*slider2;
3858set(handles.num_ColCode2,'String',num2str(col))
3859if(get(handles.Slider1,'Value') > col)%move also the first slider at the same value if needed
3860    set(handles.Slider1,'Value',col)
3861    set(handles.num_ColCode1,'String',num2str(col))
3862end
3863set_vec_col_bar(handles)
3864update_plot(handles);
3865
3866%----------------------------------------------------------------
3867% --- Execute on return carriage on the edit box corresponding to slider 1
3868%----------------------------------------------------------------
3869function num_ColCode1_Callback(hObject, eventdata, handles)
3870set_vec_col_bar(handles)
3871update_plot(handles);
3872
3873%----------------------------------------------------------------
3874% --- Execute on return carriage on the edit box corresponding to slider 2
3875%----------------------------------------------------------------
3876function num_ColCode2_Callback(hObject, eventdata, handles)
3877set_vec_col_bar(handles)
3878update_plot(handles);
3879%------------------------------------------------------------------------
3880%-------------------------------------------------------
3881% --- Executes on button press in CheckFixVecColor.
3882%-------------------------------------------------------
3883function VecColBar_Callback(hObject, eventdata, handles)
3884set_vec_col_bar(handles)
3885
3886%------------------------------------------------------------------------
3887% --- Executes on button press in CheckFixVecColor.
3888function CheckFixVecColor_Callback(hObject, eventdata, handles)
3889%------------------------------------------------------------------------
3890if ~get(handles.CheckFixVecColor,'Value')
3891    update_plot(handles);
3892end
3893
3894%------------------------------------------------------------------------
3895% --- Executes on selection change in num_MaxVec.
3896function num_MinVec_Callback(hObject, eventdata, handles)
3897%------------------------------------------------------------------------
3898max_vec_Callback(hObject, eventdata, handles)
3899
3900%------------------------------------------------------------------------
3901% --- Executes on selection change in num_MaxVec.
3902function num_MaxVec_Callback(hObject, eventdata, handles)
3903%------------------------------------------------------------------------
3904set(handles.CheckFixVecColor,'Value',1)
3905CheckFixVecColor_Callback(hObject, eventdata, handles)
3906min_val=str2num(get(handles.num_MinVec,'String'));
3907max_val=str2num(get(handles.num_MaxVec,'String'));
3908slider1=get(handles.Slider1,'Value');
3909slider2=get(handles.Slider2,'Value');
3910colcode1=min_val+(max_val-min_val)*slider1;
3911colcode2=min_val+(max_val-min_val)*slider2;
3912set(handles.num_ColCode1,'String',num2str(colcode1))
3913set(handles.num_ColCode2,'String',num2str(colcode2))
3914update_plot(handles);
3915
3916%------------------------------------------------------------------------
3917% --- update the display of color code for vectors (on vecColBar)
3918function set_vec_col_bar(handles)
3919%------------------------------------------------------------------------
3920%get the image of the color display button 'VecColBar' in pixels
3921set(handles.VecColBar,'Unit','pixel');
3922pos_vert=get(handles.VecColBar,'Position');
3923set(handles.VecColBar,'Unit','Normalized');
3924width=ceil(pos_vert(3));
3925height=ceil(pos_vert(4));
3926
3927%get slider indications
3928list=get(handles.ColorCode,'String');
3929ichoice=get(handles.ColorCode,'Value');
3930colcode.ColorCode=list{ichoice};
3931colcode.MinVec=str2num(get(handles.num_MinVec,'String'));
3932colcode.MaxVec=str2num(get(handles.num_MaxVec,'String'));
3933test3color=strcmp(colcode.ColorCode,'rgb') || strcmp(colcode.ColorCode,'bgr');
3934if test3color
3935    colcode.ColCode1=str2num(get(handles.num_ColCode1,'String'));
3936    colcode.ColCode2=str2num(get(handles.num_ColCode2,'String'));
3937end
3938vec_C=colcode.MinVec+(colcode.MaxVec-colcode.MinVec)*(0.5:width-0.5)/width;%sample of vec_C values from min to max
3939[colorlist,col_vec]=set_col_vec(colcode,vec_C);
3940oneheight=ones(1,height);
3941A1=colorlist(col_vec,1)*oneheight;
3942A2=colorlist(col_vec,2)*oneheight;
3943A3=colorlist(col_vec,3)*oneheight;
3944A(:,:,1)=A1';
3945A(:,:,2)=A2';
3946A(:,:,3)=A3';
3947set(handles.VecColBar,'Cdata',A)
3948
3949%-------------------------------------------------------------------
3950function update_plot(handles)
3951%-------------------------------------------------------------------
3952UvData=get(handles.uvmat,'UserData');
3953AxeData=UvData.axes3;% retrieve the current plotted data
3954PlotParam=read_GUI(handles.uvmat);
3955[tild,PlotParamOut]= plot_field(AxeData,handles.axes3,PlotParam);
3956write_plot_param(handles,PlotParamOut); %update the auto plot parameters
3957
3958%------------------------------------------------------------------------
3959%------------------------------------------------------------------------
3960%   SELECTION AND EDITION OF PROJECTION OBJECTS
3961%------------------------------------------------------------------------
3962%------------------------------------------------------------------------
3963
3964% --- Executes on selection change in ListObject_1.
3965function ListObject_1_Callback(hObject, eventdata, handles)
3966list_str=get(handles.ListObject,'String');
3967UvData=get(handles.uvmat,'UserData');
3968ObjectData=UvData.Object{get(handles.ListObject_1,'Value')};
3969
3970%% update the projection plot on uvmat
3971ProjData= proj_field(UvData.Field,ObjectData);%project the current input field on object ObjectData
3972plot_field(ProjData,handles.axes3,read_GUI(handles.uvmat));% plot the projected field;
3973%replot all the objects within the new projected field
3974for IndexObj=1:numel(list_str)
3975    IndexObj
3976        hobject=UvData.Object{IndexObj}.DisplayHandle.uvmat
3977        if isempty(hobject) || ~ishandle(hobject)
3978            hobject=handles.axes3
3979        end
3980        if isequal(IndexObj,get(handles.ListObject,'Value'))
3981            objectcolor='m'; %paint in magenta the currently selected object in ListObject
3982        else
3983            objectcolor='b';
3984        end
3985        UvData.Object{IndexObj}.DisplayHandle.uvmat=plot_object(UvData.Object{IndexObj},ObjectData,hobject,objectcolor);%draw the object in uvmat     
3986end
3987set(handles.uvmat,'UserData',UvData)
3988
3989%% display the object parameters if the GUI set_object is already opened
3990if ~get(handles.ViewObject,'Value')
3991    ZBounds=0; % default
3992    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
3993        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
3994        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
3995    end
3996    ObjectData.Name=list_str{get(handles.ListObject_1,'Value')};
3997    set_object(ObjectData,[],ZBounds);
3998    set(handles.ViewObject,'Value',1)% show that the selected object in ListObject_1 is currently visualised
3999end
4000
4001%  desactivate the edit object mode
4002set(handles.edit_object,'Value',0)
4003set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7])
4004
4005%------------------------------------------------------------------------
4006% --- Executes on selection change in ListObject.
4007function ListObject_Callback(hObject, eventdata, handles)
4008%------------------------------------------------------------------------
4009list_str=get(handles.ListObject,'String');
4010IndexObj=get(handles.ListObject,'Value');%present object selection
4011
4012%% The object  is displayed in set_object if this GUI is already opened
4013UvData=get(handles.uvmat,'UserData');
4014ObjectData=UvData.Object{IndexObj};
4015hset_object=findobj(allchild(0),'tag','set_object');
4016if ~isempty(hset_object)
4017    ZBounds=0; % default
4018    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4019        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4020        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4021    end
4022    ObjectData.Name=list_str{IndexObj};
4023    set_object(ObjectData,[],ZBounds);
4024    set(handles.ViewField,'Value',1)% show that the selected object in ListObject is currently visualised
4025end
4026
4027%%  desactivate the edit object mode
4028set(handles.edit_object,'Value',0)
4029set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7])
4030
4031%% update the  plot on view_field if view_field is already openened
4032hview_field=findobj(allchild(0),'tag','view_field');
4033if isempty(hview_field)
4034    hhview_field.axes3=[];
4035else
4036    Data=get(hview_field,'UserData');
4037    hhview_field=guidata(hview_field);
4038    ProjData= proj_field(UvData.Field,ObjectData);%project the current interface field on ObjectData
4039    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.axes3,read_GUI(hview_field));%read plotting parameters on the uvmat interfachhview_fiel
4040    write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4041    haxes=findobj(hview_field,'tag','axes3');
4042    pos=get(hview_field,'Position'); 
4043    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4044        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4045        pos_table=get(h_TableDisplay,'Position');
4046        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4047        drawnow% needed to change position before the next command
4048        set(hview_field,'UserData',Data);% restore the previously stored GUI position after GUI resizing
4049    else
4050        set(hview_field,'Position',Data.GUISize)% return to the previously stored GUI position and size
4051    end
4052end
4053
4054%% update the color of the graphic object representation: the selected object in magenta, others in blue
4055update_object_color(handles.axes3,hhview_field.axes3,UvData.Object{IndexObj}.DisplayHandle.uvmat)
4056
4057%------------------------------------------------------------------------
4058%--- update the color representation of objects (indicating the selected ones)
4059function update_object_color(axes_uvmat,axes_view_field,DisplayHandle)
4060%------------------------------------------------------------------------
4061if isempty(axes_view_field)% case with no view_field plot
4062hother=[findobj(axes_uvmat,'Tag','proj_object');findobj(axes_uvmat,'Tag','DeformPoint')];%find all the proj object and deform point representations
4063else
4064hother=[findobj(axes_uvmat,'Tag','proj_object') ;findobj(axes_view_field,'Tag','proj_object');... %find all the proj object representations
4065findobj(axes_uvmat,'Tag','DeformPoint'); findobj(axes_view_field,'Tag','DeformPoint')];%find all the deform point representations
4066end
4067for iobj=1:length(hother)
4068    if isequal(get(hother(iobj),'Type'),'rectangle')||isequal(get(hother(iobj),'Type'),'patch')
4069        set(hother(iobj),'EdgeColor','b')
4070        if isequal(get(hother(iobj),'FaceColor'),'m')
4071            set(hother(iobj),'FaceColor','b')
4072        end
4073    elseif isequal(get(hother(iobj),'Type'),'image')
4074        Acolor=get(hother(iobj),'CData');
4075        Acolor(:,:,1)=zeros(size(Acolor,1),size(Acolor,2));
4076        set(hother(iobj),'CData',Acolor);
4077    else
4078        set(hother(iobj),'Color','b')
4079    end
4080    set(hother(iobj),'Selected','off')
4081end
4082if ishandle(DisplayHandle)
4083    linetype=get(DisplayHandle,'Type');
4084    if isequal(linetype,'line')
4085        set(DisplayHandle,'Color','m'); %set the selected object to magenta color
4086    elseif isequal(linetype,'rectangle')
4087        set(DisplayHandle,'EdgeColor','m'); %set the selected object to magenta color
4088    elseif isequal(linetype,'patch')
4089        set(DisplayHandle,'FaceColor','m'); %set the selected object to magenta color
4090    end
4091    SubObjectData=get(DisplayHandle,'UserData');
4092    if isfield(SubObjectData,'SubObject') & ishandle(SubObjectData.SubObject)
4093        for iobj=1:length(SubObjectData.SubObject)
4094            hsub=SubObjectData.SubObject(iobj);
4095            if isequal(get(hsub,'Type'),'rectangle')
4096                set(hsub,'EdgeColor','m'); %set the selected object to magenta color
4097            elseif isequal(get(hsub,'Type'),'image')
4098                Acolor=get(hsub,'CData');
4099                Acolor(:,:,1)=Acolor(:,:,3);
4100                set(hsub,'CData',Acolor);
4101            else
4102                set(hsub,'Color','m')
4103            end
4104        end
4105    end
4106    if isfield(SubObjectData,'DeformPoint') & ishandle(SubObjectData.DeformPoint)
4107        set(SubObjectData.DeformPoint,'Color','m')
4108    end
4109end
4110
4111%-------------------------------------------------------------------
4112% --- Executes on selection change in edit_object.
4113function edit_object_Callback(hObject, eventdata, handles)
4114%-------------------------------------------------------------------
4115UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4116hset_object=findobj(allchild(0),'Tag','set_object');
4117if get(handles.edit_object,'Value')
4118    set(handles.edit_object,'BackgroundColor',[1,1,0]) 
4119    %suppress the other options
4120    set(handles.CheckZoom,'Value',0)
4121    CheckZoom_Callback(hObject, eventdata, handles)
4122    hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4123    if ishandle(hgeometry_calib)
4124        hhgeometry_calib=guidata(hgeometry_calib);
4125        set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4126        set(hhgeometry_calib.edit_append,'BackgroundColor',[0.7 0.7 0.7])
4127    end
4128    set(handles.ViewObject,'value',1)
4129    ViewObject_Callback(hObject, eventdata, handles)
4130else % desctivate object edit mode
4131    set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4132    if ~isempty(hset_object)% open the
4133        hhset_object=guidata(hset_object);
4134        set(hhset_object.PLOT,'enable','off');
4135        set(get(hset_object,'children'),'enable','inactive')
4136    end
4137end
4138
4139
4140%------------------------------------------------------------------------
4141% --- Executes on button press in ViewObject.
4142function ViewObject_Callback(hObject, eventdata, handles)
4143%------------------------------------------------------------------------
4144check_view=get(handles.ViewObject,'Value');
4145
4146if check_view %activate set_object   
4147    IndexObj=get(handles.ListObject,'Value');
4148    list_object=get(handles.ListObject,'String');
4149    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4150    UvData.Object{IndexObj}.Name=list_object{IndexObj};
4151    if numel(UvData.Object)<IndexObj;% error in UvData
4152        msgbox_uvmat('ERROR','invalid object list')
4153        return
4154    end
4155    ZBounds=0; % default
4156    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4157        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4158        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4159    end
4160%     set(handles.ListObject_1,'Value',IndexObj);%restore ListObject selection after set_object deletion
4161    data=UvData.Object{IndexObj};
4162    if ~isfield(data,'Type')% default plane
4163        data.Type='plane';
4164    end
4165    if isfield(UvData,'Field')
4166        Field=UvData.Field;
4167        if isfield(UvData.Field,'Mesh')&&~isempty(UvData.Field.Mesh)
4168            data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4169            if strcmp(data.Type,'line')||strcmp(data.Type,'polyline')
4170                data.RangeY=UvData.Field.Mesh;
4171            else
4172                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4173            end
4174            data.DX=UvData.Field.Mesh;
4175            data.DY=UvData.Field.Mesh;
4176        end
4177        if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4178            data.Coord=[0 0 0]; %default
4179        end
4180        if isfield(Field,'CoordUnit')
4181            data.CoordUnit=Field.CoordUnit;
4182        end
4183    end
4184    hset_object=set_object(data,[],ZBounds);
4185    hhset_object=guidata(hset_object);
4186    if get(handles.edit_object,'Value')% edit mode
4187        set(hhset_object.PLOT,'Enable','on')
4188        set(get(hset_object,'children'),'enable','on')
4189    else
4190        set(hhset_object.PLOT,'Enable','off')
4191        set(get(hset_object,'children'),'enable','inactive')% deactivate the GUI except SAVE
4192        set(hhset_object.SAVE,'Enable','on')
4193    end
4194else
4195    hset_object=findobj(allchild(0),'tag','set_object');
4196    if ~isempty(hset_object)
4197        delete(hset_object)% delete existing version of set_object
4198    end
4199end
4200 
4201
4202%------------------------------------------------------------------------
4203% --- Executes on button press in ViewField.
4204function ViewField_Callback(hObject, eventdata, handles)
4205%------------------------------------------------------------------------
4206check_view=get(handles.ViewField,'Value');
4207
4208if check_view
4209    IndexObj=get(handles.ListObject,'Value');
4210    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4211    if numel(UvData.Object)<IndexObj(end);% error in UvData
4212        msgbox_uvmat('ERROR','invalid object list')
4213        return
4214    end
4215    ZBounds=0; % default
4216    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4217        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4218        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4219    end
4220    set(handles.ListObject,'Value',IndexObj);%restore ListObject selection after set_object deletion
4221    if ~isfield(UvData.Object{IndexObj(1)},'Type')% default plane
4222        UvData.Object{IndexObj(1)}.Type='plane';
4223    end
4224    list_object=get(handles.ListObject,'String');
4225    UvData.Object{IndexObj(end)}.Name=list_object{IndexObj(end)};
4226   
4227    %% show the projection of the selected object on view_field
4228    ProjData= proj_field(UvData.Field,UvData.Object{IndexObj});%project the current field on ObjectData
4229    hview_field=findobj(allchild(0),'tag','view_field');
4230    if isempty(hview_field)
4231        hview_field=view_field;
4232    end
4233    hhview_field=guidata(hview_field);
4234    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.axes3,read_GUI(hview_field));%read plotting parameters on the GUI view_field);
4235    write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4236    haxes=findobj(hview_field,'tag','axes3');
4237    pos=get(hview_field,'Position');
4238    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4239        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4240        pos_table=get(h_TableDisplay,'Position');
4241        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4242    else
4243        Data=get(hview_field,'UserData');
4244        set(hview_field,'Position',Data.GUISize)% restore the size of view_field for plots
4245    end
4246else
4247    hview_field=findobj(allchild(0),'tag','view_field');
4248    if ~isempty(hview_field)
4249        delete(hview_field)% delete existing version of set_object
4250    end
4251end
4252
4253
4254%------------------------------------------------------------------------
4255% --- Executes on button press in delete_object.
4256function delete_object_Callback(hObject, eventdata, handles)
4257%------------------------------------------------------------------------
4258IndexObj=get(handles.ListObject,'Value');
4259IndexObj_1=get(handles.ListObject_1,'Value');
4260if IndexObj>1 && ~isequal(IndexObj,IndexObj_1)
4261    delete_object(IndexObj)
4262end
4263
4264%------------------------------------------------------------------------
4265%------------------------------------------------------------------------
4266%  II - TOOLS FROM THE UPPER MENU BAR
4267%------------------------------------------------------------------------
4268%------------------------------------------------------------------------
4269
4270%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4271% Export  Menu Callbacks
4272%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4273%------------------------------------------------------------------------
4274% --- Executes on button press in Menu/Export/field in workspace.
4275function MenuExportField_Callback(hObject, eventdata, handles)
4276%------------------------------------------------------------------------
4277global Data_uvmat
4278Data_uvmat=get(handles.uvmat,'UserData');
4279evalin('base','global Data_uvmat')%make CurData global in the workspace
4280display('current field :')
4281evalin('base','Data_uvmat') %display CurData in the workspace
4282commandwindow; %brings the Matlab command window to the front
4283
4284%------------------------------------------------------------------------
4285% --- Executes on button press in Menu/Export/extract figure.
4286function MenuExportFigure_Callback(hObject, eventdata, handles)
4287%------------------------------------------------------------------------
4288% huvmat=get(handles.MenuExport,'parent');
4289hfig=figure;
4290copyobj(handles.axes3,hfig);
4291map=colormap(handles.axes3);
4292colormap(map);%transmit the current colormap to the zoom fig
4293colorbar
4294
4295% %------------------------------------------------------
4296% % --- Executes on button press in Menu/Export/extract figure.
4297% %------------------------------------------------------
4298% function MenuExport_plot_Callback(hObject, eventdata, handles)
4299% huvmat=get(handles.MenuExport_plot,'parent');
4300% UvData=get(huvmat,'UserData');
4301% hfig=figure;
4302% newaxes=copyobj(handles.axes3,hfig);
4303% map=colormap(handles.axes3);
4304% colormap(map);%transmit the current colormap to the zoom fig
4305% colorbar
4306
4307%
4308% % --------------------------------------------------------------------
4309% function Insert_Callback(hObject, eventdata, handles)
4310%
4311
4312%------------------------------------------------------------------------
4313% --------------------------------------------------------------------
4314function MenuExportMovie_Callback(hObject, eventdata, handles)
4315% --------------------------------------------------------------------
4316set(handles.MenuExportMovie,'BusyAction','queue')% activate the button
4317huvmat=get(handles.run0,'parent');
4318UvData=get(huvmat,'UserData');
4319%[xx,xx,FileBase]=read_file_boxes(handles);
4320[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4321FileBase=fullfile(RootPath,RootFile);
4322 %read the current input file name
4323prompt = {'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)'};
4324dlg_title = 'select properties of the output avi movie';
4325num_lines= 1;
4326% nbfield_cell=get(handles.last_i,'String');
4327def     = {[FileBase '_out.avi'];'10';'1';'[0.03 0.05 0.95 0.92]';'10'};
4328answer = inputdlg(prompt,dlg_title,num_lines,def,'on');
4329aviname=answer{1};
4330fps=str2double(answer{2});
4331% check for existing file with output name aviname
4332if exist(aviname,'file')
4333    backup=aviname;
4334    testexist=2;
4335    while testexist==2
4336        backup=[backup '~'];
4337        testexist=exist(backup,'file');     
4338    end
4339    [success,message]=copyfile(aviname,backup);%make backup of the existing file
4340    if isequal(success,1)
4341        delete(aviname)%delete existing file
4342    else
4343        msgbox_uvmat('ERROR',message)
4344        return
4345    end
4346end
4347%create avi open
4348aviobj=avifile(aviname,'Compression','None','fps',fps);
4349
4350%display first view for tests
4351newfig=figure;
4352newaxes=copyobj(handles.axes3,newfig);%new plotting axes in the new figure
4353set(newaxes,'Tag','movieaxes')
4354nbpix=[512 384]*str2double(answer{3});
4355set(gcf,'Position',[1 1 nbpix])% resolution XVGA
4356set(newaxes,'Position',eval(answer{4}));
4357map=colormap(handles.axes3);
4358colormap(map);%transmit the current colormap to the zoom fig
4359msgbox_uvmat('INPUT_Y-N',{['adjust figure ' num2str(newfig) ' with its matlab edit menu '] ;...
4360        ['then press OK to get the avi movie as a copy of figure ' num2str(newfig) ' display']});
4361UvData.plotaxes=newaxes;% the axis in the new figure becomes the current main plotting axes
4362set(huvmat,'UserData',UvData);
4363increment=str2num(get(handles.increment_scan,'String')); %get the field increment d
4364set(handles.STOP,'Visible','on')
4365set(handles.speed,'Visible','on')
4366set(handles.speed_txt,'Visible','on')
4367set(handles.Movie,'BusyAction','queue')
4368
4369%imin=str2double(get(handles.i1,'String'));
4370imax=str2double(answer{5});
4371% if isfield(UvData,'Time')
4372htitle=get(newaxes,'Title');
4373xlim=get(newaxes,'XLim');
4374ylim=get(newaxes,'YLim');
4375set(htitle,'Position',[xlim(2)+0.07*(xlim(2)-xlim(1)) ylim(2)-0.05*(ylim(2)-ylim(1)) 0])
4376time_str=get(handles.abs_time,'String');
4377set(htitle,'String',['t=' time_str])
4378set(handles.speed,'Value',1)
4379for i=1:imax
4380    if get(handles.speed,'Value')~=0 && isequal(get(handles.MenuExportMovie,'BusyAction'),'queue') % enable STOP command
4381            runpm(hObject,eventdata,handles,increment)% run plus
4382            drawnow
4383            time_str=get(handles.abs_time,'String');
4384            if ishandle(htitle)
4385             set(htitle,'String',['t=' time_str])
4386            end
4387            mov=getframe(newfig);
4388            aviobj=addframe(aviobj,mov);
4389    end
4390end
4391aviobj=close(aviobj);
4392UvData=rmfield(UvData,'plotaxes');
4393%UvData.Object{1}.plotaxes=handles.axes3;
4394set(huvmat,'UserData',UvData);
4395msgbox_uvmat('CONFIRMATION',{['movie ' aviname ' created '];['with ' num2str(imax) ' frames']})
4396
4397
4398%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4399% Projection Objects Menu Callbacks
4400%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4401
4402% -----------------------------------------------------------------------
4403function Menupoints_Callback(hObject, eventdata, handles)
4404%------------------------------------------------------------------------
4405data.Type='points';
4406data.ProjMode='projection';%default
4407data.ProjModeMenu={};% do not restrict ProjMode menus
4408create_object(data,handles)
4409
4410% -----------------------------------------------------------------------
4411function Menuline_Callback(hObject, eventdata, handles)
4412%------------------------------------------------------------------------
4413data.Type='line';
4414data.ProjMode='projection';%default
4415data.ProjModeMenu={};% do not restrict ProjMode menus
4416create_object(data,handles)
4417
4418%------------------------------------------------------------------------
4419function Menupolyline_Callback(hObject, eventdata, handles)
4420%------------------------------------------------------------------------
4421data.Type='polyline';
4422data.ProjMode='projection';%default
4423data.ProjModeMenu={};% do not restrict ProjMode menus
4424create_object(data,handles)
4425
4426%------------------------------------------------------------------------
4427function Menupolygon_Callback(hObject, eventdata, handles)
4428%------------------------------------------------------------------------
4429data.Type='polygon';
4430data.ProjMode='inside';%default
4431data.ProjModeMenu={};% do not restrict ProjMode menus
4432create_object(data,handles)
4433
4434%------------------------------------------------------------------------
4435function Menurectangle_Callback(hObject, eventdata, handles)
4436%------------------------------------------------------------------------
4437data.Type='rectangle';
4438data.ProjMode='inside';%default
4439data.ProjModeMenu={};% do not restrict ProjMode menus
4440create_object(data,handles)
4441
4442%------------------------------------------------------------------------
4443function Menuellipse_Callback(hObject, eventdata, handles)
4444%------------------------------------------------------------------------
4445data.Type='ellipse';
4446data.ProjMode='inside';%default
4447data.ProjModeMenu={};% do not restrict ProjMode menus
4448create_object(data,handles)
4449
4450%------------------------------------------------------------------------
4451function MenuMaskObject_Callback(hObject, eventdata, handles)
4452%------------------------------------------------------------------------
4453data.Type='polygon';
4454data.TypeMenu={'polygon'};
4455data.ProjMode='mask_inside';%default
4456data.ProjModeMenu={'mask_inside';'mask_outside'};
4457create_object(data,handles)
4458
4459%------------------------------------------------------------------------
4460function Menuplane_Callback(hObject, eventdata, handles)
4461%------------------------------------------------------------------------
4462data.Type='plane';
4463data.ProjMode='projection';%default
4464data.ProjModeMenu={};% do not restrict ProjMode menus
4465create_object(data,handles)
4466
4467%------------------------------------------------------------------------
4468function Menuvolume_Callback(hObject, eventdata, handles)
4469%------------------------------------------------------------------------
4470data.Type='volume';
4471data.ProjMode='interp';%default
4472data.ProjModeMenu={};
4473% set(handles.create,'Visible','on')
4474% set(handles.create,'Value',1)
4475% VOLUME_Callback(hObject,eventdata,handles)data.ProjModeMenu={};
4476create_object(data,handles)
4477
4478%------------------------------------------------------------------------
4479% --- generic function used for the creation of a projection object
4480function create_object(data,handles)
4481%------------------------------------------------------------------------
4482% desactivate geometric calibration if opened
4483hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4484if ishandle(hgeometry_calib)
4485    hhgeometry_calib=guidata(hgeometry_calib);
4486    set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4487    set(hhgeometry_calib.edit_append,'BackgroundColor',[0.7 0.7 0.7])
4488end
4489set(handles.edit_object,'Value',0); %suppress the object edit mode
4490set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4491ListObject=get(handles.ListObject,'String');
4492if ~strcmp(ListObject{end},'')
4493    ListObject=[ListObject;{''}]; %append a blank to the list (if nort already done) to indicate the creation of a new object
4494    set(handles.ListObject,'String',ListObject)
4495end
4496IndexObj=length(ListObject);
4497set(handles.ListObject,'Value',IndexObj)
4498UvData=get(handles.uvmat,'UserData');
4499UvData.Object{IndexObj}=[]; %create a new empty object
4500UvData.Object{IndexObj}.DisplayHandle.uvmat=handles.axes3; % axes for plot_object
4501UvData.Object{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4502data.Name=data.Type;% default name=type
4503data.Coord=[0 0]; %default
4504if isfield(UvData,'Field')
4505    Field=UvData.Field;
4506    if isfield(UvData.Field,'Mesh')&&~isempty(UvData.Field.Mesh)
4507        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4508        if strcmp(data.Type,'line')||strcmp(data.Type,'polyline')||strcmp(data.Type,'points')
4509            data.RangeY=UvData.Field.Mesh;
4510        else
4511            data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4512        end
4513        data.DX=UvData.Field.Mesh;
4514        data.DY=UvData.Field.Mesh;
4515    end
4516    if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4517         data.Coord=[0 0 0]; %default
4518    end
4519    if isfield(Field,'CoordUnit')
4520        data.CoordUnit=Field.CoordUnit;
4521    end
4522end
4523if ishandle(handles.UVMAT_title)
4524    delete(handles.UVMAT_title)%delete the initial display of uvmat if no field has been entered
4525end
4526hset_object=set_object(data,handles);% call the set_object interface
4527hhset_object=guidata(hset_object);
4528hchild=get(hset_object,'children');
4529set(hchild,'enable','on')
4530set(handles.uvmat,'UserData',UvData)
4531set(handles.CheckZoom,'Value',0) %desactivate the zoom for object creation by the mouse
4532CheckZoom_Callback(handles.uvmat, [], handles)
4533set(handles.delete_object,'Visible','on')
4534
4535%------------------------------------------------------------------------
4536function MenuBrowseObject_Callback(hObject, eventdata, handles)
4537%------------------------------------------------------------------------
4538%get the object file
4539[FileName, PathName, filterindex] = uigetfile( ...
4540       {'*.xml;*.mat', ' (*.xml,*.mat)';
4541       '*.xml',  '.xml files '; ...
4542        '*.mat',  '.mat matlab files '}, ...
4543        'Pick an xml Object file',get(handles.RootPath,'String'));
4544fileinput=[PathName FileName];%complete file name
4545sizf=size(fileinput);
4546if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
4547
4548%read the file
4549[data,heading]=xml2struct(fileinput);
4550if ~strcmp(heading,'ProjObject')
4551    msgbox_uvmat('WARNING','The xml file does not have the heading ProjObject for projection objects')
4552end
4553[tild,data.Name]=fileparts(FileName);% object name set as file name
4554ListObject=get(handles.ListObject,'String');
4555if ~strcmp(ListObject{end},'')
4556    ListObject=[ListObject;{''}]; %append a blank to the list (if not already done) to indicate the creation of a new object
4557    set(handles.ListObject,'String',ListObject)
4558end
4559IndexObj=length(ListObject);
4560
4561UvData=get(handles.uvmat,'UserData');
4562UvData.Object{IndexObj}=[]; %create a new empty object
4563UvData.Object{IndexObj}.DisplayHandle.uvmat=[]; %no plot handle before plot_field operation
4564UvData.Object{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4565set(handles.uvmat,'UserData',UvData)
4566set(handles.ListObject,'Value',IndexObj)
4567hset_object=set_object(data);% call the set_object interface
4568set(get(hset_object,'children'),'enable','on')% enable edit action on elements on GUI set_object
4569set(handles.edit_object,'Value',0); %suppress the object edit mode
4570set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4571set(handles.delete_object,'Visible','on')
4572
4573
4574%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4575% MenuEdit Callbacks
4576%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4577%------------------------------------------------------------------------
4578function MenuEditObject_Callback(hObject, eventdata, handles)
4579%------------------------------------------------------------------------
4580set(handles.edit_object,'Value',1)
4581edit_Callback(hObject, eventdata, handles)
4582
4583%------------------------------------------------------------------------
4584function MenuEditVectors_Callback(hObject, eventdata, handles)
4585%------------------------------------------------------------------------
4586set(handles.edit_vect,'Visible','on')
4587set(handles.edit_vect,'Value',1)
4588edit_vect_Callback(hObject, eventdata, handles)
4589
4590%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4591% MenuTools Callbacks
4592%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4593%------------------------------------------------------------------------
4594function MenuCalib_Callback(hObject, eventdata, handles)
4595%------------------------------------------------------------------------
4596
4597UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4598
4599%suppress competing options
4600set(handles.CheckZoom,'Value',0)
4601set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
4602set(handles.ListObject,'Value',1)     
4603% initiate display of GUI geometry_calib
4604data=[]; %default
4605if isfield(UvData,'CoordType')
4606    data.CoordType=UvData.CoordType;
4607end
4608pos=get(handles.uvmat,'Position');
4609pos(1)=pos(1)+pos(3)-0.311+0.04; %0.311= width of the geometry_calib interface (units relative to the srcreen)
4610pos(2)=pos(2)-0.02;
4611[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4612FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4613set(handles.view_xml,'Backgroundcolor',[1 1 0])%indicate the reading of the current xml file by geometry_calib
4614if isfield(UvData.OpenParam,'CalOrigin')
4615    pos_uvmat=get(handles.uvmat,'Position');
4616    pos_cal(1)=pos_uvmat(1)+UvData.OpenParam.CalOrigin(1)*pos_uvmat(3);
4617    pos_cal(2)=pos_uvmat(2)+UvData.OpenParam.CalOrigin(2)*pos_uvmat(4);
4618    pos_cal(3:4)=UvData.OpenParam.CalSize .* pos_uvmat(3:4);
4619end
4620geometry_calib(FileName,pos_cal);% call the geometry_calib interface   
4621set(handles.view_xml,'Backgroundcolor',[1 1 1])%indicate the end of reading of the current xml file by geometry_calib
4622set(handles.MenuCalib,'checked','on')% indicate that MenuCalib is activated, test used by mouse action
4623
4624%------------------------------------------------------------------------
4625function MenuMask_Callback(hObject, eventdata, handles)
4626%------------------------------------------------------------------------
4627UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4628ListObj=UvData.Object;
4629select=zeros(1,numel(ListObj));
4630for iobj=1:numel(ListObj);
4631    if strcmp(ListObj{iobj}.ProjMode,'mask_inside')||strcmp(ListObj{iobj}.ProjMode,'mask_outside')
4632        select(iobj)=1;
4633    end
4634end
4635val=find(select);
4636if isempty(val)
4637    msgbox_uvmat('ERROR','polygons must be first created by Projection object/mask polygon in the menu bar');
4638    return
4639else
4640%     set(handles.ListObject,'Max',2);%allow multiple selection
4641    set(handles.ListObject,'Value',val);
4642    flag=1;
4643    npx=size(UvData.Field.A,2);
4644    npy=size(UvData.Field.A,1);
4645    xi=0.5:npx-0.5;
4646    yi=0.5:npy-0.5;
4647    [Xi,Yi]=meshgrid(xi,yi);
4648    if isfield(UvData,'Object')
4649        for iobj=1:length(UvData.Object)
4650            ObjectData=UvData.Object{iobj};
4651            if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
4652                flagobj=1;
4653                testphys=0; %coordinates in pixels by default
4654                if isfield(ObjectData,'CoordUnit') && ~isequal(ObjectData.CoordUnit,'pixel')
4655                    if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
4656                        Calib=UvData.XmlData{1}.GeometryCalib;
4657                        testphys=1;
4658                    end
4659                end
4660                if isfield(ObjectData,'Coord')&& isfield(ObjectData,'Type')
4661                    if isequal(ObjectData.Type,'polygon')
4662                        X=ObjectData.Coord(:,1);
4663                        Y=ObjectData.Coord(:,2);
4664                        if testphys
4665                            [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
4666                        end
4667                        flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside
4668                    elseif isequal(ObjectData.Type,'ellipse')
4669                        if testphys
4670                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4671                        end
4672                        RangeX=max(ObjectData.RangeX);
4673                        RangeY=max(ObjectData.RangeY);
4674                        X2Max=RangeX*RangeX;
4675                        Y2Max=RangeY*RangeY;
4676                        distX=(Xi-ObjectData.Coord(1,1));
4677                        distY=(Yi-ObjectData.Coord(1,2));
4678                        flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
4679                    elseif isequal(ObjectData.Type,'rectangle')
4680                        if testphys
4681                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4682                        end
4683                        distX=abs(Xi-ObjectData.Coord(1,1));
4684                        distY=abs(Yi-ObjectData.Coord(1,2));
4685                        flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
4686                    end
4687                    if isequal(ObjectData.ProjMode,'mask_outside')
4688                        flagobj=~flagobj;
4689                    end
4690                    flag=flag & flagobj;
4691                end
4692            end
4693        end
4694    end
4695    %mask name
4696    RootPath=get(handles.RootPath,'String');
4697    SubDir=get(handles.SubDir,'String');
4698    RootFile=get(handles.RootFile,'String');
4699    if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
4700        RootFile(1)=[];
4701    end
4702   % filebase=fullfile(RootPath,RootFile);
4703    list=get(handles.masklevel,'String');
4704    masknumber=num2str(length(list));
4705    maskindex=get(handles.masklevel,'Value');
4706   % mask_name=fullfile_uvmat(RootPath,'',[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
4707    mask_name=fullfile_uvmat(RootPath,[SubDir '.mask'],'mask','.png','_1',maskindex);
4708    imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
4709    imflag=flipdim(imflag,1);
4710
4711    %display the mask
4712    hfigmask=figure;
4713    set(hfigmask,'Name','mask image')
4714    vec=linspace(0,1,256);%define a linear greyscale colormap
4715    map=[vec' vec' vec'];
4716    colormap(map)
4717    image(imflag);
4718    answer=msgbox_uvmat('INPUT_TXT','mask file name:', mask_name);
4719    if ~strcmp(answer,'Cancel')
4720        mask_dir=fileparts(answer);
4721        if ~exist(mask_dir,'dir')
4722            [xx,msg1]=mkdir(mask_dir);
4723            if ~strcmp(msg1,'')
4724                errormsg=['cannot create ' mask_dir ': ' msg1];%error message for directory creation
4725                return
4726            end
4727        end
4728        imwrite(imflag,answer,'BitDepth',8);
4729    end
4730    set(handles.ListObject,'Value',1)
4731end
4732
4733%------------------------------------------------------------------------
4734%-- open the GUI set_grid.fig to create grid
4735function MenuGrid_Callback(hObject, eventdata, handles)
4736%------------------------------------------------------------------------
4737%suppress the other options if grid is chosen
4738set(handles.edit_vect,'Value',0)
4739edit_vect_Callback(hObject, eventdata, handles)
4740set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
4741set(handles.ListObject,'Value',1)     
4742
4743%prepare display of the set_grid GUI
4744[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4745FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4746CoordList=get(handles.transform_fct,'String');
4747val=get(handles.transform_fct,'Value');
4748set_grid(FileName,CoordList{val});% call the set_object interface
4749
4750
4751%------------------------------------------------------------------------
4752function MenuRuler_Callback(hObject, eventdata, handles)
4753%------------------------------------------------------------------------
4754set(handles.CheckZoom,'Value',0)
4755CheckZoom_Callback(handles.uvmat, [], handles)
4756set(handles.MenuRuler,'checked','on')
4757UvData=get(handles.uvmat,'UserData');
4758UvData.MouseAction='ruler';
4759set(handles.uvmat,'UserData',UvData);
4760
4761%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4762% MenuRun Callbacks
4763%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4764
4765%------------------------------------------------------------------------
4766% open the GUI 'series'
4767function MenuSeries_Callback(hObject, eventdata, handles)
4768%------------------------------------------------------------------------
4769series; %first display of the GUI to fill waiting time
4770[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4771param.FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4772if isequal(get(handles.SubField,'Value'),1)
4773    [RootPath_1,SubDir_1,RootFile_1,FileIndices_1,FileExt_1]=read_file_boxes_1(handles);
4774    FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndices_1 FileExt_1];
4775    if ~isequal(FileName_1,param.FileName)
4776        param.FileName_1=FileName_1;
4777    end
4778end
4779param.NomType=get(handles.NomType,'String');
4780param.NomType_1=get(handles.NomType_1,'String');
4781param.CheckFixPair=get(handles.CheckFixPair,'Value');
4782huvmat=get(handles.MenuSeries,'parent');
4783UvData=get(huvmat,'UserData');
4784if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'Time')
4785    param.Time=UvData.XmlData{1}.Time;
4786end
4787if isequal(get(handles.scan_i,'Value'),1)
4788    param.incr_i=str2num(get(handles.increment_scan,'String'));
4789elseif isequal(get(handles.scan_j,'Value'),1)
4790    param.incr_j=str2num(get(handles.increment_scan,'String'));
4791end
4792param.list_fields=get(handles.Fields,'String');% list menu fields
4793param.list_fields(1)=[]; %suppress  'image' option
4794param.index_fields=get(handles.Fields,'Value');% selected string index
4795if param.index_fields>1
4796    param.index_fields=param.index_fields-1;
4797end
4798param.list_fields_1=get(handles.Fields_1,'String');% list menu fields
4799param.list_fields_1(1)=[]; %suppress  'image' option
4800param.index_fields_1=get(handles.Fields_1,'Value')-1;% selected string index
4801if param.index_fields_1>1
4802    param.index_fields_1=param.index_fields_1-1;
4803end
4804param.menu_coord_str=get(handles.transform_fct,'String');
4805param.menu_coord_val=get(handles.transform_fct,'Value');
4806series(param); %run the series interface
4807
4808%------------------------------------------------------------------------
4809% -- open the GUI civ.fig for PIV
4810function MenuPIV_Callback(hObject, eventdata, handles)
4811%------------------------------------------------------------------------
4812 [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
4813 FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
4814civ(FileName);% interface de civ(not in the uvmat file)
4815
4816% --------------------------------------------------------------------
4817function MenuHelp_Callback(hObject, eventdata, handles)
4818% --------------------------------------------------------------------
4819path_to_uvmat=which ('uvmat');% check the path of uvmat
4820pathelp=fileparts(path_to_uvmat);
4821helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
4822if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
4823else
4824    addpath (fullfile(pathelp,'uvmat_doc'))
4825    web(helpfile);
4826end
Note: See TracBrowser for help on using the repository browser.