source: trunk/src/uvmat.m @ 773

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

help web link corrected

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