source: trunk/src/uvmat.m @ 735

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

various corrections

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