source: trunk/src/uvmat.m @ 752

Last change on this file since 752 was 752, checked in by sommeria, 10 years ago

various update

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