source: trunk/src/uvmat.m @ 426

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

compiled matlab civ introduced in Batch mode,
minor bugs fixed for histogram of velocity

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