source: trunk/src/uvmat.m @ 528

Last change on this file since 528 was 528, checked in by sommeria, 12 years ago

bugs repaired

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