source: trunk/src/uvmat.m @ 450

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

various bugs repaired

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