source: trunk/src/uvmat.m @ 413

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

various bugs corrected and improvement in civ1_TEST

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