source: trunk/src/uvmat.m @ 841

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

bugs corrected in uvmat: object deletion.
set_slices improved.

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