source: trunk/src/uvmat.m @ 738

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

various bug resolutions and improvements in particular with geometry_calib. Introduction of a tool set_slices in uvmat.

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