source: trunk/src/uvmat.m @ 686

Last change on this file since 686 was 686, checked in by sommeria, 7 years ago

further cleaning

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