source: trunk/src/uvmat.m @ 332

Last change on this file since 332 was 332, checked in by sommeria, 12 years ago

NomType? changed from _i1-i2 ... to _1-2 ... (bugs to be expected!)
bug corrected in geometry_calib
series changed by introducing a from FileIndices?, introduction of find_file_series to detect the file series corresponding to an input file

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