source: trunk/src/uvmat.m @ 747

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

adpatations to 3D fields

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