source: trunk/src/uvmat.m @ 434

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

corrections in the use of get_field
test_tps introduced, to test thin plate shell functions
tps-eval_dxy corrected (bug on the calculation of the derivatives fixed)

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