source: trunk/src/uvmat.m @ 778

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

movie export fixed

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