source: trunk/src/uvmat.m @ 844

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

various bugs repaired

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