source: trunk/src/uvmat.m @ 476

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

bugs corrected +
* filter parameter multiplied by 1000 in filter_tps*

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