source: trunk/src/uvmat.m @ 644

Last change on this file since 644 was 644, checked in by sommeria, 8 years ago

various improvements: resize GUI uvmat, projection on lines

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