source: trunk/src/uvmat.m @ 831

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

movie export improved

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