source: trunk/src/uvmat.m @ 405

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

many bugs corrected: composition of 2 input fields, arrow colors from different scalar fields...

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