source: trunk/src/uvmat.m @ 517

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

various bugs corrected. get_field now used in a passive way from uvmat: variable names are transferred from get_field to uvmat.

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