source: trunk/src/uvmat.m @ 784

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

adpat uvmat to reading data from rdvision

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