source: trunk/src/uvmat.m @ 682

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

various bugs repaired

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