source: trunk/src/uvmat.m @ 704

Last change on this file since 704 was 704, checked in by sommeria, 10 years ago

test input of uvmat to detect broken links

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