source: trunk/src/uvmat.m @ 427

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

merge_proj corrected to project simulataneously velocity, vort, div...
Time reintroduced correctly
bug corrections for objects

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