source: trunk/src/uvmat.m @ 689

Last change on this file since 689 was 689, checked in by sommeria, 11 years ago

set unused uicontrol to invisible in uvmat

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