source: trunk/src/uvmat.m @ 772

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

manip corrections and cleaning

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