source: trunk/src/uvmat.m @ 429

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

improvements in object drawing and projection on points

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