source: trunk/src/uvmat.m @ 424

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

improved way of dealing with projection objects

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