source: trunk/src/uvmat.m @ 512

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

various cleaning

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