source: trunk/src/uvmat.m @ 771

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