source: trunk/src/uvmat.m @ 511

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

cleaning of uvmat and related fcts

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