source: trunk/src/uvmat.m @ 542

Last change on this file since 542 was 542, checked in by sommeria, 8 years ago

bugs repaired for mask display in phys coord, display of circles in geometry_calib, introduction of x,y,z initial in proj_field/proj_plane

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