source: trunk/src/uvmat.m @ 456

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

various bugs corrected

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