source: trunk/src/uvmat.m @ 324

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

GUI uvmat modified by introduction of a pannel InputFile?, NomType? now explicitley written in a edit box NomType? on this panel.

File size: 211.3 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,'')&& mmreader.isPlatformSupported()% if the function 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 {'_i_j1-j2','#_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);
1780filebase=InputFile.RootPath; %default
1781if ~isempty(InputFile.SubDir)
1782    InputFile.SubDir=regexprep(InputFile.SubDir,'/|\','');
1783%    FileName=fullfile(InputFile.RootPath,InputFile.SubDir);
1784end
1785if ~isempty(InputFile.RootFile)
1786    InputFile.RootFile=regexprep(InputFile.RootFile,'/|\','');
1787    filebase=fullfile(filebase,InputFile.RootFile);
1788end
1789FileExt=InputFile.FileExt;
1790subdir=InputFile.SubDir;
1791% [FileName,RootPath,filebase,FileIndices,FileExt,subdir]=read_file_boxes(handles);
1792NomType=get(handles.NomType,'String');
1793% NomType=get(handles.FileIndex,'UserData');
1794i1=stra2num(get(handles.i1,'String'));%read the field indices (for movie, it is not given by the file name)
1795i2=stra2num(get(handles.i2,'String'));
1796j1=stra2num(get(handles.j1,'String'));
1797j2=stra2num(get(handles.j2,'String'));
1798sub_value= get(handles.SubField,'Value');
1799if sub_value % a second input file has been entered
1800    [FileName_1,RootPath_1,filebase_1,FileIndices_1,FileExt_1,SubDir_1]=read_file_boxes_1(handles);
1801    [pp,ff,i1_1_str,i2_1_str,j1_1_str,j2_1_str]=name2display(FileIndices_1);
1802    i1_1=stra2num(i1_1_str);%current set of indices for the second field (may be set different than the main indices)
1803    i2_1=stra2num(i2_1_str);
1804    j1_1=stra2num(j1_1_str);
1805    j2_1=stra2num(j2_1_str);
1806    NomType_1=get(handles.NomType_1,'String');
1807%     NomType_1=get(handles.FileIndex_1,'UserData');
1808else
1809    filename_1=[];
1810end   
1811comp_input=get(handles.fix_pair,'Value');
1812
1813%% increment (or decrement) the field indices and update the input filename(s)
1814if get(handles.scan_i,'Value')==1% case of scanning along index i   
1815     i1=i1+increment;
1816     i2=i2+increment;
1817     [filename,i1,j1,i2,j2]=name_generator(filebase,i1,j1,FileExt,NomType,comp_input,i2,j2,subdir);
1818     if sub_value% set the second field name and indices
1819        i1_1=i1_1+increment;
1820        i2_1=i2_1+increment;
1821        filename_1=name_generator(filebase_1,i1_1,j1_1,FileExt_1,NomType_1,1,i2_1,j2_1,SubDir_1);
1822     end   
1823else % case of scanning along index j (burst numbers)
1824    j1=j1+increment;
1825    j2=j2+increment;
1826    [filename,i1,j1,i2,j2]=name_generator(filebase,i1,j1,FileExt,NomType,comp_input,i2,j2,subdir);
1827    if sub_value
1828        j1_1=j1_1+increment;
1829        j2_1=j2_1+increment;
1830        filename_1=name_generator(filebase_1,i1_1,j1_1,FileExt_1,NomType_1,1,i2_1,j2_1,SubDir_1);
1831    end   
1832end
1833
1834%% refresh plots
1835errormsg=refresh_field(handles,filename,filename_1,i1,i2,j1,j2);
1836
1837%% update the index counters if the index move is successfull
1838if isempty(errormsg)
1839    set(handles.i1,'String',num2stra(i1,NomType,1));
1840    if isequal(i2,i1)
1841        set(handles.i2,'String','');
1842    else
1843        set(handles.i2,'String',num2stra(i2,NomType,1));
1844    end
1845    set(handles.j1,'String',num2stra(j1,NomType,2));
1846    if isequal(j2,j1)
1847        set(handles.j2,'String','');
1848    else
1849        set(handles.j2,'String',num2stra(j2,NomType,2));
1850    end
1851    [indices]=name_generator('',i1,j1,'',NomType,1,i2,j2,'');
1852    set(handles.FileIndex,'String',indices);
1853    if ~isempty(filename_1)
1854        indices_1=name_generator('',i1_1,j1_1,'',NomType_1,1,i2_1,j2_1,'');
1855        set(handles.FileIndex_1,'String',indices_1);
1856    end
1857    if isequal(movie_status,1)
1858        set(handles.movie_pair,'Value',1)
1859        movie_pair_Callback(hObject, eventdata, handles); %reactivate moviepair if it was activated
1860    end
1861end
1862
1863%------------------------------------------------------------------------
1864% --- Executes on button press in movie_pair: create an alternating movie with two view
1865function movie_pair_Callback(hObject, eventdata, handles)
1866%------------------------------------------------------------------------
1867status=get(handles.movie_pair,'value');
1868if isequal(status,0)
1869    set(handles.movie_pair,'BusyAction','Cancel')%stop movie pair if button is 'off'
1870    set(handles.i2,'String','')
1871    set(handles.j2,'String','')
1872    return
1873else
1874    set(handles.movie_pair,'BusyAction','queue')
1875end
1876%initialisation
1877set(handles.movie_pair,'BackgroundColor',[1 1 0])%paint the command button in yellow
1878drawnow
1879list_fields=get(handles.Fields,'String');% list menu fields
1880index_fields=get(handles.Fields,'Value');% selected string index
1881FieldName=list_fields{index_fields}; % selected field
1882UvData=get(handles.uvmat,'UserData');
1883if isequal(FieldName,'image')
1884    test_1=0;
1885    [ff,rr,filebase,xx,Ext,SubDir]=read_file_boxes(handles);
1886    NomType=get(handles.NomType,'String');
1887%     NomType=get(handles.FileIndex,'UserData');
1888else
1889    list_fields=get(handles.Fields_1,'String');% list menu fields
1890    index_fields=get(handles.Fields_1,'Value');% selected string index
1891    FieldName=list_fields{index_fields}; % selected field
1892    if isequal(FieldName,'image')
1893        test_1=1;
1894        [ff,rr,filebase,xx,Ext,SubDir]=read_file_boxes_1(handles);
1895        NomType=get(handles.NomType_1,'String');
1896%         NomType=get(handles.FileIndex_1,'UserData');
1897    else
1898        msgbox_uvmat('ERROR','an image or movie must be first introduced as input')
1899        set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1900        return
1901    end
1902end
1903
1904num_i1=str2double(get(handles.i1,'String'));
1905num_j1=stra2num(get(handles.j1,'String'));
1906num_i2=str2double(get(handles.i2,'String'));
1907num_j2=stra2num(get(handles.j2,'String'));
1908if isnan(num_j2)
1909    if isempty(num_i2)   
1910        msgbox_uvmat('ERROR', 'a second image index i2 or j2 is needed to show the pair as a movie')
1911        set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1912        return
1913    else
1914        num_j2=num_j1;%repeat the index i1 by default
1915    end
1916end
1917if isnan(num_i2)
1918    num_i2=num_i1;%repeat the index i1 by default
1919end
1920imaname_1=name_generator(filebase,num_i2,num_j2,Ext,NomType);
1921if ~exist(imaname_1,'file')
1922      msgbox_uvmat('ERROR',['second input open (-)  ' imaname_1 ' not found']);
1923      set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1924      return
1925end
1926
1927%read the second image
1928Field.AName='image';
1929if test_1
1930    Field_a=UvData.Field_1;
1931else
1932    Field_a=UvData.Field;
1933end
1934Field_b.AX=Field_a.AX;
1935Field_b.AY=Field_a.AY;
1936% z index
1937nbslice=str2double(get(handles.nb_slice,'String'));
1938if ~isempty(nbslice)
1939    Field_b.ZIndex=mod(num_i2-1,nbslice)+1;
1940end
1941Field_b.CoordUnit='pixel';
1942%determine the input file type
1943if (test_1 && isfield(UvData,'MovieObject_1'))||(~test_1 && isfield(UvData,'MovieObject'))
1944    FileType='movie';
1945elseif isequal(lower(Ext),'.avi')
1946    FileType='avi';
1947elseif isequal(lower(Ext),'.vol')
1948    FileType='vol';
1949else
1950   form=imformats(Ext(2:end));
1951   if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
1952       if isequal(NomType,'*');
1953           FileType='multimage';
1954       else
1955           FileType='image';
1956       end
1957   end
1958end
1959switch FileType
1960        case 'movie'
1961            if test_1
1962                Field_b.A=read(UvData.MovieObject_1,num_i2);
1963            else
1964                Field_b.A=read(UvData.MovieObject,num_i2);
1965            end
1966        case 'avi'
1967            mov=aviread(imaname_1,num_i2);
1968            Field_b.A=frame2im(mov(1));
1969        case 'vol'
1970            Field_b.A=imread(imaname_1);
1971        case 'multimage'
1972            Field_b.A=imread(imaname_1,num_i2);
1973        case 'image'
1974            Field_b.A=imread(imaname_1);
1975end
1976if get(handles.slices,'Value')
1977    Field.ZIndex=str2double(get(handles.z_index,'String'));
1978end
1979
1980%px to phys or other transform on field
1981menu_transform=get(handles.transform_fct,'String');
1982choice_value=get(handles.transform_fct,'Value');
1983transform_name=menu_transform{choice_value};%name of the transform fct  given by the menu 'transform_fct'
1984transform_list=get(handles.transform_fct,'UserData');
1985transform=transform_list{choice_value};
1986if  ~isequal(transform_name,'') && ~isequal(transform_name,'px')
1987    if test_1 && isfield(UvData,'XmlData_1') && isfield(UvData.XmlData_1,'GeometryCalib')%use geometry calib recorded from the ImaDoc xml file as first priority
1988        Field_a=transform(Field_a,UvData.XmlData_1);%the first field has been stored without transform
1989        Field_b=transform(Field_b,UvData.XmlData_1);
1990    elseif ~test_1 && isfield(UvData,'XmlData') && isfield(UvData.XmlData,'GeometryCalib')%use geometry calib
1991        Field_b=transform(Field_b,UvData.XmlData);
1992    end
1993end
1994
1995 % make movie until movie speed is set to 0 or STOP is activated
1996hima=findobj(handles.axes3,'Tag','ima');% %handles.axes3 =main plotting window (A GENERALISER)
1997set(handles.STOP,'Visible','on')
1998set(handles.speed,'Visible','on')
1999set(handles.speed_txt,'Visible','on')
2000while get(handles.speed,'Value')~=0 && isequal(get(handles.movie_pair,'BusyAction'),'queue')%isequal(get(handles.run0,'BusyAction'),'queue'); % enable STOP command
2001    % read and plot the series of images in non erase mode
2002    set(hima,'CData',Field_b.A);
2003    pause(1.02-get(handles.speed,'Value'));% wait for next image
2004    set(hima,'CData',Field_a.A);
2005    pause(1.02-get(handles.speed,'Value'));% wait for next image
2006end
2007set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
2008
2009%------------------------------------------------------------------------
2010% --- Executes on button press in run0.
2011function run0_Callback(hObject, eventdata, handles)
2012%------------------------------------------------------------------------
2013set(handles.run0,'BackgroundColor',[1 1 0])%paint the command button in yellow
2014drawnow
2015filename=read_file_boxes(handles);
2016
2017filename_1=[];%default
2018if get(handles.SubField,'Value')
2019    filename_1=read_file_boxes_1(handles);
2020end
2021num_i1=stra2num(get(handles.i1,'String'));
2022num_i2=stra2num(get(handles.i2,'String'));
2023num_j1=stra2num(get(handles.j1,'String'));
2024num_j2=stra2num(get(handles.j2,'String'));
2025
2026errormsg=refresh_field(handles,filename,filename_1,num_i1,num_i2,num_j1,num_j2);
2027
2028if ~isempty(errormsg)
2029      msgbox_uvmat('ERROR',errormsg);
2030else
2031    set(handles.i1,'BackgroundColor',[1 1 1])
2032    set(handles.i2,'BackgroundColor',[1 1 1])
2033    set(handles.j1,'BackgroundColor',[1 1 1])
2034    set(handles.j2,'BackgroundColor',[1 1 1])
2035    set(handles.FileIndex,'BackgroundColor',[1 1 1])
2036    set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
2037end   
2038set(handles.run0,'BackgroundColor',[1 0 0])
2039
2040
2041%------------------------------------------------------------------------
2042% --- read the input files and refresh all the plots, including projection.
2043% OUTPUT:
2044%  errormsg: error message char string  =[] by default
2045% INPUT:
2046% filename: first input file (=[] in the absence of input file)
2047% filename_1: second input file (=[] in the asbsenc of secodn input file)
2048% num_i1,num_i2,num_j1,num_j2; frame indices
2049% Field: structure describing an optional input field (then replace the input file)
2050function errormsg=refresh_field(handles,filename,filename_1,num_i1,num_i2,num_j1,num_j2,Field)
2051%------------------------------------------------------------------------
2052
2053%% initialisation
2054abstime=[];
2055abstime_1=[];
2056dt=[];
2057if ~exist('Field','var')
2058    Field={};
2059end
2060UvData=get(handles.uvmat,'UserData');
2061if ishandle(handles.UVMAT_title) %remove title panel on uvmat
2062    delete(handles.UVMAT_title)
2063end
2064
2065%% determine the main input file information for action
2066FileType=[];%default
2067if ~exist(filename,'file')
2068    errormsg=['input file ' filename ' does not exist'];
2069    return
2070end
2071NomType=get(handles.NomType,'String');
2072% NomType=get(handles.FileIndex,'UserData');
2073%update the z position index
2074nbslice_str=get(handles.nb_slice,'String');
2075if isequal(nbslice_str,'volume')%NOT USED
2076    z_index=num_j1;
2077    set(handles.z_index,'String',num2str(z_index))
2078else
2079    nbslice=str2num(nbslice_str);
2080    z_index=mod(num_i1-1,nbslice)+1;
2081    set(handles.z_index,'String',num2str(z_index))
2082end
2083% refresh menu for save_mask if relevant
2084masknumber=get(handles.masklevel,'String');
2085if length(masknumber)>=z_index
2086    set(handles.masklevel,'Value',z_index)
2087end
2088
2089%% read the first input field if a filename has been introduced
2090if ~isempty(filename)
2091    ObjectName=filename;
2092    FieldName=[];%default
2093    VelType=[];%default
2094    Ext=get(handles.FileExt,'String');
2095    if strcmp(Ext,'.nc')||strcmp(Ext,'.cdf')
2096        FileType='netcdf';
2097        list_fields=get(handles.Fields,'String');% list menu fields
2098        index_fields=get(handles.Fields,'Value');% selected string index
2099        FieldName= list_fields{index_fields}; % selected field
2100        if ~strcmp(FieldName,'get_field...')
2101           TestVelType=get(handles.FixVelType,'Value');
2102           if TestVelType
2103               VelType=setfield(handles);% read the velocity type.
2104           end
2105        end
2106        if strcmp(FieldName,'velocity')
2107            list_code=get(handles.ListColorCode,'String');% list menu fields
2108            index_code=get(handles.ListColorCode,'Value');% selected string index
2109            if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2110                list_code=get(handles.ListColorScalar,'String');% list menu fields
2111                index_code=get(handles.ListColorScalar,'Value');% selected string index
2112                ParamIn.ColorVar= list_code{index_code}; % selected field
2113            end
2114        end
2115    elseif isfield(UvData,'MovieObject')
2116        ObjectName=UvData.MovieObject;
2117        FileType='movie';
2118    elseif isequal(lower(Ext),'.avi')
2119        FileType='avi';
2120    elseif isequal(lower(Ext),'.vol')
2121        FileType='vol';
2122        if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2123            ParamIn.Npy=UvData.XmlData.Npy;
2124            ParamIn.Npx=UvData.XmlData.Npx;
2125        else
2126            errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2127            return
2128        end
2129    else
2130       form=imformats(Ext(2:end));
2131       if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2132           if isequal(NomType,'*');
2133               FileType='multimage';
2134           else
2135               FileType='image';
2136           end
2137       end
2138    end
2139    ParamIn.FieldName=FieldName;
2140    ParamIn.VelType=VelType;
2141    ParamIn.GUIName='get_field';
2142    [Field{1},ParamOut,errormsg] = read_field(ObjectName,FileType,ParamIn,num_i1);
2143    if ~isempty(errormsg)
2144        errormsg=['error in reading ' filename ': ' errormsg];
2145        return
2146    end       
2147    if isfield(ParamOut,'Npx')&& isfield(ParamOut,'Npy')
2148        set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2149        set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2150    end
2151    if isfield(ParamOut,'TimeIndex')
2152        set(handles.i1,'String',num2str(ParamOut.TimeIndex))
2153    end
2154    if isfield(ParamOut,'TimeValue')
2155        Field{1}.Time=ParamOut.TimeValue;
2156    end
2157end
2158
2159%% choose a second field filename_1 if defined
2160VelType_1=[];%default
2161FieldName_1=[];
2162ParamOut_1=[];
2163if ~isempty(filename_1)
2164    if ~exist(filename_1,'file')
2165        errormsg=['second file ' filename_1 ' does not exist'];
2166        return
2167    else
2168        Name=filename_1;
2169        FieldName_1=[];%default
2170        VelType_1=[];%default
2171        if strcmp(get(handles.FileExt_1,'Visible'),'on')
2172            Ext_1=get(handles.FileExt_1,'String');
2173        else
2174            Ext_1=get(handles.FileExt,'String');%read the file extension for the first series (case of veltype comparison within a single file)
2175        end
2176        NomType_1=get(handles.NomType_1,'String');
2177%         NomType_1=get(handles.FileIndex_1,'UserData');
2178        if isequal(Ext_1,'.nc')||isequal(Ext_1,'.cdf')
2179            FileType_1='netcdf';
2180        elseif isfield(UvData,'MovieObject_1')
2181            Name=UvData.MovieObject_1;
2182            FileType_1='movie';
2183        elseif isequal(lower(Ext_1),'.avi')
2184            FileType_1='avi';
2185        elseif isequal(lower(Ext_1),'.vol')
2186            FileType_1='vol';
2187            if isfield(UvData.XmlData_1,'Npy') && isfield(UvData.XmlData_1,'Npx')
2188                ParamIn.Npy=UvData.XmlData_1.Npy;
2189                ParamIn.Npx=UvData.XmlData_1.Npx;
2190            else
2191                errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2192                return
2193            end
2194        else
2195           if length(Ext_1)>=2
2196           form=imformats(Ext_1(2:end));
2197           if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2198               if isequal(NomType_1,'*');
2199                   FileType_1='multimage';
2200               else
2201                   FileType_1='image';
2202               end
2203           end
2204           end
2205        end
2206        if strcmp(FileType_1,'netcdf')
2207            list_fields=get(handles.Fields_1,'String');% list menu fields
2208            index_fields=get(handles.Fields_1,'Value');% selected string index
2209            FieldName_1= list_fields{index_fields}; % selected field
2210            if ~isequal(FieldName_1,'get_field...')% read the field names on the interface get_field...
2211                VelType_1='';
2212                if get(handles.FixVelType,'Value')
2213                    VelTypeList=get(handles.VelType_1,'String');
2214                    index=get(handles.VelType_1,'Value');
2215                    VelType_1=VelTypeList{index};
2216                end
2217            end
2218            if strcmp(VelType_1,'*')% free veltype choice
2219                VelType_1=[];
2220            elseif strcmp(VelType_1,'"')% veltype the same as for the first field
2221                if isempty(VelType)
2222                    VelType_1=[];
2223                else
2224                    VelType_1=VelType;
2225                end
2226            end
2227            if strcmp(FieldName_1,'velocity')
2228                list_code=get(handles.ListColorCode,'String');% list menu fields
2229                index_code=get(handles.ListColorCode,'Value');% selected string index
2230                if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2231                    list_code=get(handles.ListColorScalar,'String');% list menu fields
2232                    index_code=get(handles.ListColorScalar,'Value');% selected string index
2233                    ParamIn.ColorVar= list_code{index_code}; % selected field
2234                end
2235            end
2236        end
2237        test_keepdata_1=0;% test for keeping the previous stored data if the input files are unchanged
2238        if ~isequal(NomType_1,'*')%in case of a series of files (not avi movie)
2239            if isfield(UvData,'filename_1')&& isfield(UvData,'VelType_1') && isfield(UvData,'FieldName_1')
2240                test_keepdata_1= strcmp(filename_1,UvData.filename_1) && strcmp(VelType_1,UvData.VelType_1) && strcmp(FieldName_1,UvData.FieldName_1);
2241            end
2242        end
2243        if test_keepdata_1
2244            Field{2}=UvData.Field_1;
2245        else
2246            ParamIn.FieldName=FieldName_1;
2247            ParamIn.VelType=VelType_1;
2248            ParamIn.GUIName='get_field_1';
2249            [Field{2},ParamOut_1,errormsg] = read_field(Name,FileType_1,ParamIn,num_i1);
2250            if ~isempty(errormsg)
2251                errormsg=['error in reading ' FieldName_1 ' in ' filename_1 ': ' errormsg];
2252                return
2253            end
2254            UvData.Field_1=Field{2}; %store the second field for possible use at next RUN
2255        end
2256    end
2257end
2258
2259%% update uvmat interface
2260if isfield(ParamOut,'Npx')
2261    set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2262    set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2263elseif isfield(ParamOut_1,'Npx')
2264    set(handles.num_Npx,'String',num2str(ParamOut_1.Npx));% display image size on the interface
2265    set(handles.num_Npy,'String',num2str(ParamOut_1.Npy));
2266end
2267
2268%% update the display menu for the first velocity type (first menuline)
2269test_veltype=0;
2270if ~isequal(FileType,'netcdf')|| isequal(FieldName,'get_field...')
2271    set(handles.VelType,'Visible','off')
2272else
2273    test_veltype=1;
2274    set(handles.VelType,'Visible','on')
2275    set(handles.VelType_1,'Visible','on')
2276    set(handles.FixVelType,'Visible','on')
2277    menu=set_veltype_display(ParamOut.CivStage);
2278    index_menu=strcmp(ParamOut.VelType,menu);
2279    set(handles.VelType,'Value',find(index_menu,1))
2280    if ~get(handles.SubField,'value')
2281    set(handles.VelType,'String',menu)
2282     set(handles.VelType_1,'Value',1)
2283     set(handles.VelType_1,'String',[{''};menu])
2284    end
2285end
2286field_index=strcmp(ParamOut.FieldName,ParamOut.FieldList);
2287set(handles.Fields,'String',ParamOut.FieldList); %update the field menu
2288set(handles.Fields,'Value',find(field_index,1))
2289
2290%% update the display menu for the second velocity type (second menuline)
2291test_veltype_1=0;
2292if isempty(filename_1)
2293    set(handles.Fields_1,'Value',1); %update the field menu
2294    set(handles.Fields_1,'String',[{''};ParamOut.FieldList]); %update the field menu
2295else
2296    if ~isequal(FileType_1,'netcdf')|| isequal(FieldName_1,'get_field...')
2297        set(handles.VelType_1,'Visible','off')
2298    else
2299        test_veltype_1=1;
2300        set(handles.VelType_1,'Visible','on')
2301        if ~get(handles.FixVelType,'Value')
2302            menu=set_veltype_display(ParamOut_1.CivStage);
2303            index_menu=strcmp(ParamOut_1.VelType,menu);
2304            set(handles.VelType_1,'Value',1+find(index_menu,1))
2305            set(handles.VelType_1,'String',[{''};menu])
2306        end
2307    end
2308end
2309if test_veltype||test_veltype_1
2310     set(handles.FixVelType,'Visible','on')
2311else
2312     set(handles.FixVelType,'Visible','off')
2313end
2314   
2315%% introduce w as background image by default for a new series (only for nbdim=2)
2316if ~isfield(UvData,'NewSeries')
2317    UvData.NewSeries=1;
2318end
2319%put W as background image by default if NbDim=2:
2320if  UvData.NewSeries && isequal(get(handles.SubField,'Value'),0) && isfield(Field{1},'W') && ~isempty(Field{1}.W) && ~isequal(Field{1}.NbDim,3);
2321        set(handles.SubField,'Value',1);
2322        %menu=update_menu(handles.Fields_1,'w');%update the menu for the background scalar nd set the choice to 'w'
2323        set(handles.RootPath_1,'String','"')
2324        set(handles.RootFile_1,'String','"')
2325        set(handles.SubDir_1,'String','"');
2326        [indices]=name_generator('',num_i1,num_j1,'',NomType,1,num_i2,num_j2,'');
2327        set(handles.FileIndex_1,'String',indices)
2328        set(handles.FileExt_1,'String','"');
2329        set(handles.Fields_1,'Visible','on');
2330        set(handles.Fields_1,'Visible','on');
2331        set(handles.RootPath_1,'Visible','on')
2332        set(handles.RootFile_1,'Visible','on')
2333        set(handles.SubDir_1,'Visible','on');
2334        set(handles.FileIndex_1,'Visible','on');
2335        set(handles.FileExt_1,'Visible','on');
2336        set(handles.Fields_1,'Visible','on');
2337        Field{1}.AName='w';
2338end           
2339
2340%% store the current open names, fields and vel types in uvmat interface
2341UvData.filename_1=filename_1;
2342UvData.VelType_1=[];%default
2343UvData.FieldName_1=[];
2344if isfield(ParamOut_1,VelType)
2345    UvData.VelType_1=ParamOut_1.VelType;
2346end
2347if isfield(ParamOut_1,FieldName)
2348    UvData.FieldName_1=ParamOut_1.FieldName;
2349end
2350
2351%% apply coordinate transform or other user fct
2352XmlData=[];%default
2353if isfield(UvData,'XmlData')%use geometry calib recorded from the ImaDoc xml file as first priority
2354    XmlData=UvData.XmlData;
2355end
2356XmlData_1=[];%default
2357if isfield(UvData,'XmlData_1')
2358   XmlData_1=UvData.XmlData_1;
2359end
2360% menu_transform=get(handles.transform_fct,'String');
2361choice_value=get(handles.transform_fct,'Value');
2362transform_list=get(handles.transform_fct,'UserData');
2363transform=transform_list{choice_value};%selected function handles
2364% z index
2365if ~isempty(filename)
2366    Field{1}.ZIndex=z_index;
2367end
2368%px to phys or other transform on field
2369if ~isempty(transform)
2370    if length(Field)>=2
2371        Field{2}.ZIndex=z_index;
2372        [Field{1},Field{2}]=transform(Field{1},XmlData,Field{2},XmlData_1);
2373        if isempty(Field{2})
2374            Field(2)=[];
2375        end
2376    else
2377        Field{1}=transform(Field{1},XmlData);
2378    end
2379end
2380
2381%% calculate scalar
2382if isequal(FileType,'netcdf') && ~isequal(ParamOut.CivStage,0)%&&~isempty(FieldName)%
2383    Field{1}=calc_field([{ParamOut.FieldName} {ParamOut.ColorVar}],Field{1});
2384end
2385if numel(Field)==2 && ~test_keepdata_1 && isequal(FileType_1,'netcdf') && ~isequal(ParamOut_1.FieldName,'get_field...')%&&~isempty(FieldName_1)
2386    Field{2}=calc_field([{ParamOut_1.FieldName} {ParamOut_1.ColorVar}],Field{2});
2387end
2388
2389%% combine the two input fields (e.g. substract velocity fields)
2390if numel(Field)==2
2391   UvData.Field=sub_field(Field{1},Field{2}); 
2392else
2393   UvData.Field=Field{1};
2394end
2395
2396%% get bounds and mesh (needed for mouse action and to open set_object)
2397test_x=0;
2398test_z=0;% test for unstructured z coordinate
2399[UvData.Field,errormsg]=check_field_structure(UvData.Field);
2400if ~isempty(errormsg)
2401    errormsg=['error in uvmat/refresh_field/check_field_structure: ' errormsg];
2402    return
2403end
2404[CellVarIndex,NbDim,VarType,errormsg]=find_field_indices(UvData.Field);
2405if ~isempty(errormsg)
2406    errormsg=['error in uvmat/refresh_field/find_field_indices: ' errormsg];
2407    return
2408end
2409[NbDim,imax]=max(NbDim);
2410if isfield(UvData.Field,'NbDim')
2411    NbDim=UvData.Field.NbDim;% deal with plane fields containing z coordinates
2412end
2413if ~isempty(VarType{imax}.coord_x)  && ~isempty(VarType{imax}.coord_y)    %unstructured coordinates
2414    XName=UvData.Field.ListVarName{VarType{imax}.coord_x};
2415    YName=UvData.Field.ListVarName{VarType{imax}.coord_y};
2416    eval(['nbvec=length(UvData.Field.' XName ');'])%nbre of measurement points (e.g. vectors)
2417    test_x=1;%test for unstructured coordinates
2418    if ~isempty(VarType{imax}.coord_z)
2419        ZName=UvData.Field.ListVarName{VarType{imax}.coord_z};
2420    else
2421        NbDim=2;
2422    end
2423elseif numel(VarType)>=imax && numel(VarType{imax}.coord)>=NbDim && VarType{imax}.coord(NbDim)>0 %structured coordinate
2424    XName=UvData.Field.ListVarName{VarType{imax}.coord(NbDim)};
2425    if NbDim>1
2426        YName=UvData.Field.ListVarName{VarType{imax}.coord(NbDim-1)}; %structured coordinates
2427    end
2428end
2429if NbDim==3
2430    if ~test_x
2431        ZName=UvData.Field.ListVarName{VarType{imax}.coord(1)};%structured coordinates in 3D
2432    end
2433    eval(['ZMax=max(UvData.Field.' ZName ');'])
2434    eval(['ZMin=min(UvData.Field.' ZName ');'])
2435    UvData.Field.ZMax=ZMax;
2436    UvData.Field.ZMin=ZMin;
2437    test_z=1;
2438    if isequal(ZMin,ZMax)%no z dependency
2439        NbDim=2;
2440        test_z=0;
2441    end
2442end
2443if exist('XName','var')
2444    eval(['XMax=max(max(UvData.Field.' XName '));'])
2445    eval(['XMin=min(min(UvData.Field.' XName '));'])
2446    UvData.Field.NbDim=NbDim;
2447    UvData.Field.XMax=XMax;
2448    UvData.Field.XMin=XMin;
2449    if NbDim >1
2450        eval(['YMax=max(max(UvData.Field.' YName '));'])
2451        eval(['YMin=min(min(UvData.Field.' YName '));'])
2452        UvData.Field.YMax=YMax;
2453        UvData.Field.YMin=YMin;
2454    end
2455    eval(['nbvec=length(UvData.Field.' XName ');'])
2456    if test_x %unstructured coordinates
2457        if test_z
2458            UvData.Field.Mesh=((XMax-XMin)*(YMax-YMin)*(ZMax-ZMin))/nbvec;% volume per vector
2459            UvData.Field.Mesh=(UvData.Field.Mesh)^(1/3);
2460        else
2461            UvData.Field.Mesh=sqrt((XMax-XMin)*(YMax-YMin)/nbvec);%2D
2462        end
2463    else
2464        VarIndex=CellVarIndex{imax}; % list of variable indices
2465        DimIndex=UvData.Field.VarDimIndex{VarIndex(1)}; %list of dim indices for the variable
2466        nbpoints_x=UvData.Field.DimValue(DimIndex(NbDim));
2467        DX=(XMax-XMin)/(nbpoints_x-1);
2468        if NbDim >1
2469            nbpoints_y=UvData.Field.DimValue(DimIndex(NbDim-1));
2470            DY=(YMax-YMin)/(nbpoints_y-1);
2471        end
2472        if NbDim==3
2473            nbpoints_z=UvData.Field.DimValue(DimIndex(1));
2474            DZ=(ZMax-ZMin)/(nbpoints_z-1);
2475            UvData.Field.Mesh=(DX*DY*DZ)^(1/3);
2476            UvData.Field.ZMax=ZMax;
2477            UvData.Field.ZMin=ZMin;
2478        else
2479            UvData.Field.Mesh=DX;%sqrt(DX*DY);
2480        end
2481    end
2482end
2483
2484%% 3D case (menuvolume)
2485if NbDim==3% && UvData.NewSeries
2486    test_set_object=1;
2487    hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
2488    ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
2489    ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
2490    if ~isempty(hset_object) %if set_object is detected
2491%         hhset_object=guidata(hset_object);
2492% %         ZBounds_old(1)=get(hhset_object.z_slider,'Min');
2493% %         ZBounds_old(2)=get(hhset_object.z_slider,'Max');
2494% %         if isequal(ZBounds_old,ZBounds)
2495%             test_set_object=0;% do not refresh the GUI set_object
2496%         else
2497            delete(hset_object);% delete the GUI set_object if it does not fit
2498%         end
2499    end
2500    if test_set_object% reinitiate the GUI set_object
2501        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
2502        UvData.Object{1}.Style='plane';%main plotting plane
2503        UvData.Object{1}.ProjMode='projection';%main plotting plane
2504        UvData.Object{1}.DisplayHandle_uvmat=[]; %plane not visible in uvmat
2505        UvData.Object{1}.NbDim=NbDim;%test for 3D objects
2506        UvData.Object{1}.RangeZ=UvData.Field.Mesh;%main plotting plane
2507        UvData.Object{1}.Coord(1,3)=(UvData.Field.ZMin+UvData.Field.ZMax)/2;%section at a middle plane chosen
2508        UvData.Object{1}.Angle=[0 0 0];
2509%         UvData.Object{1}.Theta=0;
2510%         UvData.Object{1}.Psi=0;
2511        UvData.Object{1}.HandlesDisplay=plot(0,0,'Tag','proj_object');% A REVOIR
2512%         PlotHandles=get_plot_handles(handles);
2513        UvData.Object{1}.Name='1-PLANE';
2514        UvData.Object{1}.enable_plot=1;
2515        set_object(UvData.Object{1},handles,ZBounds);
2516        set(handles.ListObject,'Value',1);
2517        set(handles.ListObject,'String',{'1-PLANE'});
2518        set(handles.edit_object,'Value',1)% put the plane in edit mode to enable the z cursor
2519        edit_object_Callback([],[], handles)
2520    end
2521    %multilevel case (single menuplane in a 3D space)
2522elseif isfield(UvData,'Z')
2523    if isfield(UvData,'CoordType')&& isequal(UvData.CoordType,'phys') && isfield(UvData,'XmlData')
2524        XmlData=UvData.XmlData;
2525        if isfield(XmlData,'PlanePos')
2526            UvData.Object{1}.Coord=XmlData.PlanePos(UvData.ZIndex,:);
2527        end
2528        if isfield(XmlData,'PlaneAngle')
2529            siz=size(XmlData.PlaneAngle);
2530            indangle=min(siz(1),UvData.ZIndex);%take first angle if a single angle is defined (translating scanning)
2531            UvData.Object{1}.PlaneAngle=XmlData.PlaneAngle(indangle,:);
2532        end
2533    elseif isfield(UvData,'ZIndex')
2534        UvData.Object{1}.ZObject=UvData.ZIndex;
2535    end
2536else
2537    % create a default projection
2538    UvData.Object{1}.ProjMode='projection';%main plotting plane
2539    UvData.Object{1}.DisplayHandle_uvmat=[]; %plane not visible in uvmat
2540    set(handles.ListObject,'Value',1);
2541    list_object=get(handles.ListObject,'String');
2542    if isempty(list_object)
2543        list_object={''};
2544    elseif ~isempty(list_object{1})
2545        list_object=[{''};list_object];
2546    end
2547    set(handles.ListObject,'String',list_object);
2548%     set(handles.list_object_2,'String',list_object);
2549end
2550testnewseries=UvData.NewSeries;
2551UvData.NewSeries=0;% put to 0 the test for a new field series (set by RootPath_callback)
2552set(handles.uvmat,'UserData',UvData)
2553
2554%% reset the min and max of scalar if only the mask is displayed(TODO: check the need)
2555if isfield(UvData,'Mask')&& ~isfield(UvData,'A')
2556    set(handles.num_MinA,'String','0')
2557    set(handles.num_MaxA,'String','255')
2558end
2559
2560%% Plot the projections on the selected  projection objects
2561% main projection object (uvmat display)
2562list_object=get(handles.ListObject,'String');
2563if isequal(list_object,{''})%refresh list of objects if the menu is empty
2564    UvData.Object={[]};
2565    set(handles.ListObject,'Value',1)
2566%     set(handles.list_object_2,'Value',1)
2567%     set(handles.list_object_2,'String',{''})
2568%     set(handles.list_object_2,'Visible','off')
2569end
2570IndexObj=get(handles.ListObject,'Value');%selected projection object for main view
2571if IndexObj(1)> numel(UvData.Object)
2572    IndexObj(1)=1;%select the first object if the selected one does not exist
2573    set(handles.ListObject,'Value',1)
2574end
2575plot_handles{1}=handles;
2576if isfield(UvData,'plotaxes')%case of movies
2577    haxes(1)=UvData.plotaxes;
2578else
2579    haxes(1)=handles.axes3;
2580end
2581%PlotParam{1}=read_plot_param(handles);%read plotting parameters on the uvmat interfac
2582PlotParam{1}=read_GUI(handles.uvmat);
2583if ~isfield(PlotParam{1},'Vectors')
2584    PlotParam{1}.Vectors.MaxVec=1;
2585    PlotParam{1}.Vectors.MinVec=0;
2586    PlotParam{1}.Vectors.CheckFixVecColor=1;
2587    PlotParam{1}.Vectors.ColCode1=0.33;
2588    PlotParam{1}.Vectors.ColCode2=0.66;
2589     PlotParam{1}.Vectors.ListColorScalar={'ima_cor'};
2590     PlotParam{1}.Vectors.ListColorCode= {'rgb'};
2591end
2592keeplim(1)=get(handles.CheckFixLimits,'Value');% test for fixed graph limits
2593PosColorbar{1}=UvData.OpenParam.PosColorbar;%prescribe the colorbar position on the uvmat interface
2594
2595% second projection object (view_field display)
2596if length( IndexObj)>=2
2597    view_field_handle=findobj(allchild(0),'tag','view_field');%handles of the view_field GUI
2598    if ~isempty(view_field_handle)
2599        plot_handles{2}=guidata(view_field_handle);
2600        haxes(2)=plot_handles{2}.axes3;
2601        %PlotParam{2}=read_plot_param(plot_handles{2});%read plotting parameters on the viewinterface
2602        PlotParam{2}=read_GUI(handles.uvmat);%read plotting parameters on the uvmat interface
2603        keeplim(2)=get(plot_handles{2}.CheckFixLimits,'Value');
2604        PosColorbar{2}='*'; %TODO: deal with colorbar position on view_field
2605    end
2606end
2607
2608%loop on the projection objects: one or two
2609for imap=1:numel(IndexObj)
2610    iobj=IndexObj(imap);
2611    [ObjectData,errormsg]=proj_field(UvData.Field,UvData.Object{iobj});% project field on the object
2612
2613    if ~isempty(errormsg)
2614        return
2615    end
2616    %     if testnewseries && isfield(ObjectData,'CoordUnit')&& isfield(PlotParam{imap},'Coordinates')
2617%         PlotParam{imap}.Coordinates=rmfield(PlotParam{imap}.Coordinates,'CheckFixEqual'); %set FixEqual to depend on the field (=1 if Data.CoordUnit=1 in plot_field)
2618%     end
2619    if testnewseries && isfield(ObjectData,'CoordUnit')
2620        PlotParam{imap}.Coordinates.CheckFixEqual=1;
2621    end
2622    %use of mask (TODO: check)
2623    if isfield(ObjectData,'NbDim') && isequal(ObjectData.NbDim,2) && isfield(ObjectData,'Mask') && isfield(ObjectData,'A')
2624        flag_mask=double(ObjectData.Mask>200);%=0 for masked regions
2625        AX=ObjectData.AX;%x coordiantes for the scalar field
2626        AY=ObjectData.AY;%y coordinates for the scalar field
2627        MaskX=ObjectData.MaskX;%x coordiantes for the mask
2628        MaskY=ObjectData.MaskY;%y coordiantes for the mask
2629        if ~isequal(MaskX,AX)||~isequal(MaskY,AY)
2630            nxy=size(flag_mask);
2631            sizpx=(ObjectData.MaskX(end)-ObjectData.MaskX(1))/(nxy(2)-1);%size of a mask pixel
2632            sizpy=(ObjectData.MaskY(1)-ObjectData.MaskY(end))/(nxy(1)-1);
2633            x_mask=ObjectData.MaskX(1):sizpx:ObjectData.MaskX(end); % pixel x coordinates for image display
2634            y_mask=ObjectData.MaskY(1):-sizpy:ObjectData.MaskY(end);% pixel x coordinates for image display
2635            %project on the positions of the scalar
2636            npxy=size(ObjectData.A);
2637            dxy(1)=(ObjectData.AY(end)-ObjectData.AY(1))/(npxy(1)-1);%grid mesh in y
2638            dxy(2)=(ObjectData.AX(end)-ObjectData.AX(1))/(npxy(2)-1);%grid mesh in x
2639            xi=ObjectData.AX(1):dxy(2):ObjectData.AX(end);
2640            yi=ObjectData.AY(1):dxy(1):ObjectData.AY(end);
2641            [XI,YI]=meshgrid(xi,yi);% creates the matrix of regular coordinates
2642            flag_mask = interp2(x_mask,y_mask,flag_mask,XI,YI);
2643        end
2644        AClass=class(ObjectData.A);
2645        ObjectData.A=flag_mask.*double(ObjectData.A);
2646        ObjectData.A=feval(AClass,ObjectData.A);
2647        ind_off=[];
2648        if isfield(ObjectData,'ListVarName')
2649            for ilist=1:length(ObjectData.ListVarName)
2650                if isequal(ObjectData.ListVarName{ilist},'Mask')||isequal(ObjectData.ListVarName{ilist},'MaskX')||isequal(ObjectData.ListVarName{ilist},'MaskY')
2651                    ind_off=[ind_off ilist];
2652                end
2653            end
2654            ObjectData.ListVarName(ind_off)=[];
2655            ObjectData.VarDimIndex(ind_off)=[];
2656            ind_off=[];
2657            for ilist=1:length(ObjectData.ListDimName)
2658                if isequal(ObjectData.ListDimName{ilist},'MaskX') || isequal(ObjectData.ListDimName{ilist},'MaskY')
2659                    ind_off=[ind_off ilist];
2660                end
2661            end
2662            ObjectData.ListDimName(ind_off)=[];
2663            ObjectData.DimValue(ind_off)=[];
2664        end
2665    end   
2666    if ~isempty(ObjectData)
2667        PlotType='none'; %default
2668        if imap==2 && isempty(view_field_handle)
2669            view_field(ObjectData)
2670        else
2671            [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
2672            write_plot_param(plot_handles{imap},PlotParamOut) %update the auto plot parameters
2673            if isfield(Field,'Mesh')&&~isempty(Field.Mesh)
2674                ObjectData.Mesh=Field.Mesh; % gives an estimated mesh size (useful for mouse action on the plot)
2675            end
2676        end
2677        if isequal(PlotType,'none')
2678            hget_field=findobj(allchild(0),'name','get_field');
2679            if isempty(hget_field)
2680                get_field(filename)% the projected field cannot be automatically plotted: use get_field to specify the variablesdelete(hget_field)
2681            end
2682            errormsg='The field defined by get_field cannot be plotted';
2683            return
2684        end
2685    end
2686end
2687
2688%% update the mask
2689if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
2690   update_mask(handles,num_i1,num_i2);
2691end
2692
2693%% prepare the menus of histograms and plot them (histogram of the whole volume in 3D case)
2694menu_histo=(UvData.Field.ListVarName)';%list of field variables to be displayed for the menu of histogram display
2695ind_bad=[];
2696nb_histo=1;
2697
2698% suppress coordinates from the histogram menu
2699for ivar=1:numel(menu_histo)%l loop on field variables:
2700    if isfield(UvData.Field,'VarAttribute') && numel(UvData.Field.VarAttribute)>=ivar && isfield(UvData.Field.VarAttribute{ivar},'Role')
2701        Role=UvData.Field.VarAttribute{ivar}.Role;
2702        switch Role
2703            case {'coord_x','coord_y','coord_z','dimvar'}
2704                ind_bad=[ind_bad ivar];
2705            case {'vector_y'}
2706                nb_histo=nb_histo+1;
2707        end
2708    end
2709    DimCell=UvData.Field.VarDimName{ivar};
2710    DimName='';
2711    if ischar(DimCell)
2712        DimName=DimCell;
2713    elseif iscell(DimCell)&& numel(DimCell)==1
2714        DimName=DimCell{1};
2715    end
2716    if strcmp(DimName,menu_histo{ivar})
2717        ind_bad=[ind_bad ivar];
2718    end
2719end
2720menu_histo(ind_bad)=[];
2721
2722%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2723% display menus and plot histograms
2724test_v=0;
2725if ~isempty(menu_histo)
2726    set(handles.histo1_menu,'Value',1)
2727    set(handles.histo1_menu,'String',menu_histo)
2728    histo1_menu_Callback(handles.histo1_menu, [], handles)% plot first histogram
2729    % case of more than one variables (eg vector components)
2730    if nb_histo > 1
2731        test_v=1;
2732        set(handles.histo2_menu,'Visible','on')
2733        set(handles.histo_v,'Visible','on')
2734        set(handles.histo2_menu,'String',menu_histo)
2735        set(handles.histo2_menu,'Value',2)
2736        histo2_menu_Callback(handles.histo2_menu,[], handles)% plot second histogram
2737    end
2738end
2739if ~test_v
2740    set(handles.histo2_menu,'Visible','off')
2741    set(handles.histo_v,'Visible','off')
2742    cla(handles.histo_v)
2743    set(handles.histo2_menu,'Value',1)
2744end
2745%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2746
2747%% display time
2748testimedoc=0;
2749TimeUnit='';
2750if isfield(UvData.Field,'Time')
2751    abstime=UvData.Field.Time;%time read from the netcdf input file
2752end
2753if isfield(UvData,'Field_1') && isfield(UvData.Field_1,'Time')
2754    abstime_1=UvData.Field_1.Time;%time read from the netcdf input file
2755end
2756if isfield(UvData.Field,'dt')
2757    dt=UvData.Field.dt;%dt read from the netcdf input file
2758    if isfield(UvData.Field,'TimeUnit')
2759       TimeUnit=UvData.Field.TimeUnit;
2760    end
2761elseif isfield(UvData,'Field_1') && isfield(UvData.Field_1,'dt')%dt obtained from the second field if not defined in the first
2762    dt=UvData.Field_1.dt;%dt read from the netcdf input file
2763    if isfield(UvData.Field_1,'TimeUnit')
2764       TimeUnit=UvData.Field_1.TimeUnit;
2765    end
2766end
2767% time from xml file overset previous result
2768if isfield(UvData,'XmlData') && isfield(UvData.XmlData,'Time')
2769    if isempty(num_i2)||isnan(num_i2)
2770        num_i2=num_i1;
2771    end
2772    if isempty(num_j1)||isnan(num_j1)
2773        num_j1=1;
2774    end
2775    if isempty(num_j2)||isnan(num_j2)
2776        num_j2=num_j1;
2777    end
2778    siz=size(UvData.XmlData.Time);
2779    if siz(1)>=max(num_i1,num_i2) && siz(2)>=max(num_j1,num_j2)
2780        abstime=(UvData.XmlData.Time(num_i1,num_j1)+UvData.XmlData.Time(num_i2,num_j2))/2;%overset the time read from files
2781        dt=(UvData.XmlData.Time(num_i2,num_j2)-UvData.XmlData.Time(num_i1,num_j1));
2782        testimedoc=1;
2783        if isfield(UvData.XmlData,'TimeUnit')
2784            TimeUnit=UvData.XmlData.TimeUnit;
2785        end
2786    end
2787end
2788if isfield(UvData,'XmlData_1') && isfield(UvData.XmlData_1,'Time')
2789    [P,F,str1,str2,str_a,str_b,E]=name2display(['xx' get(handles.FileIndex_1,'String') get(handles.FileExt_1,'String')]);
2790    num_i2=str2double(str2);
2791    if isnan(num_i2)
2792        num_i2=num_i1;
2793    end
2794    num_j1=str2double(str_a);
2795    if isnan(num_j1)
2796        num_j1=1;
2797    end
2798    num_j2=str2double(str_b);
2799    if isnan(num_j2)
2800        num_j2=num_j1;
2801    end
2802    num_i1=str2double(str1);
2803    siz=size(UvData.XmlData_1.Time);
2804    if siz(1)>=max(num_i1,num_i2) && siz(2)>=max(num_j1,num_j2)
2805        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
2806    end
2807end
2808if ~isequal(numel(abstime),1)
2809    abstime=[];
2810end
2811if ~isequal(numel(abstime_1),1)
2812      abstime_1=[];
2813end 
2814set(handles.abs_time,'String',num2str(abstime,4))
2815set(handles.abs_time_1,'String',num2str(abstime_1,4))
2816if testimedoc && isfield(UvData,'dt')
2817    dt=UvData.dt;
2818end
2819if isempty(dt)||isequal(dt,0)
2820    set(handles.Dt_txt,'String','')
2821else
2822    if  isempty(TimeUnit)
2823        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  10^(-3)'] )
2824    else
2825        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  m' TimeUnit] )
2826    end
2827end
2828
2829
2830%-------------------------------------------------------------------
2831% --- translate coordinate to matrix index
2832%-------------------------------------------------------------------
2833function [indx,indy]=pos2ind(x0,rangx0,nxy)
2834indx=1+round((nxy(2)-1)*(x0-rangx0(1))/(rangx0(2)-rangx0(1)));% index x of pixel 
2835indy=1+round((nxy(1)-1)*(y12-rangy0(1))/(rangy0(2)-rangy0(1)));% index y of pixel
2836
2837%-------------------------------------------------------------------
2838% --- Executes on button press in 'CheckFixLimits'.
2839%-------------------------------------------------------------------
2840function CheckFixLimits_Callback(hObject, eventdata, handles)
2841test=get(handles.CheckFixLimits,'Value');
2842if test
2843    set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
2844else
2845    set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
2846    update_plot(handles);
2847end
2848
2849%-------------------------------------------------------------------
2850% --- Executes on button press in CheckFixEqual.
2851function CheckFixEqual_Callback(hObject, eventdata, handles)
2852test=get(handles.CheckFixEqual,'Value');
2853if test
2854    set(handles.CheckFixEqual,'BackgroundColor',[1 1 0])
2855    cla(handles.axes3)
2856    update_plot(handles);
2857else
2858    set(handles.CheckFixEqual,'BackgroundColor',[0.7 0.7 0.7])
2859    update_plot(handles);
2860%     axis(handles.axes3,'image')
2861end
2862
2863
2864%-------------------------------------------------------------------
2865
2866%-------------------------------------------------------------------
2867% --- Executes on button press in 'CheckZoom'.
2868%-------------------------------------------------------------------
2869function CheckZoom_Callback(hObject, eventdata, handles)
2870
2871if (get(handles.CheckZoom,'Value') == 1);
2872    set(handles.CheckZoom,'BackgroundColor',[1 1 0])
2873    set(handles.CheckFixLimits,'Value',1)% propose by default fixed limits for the plotting axes
2874    set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
2875else
2876    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
2877end
2878
2879
2880%-------------------------------------------------------------------
2881%----Executes on button press in 'record': records the current flags of manual correction.
2882%-------------------------------------------------------------------
2883function record_Callback(hObject, eventdata, handles)
2884% [filebase,num_i1,num_j1,num_i2,num_j2,Ext,NomType,SubDir]=read_input_file(handles);
2885filename=read_file_boxes(handles);
2886[erread,message]=fileattrib(filename);
2887if ~isempty(message) && ~isequal(message.UserWrite,1)
2888     msgbox_uvmat('ERROR',['no writting access to ' filename])
2889     return
2890end
2891test_civ2=isequal(get(handles.civ2,'BackgroundColor'),[1 1 0]);
2892test_civ1=isequal(get(handles.VelType,'BackgroundColor'),[1 1 0]);
2893if ~test_civ2 && ~test_civ1
2894    msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
2895end
2896if test_civ2
2897    nbname='nb_vectors2';
2898   flagname='vec2_FixFlag';
2899   attrname='fix2';
2900end
2901if test_civ1
2902    nbname='nb_vectors';
2903   flagname='vec_FixFlag';
2904   attrname='fix';
2905end
2906%write fix flags in the netcdf file
2907UvData=get(handles.uvmat,'UserData');
2908hhh=which('netcdf.open');% look for built-in matlab netcdf library
2909if ~isequal(hhh,'')% case of new builtin Matlab netcdf library
2910    nc=netcdf.open(filename,'NC_WRITE');
2911    netcdf.reDef(nc);
2912    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),attrname,1);
2913    dimid = netcdf.inqDimID(nc,nbname);
2914    try
2915        varid = netcdf.inqVarID(nc,flagname);% look for already existing fixflag variable
2916    catch
2917        varid=netcdf.defVar(nc,flagname,'double',dimid);%create fixflag variable if it does not exist
2918    end
2919    netcdf.endDef(nc);
2920    netcdf.putVar(nc,varid,UvData.axes3.FF);
2921    netcdf.close(nc); 
2922else %old netcdf library
2923    netcdf_toolbox(filename,AxeData,attrname,nbname,flagname)
2924end
2925
2926%-------------------------------------------------------------------
2927%----Correct the netcdf file, using toolbox (old versions of Matlab).
2928%-------------------------------------------------------------------
2929function netcdf_toolbox(filename,AxeData,attrname,nbname,flagname)
2930nc=netcdf(filename,'write'); %open netcdf file
2931result=redef(nc);
2932eval(['nc.' attrname '=1;']);
2933theDim=nc(nbname) ;% get the number of velocity vectors
2934nb_vectors=size(theDim);
2935var_FixFlag=ncvar(flagname,nc);% var_FixFlag will be written as the netcdf variable vec_FixFlag
2936var_FixFlag(1:nb_vectors)=AxeData.FF;%
2937fin=close(nc);
2938
2939
2940%-------------------------------------------------------------------
2941%determines the fields to read from the interface
2942%------------------------------------------------------------------
2943function VelType=setfield(handles)
2944VelTypeList=get(handles.VelType,'String');
2945index=get(handles.VelType,'Value');
2946VelType=VelTypeList{index};
2947
2948% VelType=[]; %default
2949% if (get(handles.VelType,'Value') == 1);
2950%         VelType='civ1';
2951% % interp1   
2952% elseif (get(handles.interp1,'Value') == 1);
2953%     VelType='interp1';
2954% % filter1   
2955% elseif (get(handles.filter1,'Value') == 1);
2956%     VelType='filter1'; 
2957% % CIV2
2958% elseif (get(handles.civ2,'Value') == 1);
2959%     VelType='civ2';
2960% % interp2   
2961% elseif (get(handles.interp2,'Value') == 1);
2962%     VelType='interp2';
2963% % filter2   
2964% elseif (get(handles.filter2,'Value') == 1); 
2965%     VelType='filter2';
2966% end
2967%
2968% if isequal(get(handles.filter2,'Visible'),'on');
2969%     civ=6;
2970% % interp1   
2971% elseif isequal(get(handles.interp2,'Visible'),'on');
2972%     civ=5;
2973% % filter1   
2974% elseif isequal(get(handles.civ2,'Visible'),'on');
2975%     civ=4; 
2976% % CIV2
2977% elseif isequal(get(handles.filter1,'Visible'),'on');
2978%    civ=3;
2979% % interp2   
2980% elseif isequal(get(handles.interp1,'Visible'),'on');
2981%     civ=2;
2982% % filter2   
2983% elseif isequal(get(handles.VelType,'Visible'),'on'); 
2984%     civ=1;
2985% else
2986%     civ=0;
2987% end
2988
2989%-------------------------------------------------------------------
2990%determines the veltype of the second field to read from the iinterface
2991%------------------------------------------------------------------
2992function VelType=setfield_1(handles)
2993VelTypeList=get(handles.VelType_1,'String');
2994index=get(handles.VelType_1,'Value');
2995VelType=VelTypeList{index};
2996% VelType=[]; %default
2997% if (get(handles.VelType_1,'Value') == 1);
2998%     VelType='civ1';
2999% % interp1   
3000% elseif (get(handles.interp1_1,'Value') == 1);
3001%     VelType='interp1';
3002% % filter1   
3003% elseif (get(handles.filter1_1,'Value') == 1);
3004%     VelType='filter1'; 
3005% % CIV2
3006% elseif (get(handles.civ2_1,'Value') == 1);
3007%     VelType='civ2';
3008% % interp2   
3009% elseif (get(handles.interp2_1,'Value') == 1);
3010%     VelType='interp2';
3011% % filter2   
3012% elseif (get(handles.filter2_1,'Value') == 1); 
3013%     VelType='filter2';
3014% end
3015
3016
3017%---------------------------------------------------
3018% --- Executes on button press in SubField
3019function SubField_Callback(hObject, eventdata, handles)
3020% huvmat=get(handles.run0,'parent');
3021UvData=get(handles.uvmat,'UserData');
3022if get(handles.SubField,'Value')==0% if the subfield button is desactivated   
3023    set(handles.RootPath_1,'String','')
3024    set(handles.RootFile_1,'String','')
3025    set(handles.SubDir_1,'String','');
3026    set(handles.FileIndex_1,'String','');
3027    set(handles.FileExt_1,'String','');
3028    set(handles.RootPath_1,'Visible','off')
3029    set(handles.RootFile_1,'Visible','off')
3030    set(handles.SubDir_1,'Visible','off');
3031    set(handles.FileIndex_1,'Visible','off');
3032    set(handles.FileExt_1,'Visible','off');
3033    set(handles.Fields_1,'Value',1);%set to blank state
3034    set(handles.VelType_1,'Value',1);%set to blank state
3035    if ~strcmp(get(handles.VelType,'Visible'),'on')
3036        set(handles.VelType_1,'Visible','off')
3037    end
3038%     set_veltype_display([handles.VelType_1 handles.interp1_1 handles.filter1_1 ...
3039%             handles.civ2_1 handles.interp2_1 handles.filter2_1],0)
3040    if isfield(UvData,'XmlData_1')
3041        UvData=rmfield(UvData,'XmlData_1');
3042    end
3043    set(handles.uvmat,'UserData',UvData);
3044    run0_Callback(hObject, eventdata, handles); %run
3045else
3046    MenuBrowse_1_Callback(hObject, eventdata, handles)
3047end
3048
3049%------------------------------------------------------------------------
3050% --- read the data displayed for the input rootfile windows (new): TODO use read_GUI
3051
3052function [FileName,RootPath,FileBase,FileIndices,FileExt,SubDir]=read_file_boxes(handles)
3053%------------------------------------------------------------------------
3054InputFile=read_GUI(handles.InputFile);
3055RootPath=InputFile.RootPath;
3056FileName=InputFile.RootPath; %default
3057if ~isempty(InputFile.SubDir)
3058    InputFile.SubDir=regexprep(InputFile.SubDir,'/|\','');
3059    FileName=fullfile(InputFile.RootPath,InputFile.SubDir);
3060end
3061if ~isempty(InputFile.RootFile)
3062    InputFile.RootFile=regexprep(InputFile.RootFile,'/|\','');
3063    FileName=fullfile(FileName,InputFile.RootFile);
3064end
3065SubDir=InputFile.SubDir;
3066% if ~isempty(SubDir) && ~isequal(SubDir,'')
3067%     if (isequal(SubDir(1),'/')|| isequal(SubDir(1),'\'))
3068%         SubDir(1)=[]; %suppress possible / or \ separator
3069%     end
3070%     FileName=fullfile(RootPath,SubDir);
3071% end
3072% RootFile=get(handles.RootFile,'String');
3073% if ~isempty(RootFile) && ~isequal(RootFile,'')
3074%     if (isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
3075%         RootFile(1)=[]; %suppress possible / or \ separator
3076%     end
3077%     FileName=fullfile(FileName,RootFile);
3078% end
3079FileBase=fullfile(InputFile.RootPath,InputFile.RootFile);
3080FileIndices=InputFile.FileIndex;
3081FileExt=InputFile.FileExt;
3082FileName=[FileName InputFile.FileIndex InputFile.FileExt];
3083
3084%------------------------------------------------------------------------
3085% ---- read the data displayed for the second input rootfile windows
3086function [FileName_1,RootPath_1,FileBase_1,FileIndices_1,FileExt_1,SubDir_1]=read_file_boxes_1(handles)
3087%------------------------------------------------------------------------
3088RootPath_1=get(handles.RootPath_1,'String'); % read the data from the file1_input window
3089if isequal(get(handles.RootPath_1,'Visible'),'off') || isequal(RootPath_1,'"')
3090    RootPath_1=get(handles.RootPath,'String');
3091end;
3092FileName_1=RootPath_1; %default
3093SubDir_1=get(handles.SubDir_1,'String');
3094if isequal(get(handles.SubDir_1,'Visible'),'off')|| isequal(SubDir_1,'"')
3095    SubDir_1=get(handles.SubDir,'String');
3096end
3097if numel(SubDir_1)>=1
3098    if (isequal(SubDir_1(1),'/')|| isequal(SubDir_1(1),'\'))
3099        SubDir_1(1)=[]; %suppress possible / or \ separator
3100    end
3101    FileName_1=fullfile(RootPath_1,SubDir_1);
3102end
3103RootFile_1=get(handles.RootFile_1,'String');
3104if isequal(get(handles.RootFile_1,'Visible'),'off') || isequal(RootFile_1,'"')
3105    RootFile_1=get(handles.RootFile,'String');
3106end
3107if numel(RootFile_1)>=1
3108    if ~(isequal(RootFile_1(1),'/')||isequal(RootFile_1(1),'\'))
3109        RootFile_1(1)=[];%suppress possible / or \ separator
3110    end
3111    FileName_1=fullfile(FileName_1,RootFile_1);
3112end
3113FileBase_1=fullfile(RootPath_1,RootFile_1);
3114if isequal(get(handles.FileIndex_1,'Visible'),'off')
3115    FileIndices_1=get(handles.FileIndex,'String');
3116else
3117    FileIndices_1=get(handles.FileIndex_1,'String');
3118end
3119FileExt_1=get(handles.FileExt_1,'String');
3120if isequal(get(handles.FileExt_1,'Visible'),'off') || isequal(FileExt_1,'"')
3121    FileExt_1=get(handles.FileExt,'String');%read FileExt by default
3122end
3123FileName_1=[FileName_1 FileIndices_1 FileExt_1];
3124
3125%------------------------------------------------------------------------
3126% --- Executes on menu selection Fields
3127function Fields_Callback(hObject, eventdata, handles)
3128%------------------------------------------------------------------------
3129list_fields=get(handles.Fields,'String');% list menu fields
3130index_fields=get(handles.Fields,'Value');% selected string index
3131field= list_fields{index_fields(1)}; % selected string
3132if isequal(field,'get_field...')
3133    set(handles.FixVelType,'visible','off')
3134    set(handles.VelType,'visible','off')
3135    set(handles.VelType_1,'visible','off')
3136    filename=read_file_boxes(handles);
3137    hget_field=findobj(allchild(0),'name','get_field');
3138    if ~isempty(hget_field)
3139        delete(hget_field)
3140    end
3141    hget_field=get_field(filename);
3142    set(hget_field,'Name','get_field')
3143    hhget_field=guidata(hget_field);
3144    set(hhget_field.list_fig,'Value',1)
3145    set(hhget_field.list_fig,'String',{'uvmat'})
3146    set(handles.transform_fct,'Value',1)% no transform by default
3147    set(handles.path_transform,'String','')
3148    return %no action
3149end
3150list_fields=get(handles.Fields_1,'String');% list menu fields
3151index_fields=get(handles.Fields_1,'Value');% selected string index
3152field_1= list_fields{index_fields(1)}; % selected string
3153UvData=get(handles.uvmat,'UserData');
3154
3155%read the rootfile input display
3156[FileName,RootPath,FileBase,FileIndices,FileExt]=read_file_boxes(handles);
3157[P,F,str1,str2,str_a,str_b,E,NomType]=name2display(['xxx' get(handles.FileIndex,'String') FileExt]);
3158NomTypeNew=NomType;%default
3159if isequal(field,'image')
3160    if isequal(NomType,'_i1-i2_j')||isequal(NomType,'_i_j1-j2')
3161        NomTypeNew='_i_j';
3162    elseif isequal(NomType,'#_ab')
3163        NomTypeNew='#a';
3164    elseif isequal(NomType,'_i1-i2')
3165        NomTypeNew='_i';
3166    end
3167    imagename=name_generator(FileBase,str2double(str1),str2double(str_a),'.png',NomTypeNew,1,str2double(str2),str2double(str_b),'');
3168    if ~exist(imagename,'file')
3169        [FileName,PathName] = uigetfile( ...
3170            {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3171            '*.jpg',' jpeg image files'; ...
3172            '*.png','.png image files'; ...
3173            '*.tif','.tif image files'; ...
3174            '*.avi;*.AVI','.avi movie files'; ...
3175            '*.vol','.volume images (png)'; ...
3176            '*.*',  'All Files (*.*)'}, ...
3177            'Pick an image',imagename);   
3178        imagename=[PathName FileName];
3179    end
3180     % display the selected field and related information
3181    display_file_name(hObject, eventdata, handles,imagename)%display the image
3182    return
3183else
3184    ext=get(handles.FileExt,'String');
3185    if ~isequal(ext,'.nc') %find the new NomType if the previous display was not already a netcdf file
3186        [FileName,PathName] = uigetfile( ...
3187            {'*.nc', ' (*.nc)';
3188            '*.nc',' netcdf files'; ...
3189            '*.*',  'All Files (*.*)'}, ...
3190            'Pick a netcdf file',FileBase);
3191        filename=[PathName FileName];
3192        % display the selected field and related information
3193        display_file_name(hObject, eventdata, handles,filename)
3194        return
3195    end
3196end
3197indices=name_generator('',str2double(str1),str2double(str_a),'',NomTypeNew,1,str2double(str2),str2double(str_b),'');
3198set(handles.FileIndex,'String',indices)
3199set(handles.NomType,'String',NomTypeNew)
3200% set(handles.FileIndex,'UserData',NomTypeNew)
3201%common to Fields_1_Callback
3202if isequal(field,'image')||isequal(field_1,'image')
3203    set(handles.TitleNpx,'Visible','on')% visible npx,pxcm... buttons
3204    set(handles.TitleNpy,'Visible','on')
3205    set(handles.num_Npx,'Visible','on')
3206    set(handles.num_Npy,'Visible','on')
3207else
3208    set(handles.TitleNpx,'Visible','off')% visible npx,pxcm... buttons
3209    set(handles.TitleNpy,'Visible','off')
3210    set(handles.num_Npx,'Visible','off')
3211    set(handles.num_Npy,'Visible','off')
3212end
3213setfield(handles);% update the field structure ('civ1'....)
3214if ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3215    run0_Callback(hObject, eventdata, handles)
3216end
3217
3218%---------------------------------------------------
3219% --- Executes on menu selection Fields
3220function Fields_1_Callback(hObject, eventdata, handles)
3221%-------------------------------------------------
3222list_fields=get(handles.Fields,'String');% list menu fields
3223index_fields=get(handles.Fields,'Value');% selected string index
3224field= list_fields{index_fields(1)}; % selected string
3225list_fields=get(handles.Fields_1,'String');% list menu fields
3226index_fields=get(handles.Fields_1,'Value');% selected string index
3227field_1= list_fields{index_fields(1)}; % selected string for the second field
3228if isequal(field_1,'') %remove second field if 'blank' field is selected
3229    set(handles.SubField,'Value',0)
3230    SubField_Callback(hObject, eventdata, handles)
3231    return
3232end
3233UvData=get(handles.uvmat,'UserData');
3234
3235%read the rootfile input display
3236[FileName,RootPath,FileBase,FileIndices,FileExt_1]=read_file_boxes_1(handles);
3237[P,F,str1,str2,str_a,str_b,E,NomType_1]=name2display(['xxx' get(handles.FileIndex,'String') FileExt_1]);
3238if isempty(NomType_1)|| strcmp(NomType_1,'')
3239    [FileName,RootPath,FileBase,FileIndices,FileExt_1]=read_file_boxes(handles);
3240    [P,F,str1,str2,str_a,str_b,E,NomType_1]=name2display(['xxx' get(handles.FileIndex,'String') FileExt_1]);
3241end
3242NomTypeNew=NomType_1;%default
3243
3244set(handles.SubField,'Value',1)%introduce second field
3245if isfield(UvData,'XmlData')
3246    UvData.XmlData_1=UvData.XmlData;
3247end
3248set(handles.FileIndex_1,'Visible','on')
3249set(handles.FileExt_1,'Visible','on')
3250RootPath_1=get(handles.RootPath_1,'String');
3251RootFile_1=get(handles.RootFile_1,'String');
3252if isempty(RootPath_1)||isequal(RootPath_1,'')
3253    set(handles.RootPath_1,'String','"')
3254end
3255if isempty(RootFile_1) || isequal(RootFile_1,'')
3256    set(handles.RootFile_1,'String','"')
3257end
3258if ~isempty(RootFile_1)&&(isequal(RootFile_1(1),'/')||isequal(RootFile_1(1),'\'))
3259    RootFile_1(1)=[];
3260end
3261
3262if isequal(field_1,'get_field...')
3263     veltype_handles=[handles.VelType handles.interp1 handles.filter1 handles.civ2 handles.interp2 handles.filter2];
3264     set_veltype_display(veltype_handles,0) % unvisible civ buttons
3265     filename=read_file_boxes_1(handles);
3266     hget_field=findobj(allchild(0),'name','get_field_1');
3267     if ~isempty(hget_field)
3268         delete(hget_field)
3269     end
3270     hget_field=get_field(filename);
3271     set(hget_field,'name','get_field_1')
3272     hhget_field=guidata(hget_field);
3273     set(hhget_field.list_fig,'Value',1)
3274     set(hhget_field.list_fig,'String',{'uvmat'})
3275     set(handles.transform_fct,'Value',1)% no transform by default
3276     set(handles.path_transform,'String','')
3277    return %no action
3278end
3279if isequal(field_1,'image')
3280    % transform netc type to the corresponding image type
3281    if isequal(NomType_1,'_i1-i2_j')||isequal(NomType_1,'_i_j1-j2')|| isequal(NomType_1,'#_ab')|| isequal(NomType_1,'_i1-i2')
3282        UvData.SubDir_1=get(handles.SubDir_1,'String'); %preserve the subdir in memory   
3283        if isequal(NomType_1,'_i1-i2_j')||isequal(NomType_1,'_i_j1-j2')
3284            NomTypeNew='_i_j';
3285        elseif isequal(NomType_1,'#_ab')
3286            NomTypeNew='#a';
3287        elseif isequal(NomType_1,'_i1-i2')
3288            NomTypeNew='_i';
3289        end 
3290    end
3291    imagename=name_generator(FileBase,str2double(str1),str2double(str_a),'.png',NomTypeNew,1,str2double(str2),str2double(str_b),'');
3292    if ~exist(imagename,'file')
3293        [FileName,PathName] = uigetfile( ...
3294            {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3295            '*.jpg',' jpeg image files'; ...
3296            '*.png','.png image files'; ...
3297            '*.tif','.tif image files'; ...
3298            '*.avi;*.AVI','.avi movie files'; ...
3299            '*.vol','.volume images (png)'; ...
3300            '*.*',  'All Files (*.*)'}, ...
3301            'Pick an image',imagename);
3302        % display the selected field and related information
3303        imagename=[PathName FileName];
3304    end
3305    display_file_name_1(hObject, eventdata, handles,imagename)%display the image
3306    return
3307else
3308    set(handles.SubDir_1,'Visible','on')
3309    if ~isequal(FileExt_1,'.nc') %find the new NomType if the previous display was not already a netcdf file
3310        RootPath_1=get(handles.RootPath_1,'String');
3311        RootFile_1=get(handles.RootFile_1,'String');
3312        if isempty(RootPath_1)||isequal(RootPath_1,'')
3313            set(handles.RootPath_1,'String','"')
3314        end
3315        if isempty(RootFile_1) || isequal(RootFile_1,'')
3316            set(handles.RootFile_1,'String','"')
3317        end
3318        if ~isempty(RootFile_1)&&(isequal(RootFile_1(1),'/')||isequal(RootFile_1(1),'\'))
3319            RootFile_1(1)=[];
3320        end
3321        filebase_1=fullfile(RootPath_1,RootFile_1);
3322        SubDir_1=get(handles.SubDir,'String');
3323        if isempty(SubDir_1)||isequal(SubDir_1,'')
3324            if isfield(UvData,'SubDir_1')
3325                SubDir_1=UvData.SubDir_1;%retrieve previous subdir
3326            else
3327                SubDir_1='?';
3328            end
3329        end
3330        str1=get(handles.i1,'String');
3331        str_a=get(handles.j1,'String');
3332        if isequal(NomType_1,'#_ab')||isequal(NomType_1,'_i1-i2_j')||isequal(NomType_1,'_i_j1-j2')||isequal(NomType_1,'_i1-i2')
3333            NomTypeNew=NomType_1;
3334        elseif isequal(NomType_1,'#a')
3335             [filename, n1,na,n2,nb,SubDir_1]=name_generator(filebase_1, str2num(str1),stra2num(str_a),'.nc','#_ab',0,[],[],SubDir_1);
3336             NomTypeNew='#_ab';
3337        elseif isequal(NomType_1,'_i_j')
3338             [filename,n1,na,n2,nb,SubDir_1]=name_generator(filebase_1,str2num(str1),stra2num(str_a),'.nc','_i1-i2_j',0,str2num(str1),[],SubDir_1);
3339            if idetect==1
3340                NomTypeNew='_i1-i2_j';
3341            else
3342                NomTypeNew='_i_j1-j2';
3343            end
3344        else %for instance avi files or any ima_num series
3345            [filename,n1,na,n2,nb,SubDir_1]=name_generator(filebase_1,str2num(str1),stra2num(str_a),'.nc','_i1-i2',0,str2num(str1),[],SubDir_1);
3346            NomTypeNew='_i1-i2';
3347        end           
3348        [Path,Name]=fileparts(filebase_1);
3349        set(handles.FileExt_1,'String','.nc');
3350        if ~isempty(SubDir_1) && ~strcmp(SubDir_1,'''')&& ~strcmp(SubDir_1,'"')&& ~strcmp(SubDir_1(1),'/')
3351            SubDir_1=['/' SubDir_1];
3352        end
3353        set(handles.SubDir_1,'String',SubDir_1);
3354    end
3355    if isequal(field,'vort') || isequal(field,'div') || isequal(field,'strain')
3356        set(handles.VelType_1,'BackgroundColor',[0.702 0.702 0.702]) % put their color to grey
3357        set(handles.civ2_1,'BackgroundColor',[0.702 0.702 0.702])
3358        set(handles.interp1_1,'BackgroundColor',[0.702 0.702 0.702])
3359        set(handles.interp2_1,'BackgroundColor',[0.702 0.702 0.702])
3360    elseif isequal(field_1,'more...'); %add new item to the menu
3361        set(handles.VelType_1,'BackgroundColor',[0.702 0.702 0.702]) % put their color to grey
3362        set(handles.civ2_1,'BackgroundColor',[0.702 0.702 0.702])
3363        str=calc_field;%get the list of available scalars by the function calc_scal
3364        [ind_answer,v] = listdlg('PromptString','Select a file:',...
3365                'SelectionMode','single',...
3366                'ListString',str);
3367       % edit the choice in the field and action menu
3368        scalar=cell2mat(str(ind_answer));
3369        menu=update_menu(handles.Fields_1,scalar);
3370        set(handles.Fields_1,'String',menu);% store the selected scalar type
3371    end
3372end
3373str1=get(handles.i1,'String');
3374str2=get(handles.i2,'String');
3375str_a=get(handles.j1,'String');
3376str_b=get(handles.j2,'String');
3377indices=name_generator('',str2num(str1),stra2num(str_a),'',NomTypeNew,1,str2num(str2),stra2num(str_b),'');
3378set(handles.FileIndex_1,'String',indices)
3379set(handles.NomType_1,'String',NomTypeNew)
3380% set(handles.FileIndex_1,'UserData',NomTypeNew)
3381
3382%common to Fields_Callback
3383if isequal(field,'image')||isequal(field_1,'image')
3384    set(handles.TitleNpx,'Visible','on')% visible npx,pxcm... buttons
3385    set(handles.TitleNpy,'Visible','on')
3386    set(handles.num_Npx,'Visible','on')
3387    set(handles.num_Npy,'Visible','on')
3388%     set(handles.fix_pair,'Value',0)
3389else
3390    set(handles.TitleNpx,'Visible','off')% visible npx,pxcm... buttons
3391    set(handles.TitleNpy,'Visible','off')
3392    set(handles.num_Npx,'Visible','off')
3393    set(handles.num_Npy,'Visible','off')
3394%     set(handles.fix_pair,'Value',1)
3395end
3396if isequal(field,'velocity')||isequal(field_1,'velocity');
3397    state_vect='on';
3398else
3399    state_vect='off';
3400end
3401if ~isequal(field,'velocity')||(~isequal(field_1,'velocity')&~isequal(field_1,''));
3402    state_scal='on';
3403else
3404    state_scal='off';
3405end
3406set(handles.uvmat,'UserData',UvData)
3407setfield(handles);% update the field structure ('civ1'....)
3408if ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3409    run0_Callback(hObject, eventdata, handles)
3410end
3411
3412%------------------------------------------------------------------------
3413% --- set the visibility of relevant velocity type menus:
3414function menu=set_veltype_display(Civ)
3415%------------------------------------------------------------------------
3416if isequal(Civ,0)
3417    imax=0;
3418elseif isequal(Civ,1) || isequal(Civ,2)
3419   imax=1;
3420elseif isequal(Civ,3)
3421    imax=3;
3422elseif isequal(Civ,4) || isequal(Civ,5)
3423    imax=4;
3424elseif isequal(Civ,6) %patch2
3425    imax=6;
3426end
3427menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3428menu=menu(1:imax);
3429% for ibutton=1:imax;
3430%     set(handles(ibutton),'Visible','on')  % unvisible civ buttons
3431% end
3432% % for ibutton=max(imax+1,2):6;
3433% for ibutton=imax+1:6;
3434%     set(handles(ibutton),'Visible','off')  % unvisible civ buttons
3435%     set(handles(ibutton),'Value',0)%unactivate unvisible buttons
3436% end
3437
3438%------------------------------------------------------------------------
3439% --- Executes on button press in VelType.
3440function VelType_Callback(hObject, eventdata, handles)
3441%------------------------------------------------------------------------
3442set(handles.FixVelType,'Value',1)
3443run0_Callback(hObject, eventdata, handles)
3444
3445%------------------------------------------------------------------------
3446% --- Executes on button press in VelType.
3447function VelType_1_Callback(hObject, eventdata, handles)
3448%------------------------------------------------------------------------
3449 
3450set(handles.FixVelType,'Value',1)% the velocity type is now imposed by the GUI (not automatic)
3451%refresh field with a second filename=first fiel name
3452set(handles.run0,'BackgroundColor',[1 1 0])%paint the command button in yellow
3453drawnow   
3454InputFile=read_GUI(handles.InputFile);
3455filename=read_file_boxes(handles);
3456
3457index=get(handles.VelType_1,'Value');
3458if index==1
3459        filename_1='';% we plot the current field without the second field
3460        set(handles.SubField,'Value',0)
3461        SubField_Callback(hObject, eventdata, handles)
3462elseif get(handles.SubField,'Value')% if subfield is already 'on'
3463    filename_1=read_file_boxes_1(handles); %read the current second field
3464else
3465     filename_1=filename;% we compare two fields in the same file
3466     set(handles.SubField,'Value',1)
3467end
3468
3469num_i1=stra2num(get(handles.i1,'String'));
3470num_i2=stra2num(get(handles.i2,'String'));
3471num_j1=stra2num(get(handles.j1,'String'));
3472num_j2=stra2num(get(handles.j2,'String'));
3473
3474errormsg=refresh_field(handles,filename,filename_1,num_i1,num_i2,num_j1,num_j2);
3475
3476if ~isempty(errormsg)
3477    msgbox_uvmat('ERROR',errormsg);
3478else
3479    set(handles.i1,'BackgroundColor',[1 1 1])
3480    set(handles.i2,'BackgroundColor',[1 1 1])
3481    set(handles.j1,'BackgroundColor',[1 1 1])
3482    set(handles.j2,'BackgroundColor',[1 1 1])
3483    set(handles.FileIndex,'BackgroundColor',[1 1 1])
3484    set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
3485end
3486set(handles.run0,'BackgroundColor',[1 0 0])
3487
3488%-----------------------------------------------
3489% --- reset civ buttons
3490function reset_vel_type(handles_civ0,handle1)
3491for ibutton=1:length(handles_civ0)
3492    set(handles_civ0(ibutton),'BackgroundColor',[0.831 0.816 0.784])
3493    set(handles_civ0(ibutton),'Value',0)
3494end
3495if exist('handle1','var')%handles of selected button
3496        set(handle1,'BackgroundColor',[1 1 0]) 
3497end
3498
3499%-------------------------------------------------------
3500% --- Executes on button press in MENUVOLUME.
3501%-------------------------------------------------------
3502function VOLUME_Callback(hObject, eventdata, handles)
3503%errordlg('command VOL not implemented yet')
3504if ishandle(handles.UVMAT_title)
3505    delete(handles.UVMAT_title)
3506end
3507UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3508if isequal(get(handles.VOLUME,'Value'),1)
3509    set(handles.CheckZoom,'Value',0)
3510    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3511    set(handles.edit_vect,'Value',0)
3512    edit_vect_Callback(hObject, eventdata, handles)
3513    set(handles.edit_object,'Value',0)
3514    set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
3515%     set(handles.cal,'Value',0)
3516%     set(handles.cal,'BackgroundColor',[0 1 0])
3517    set(handles.edit_vect,'Value',0)
3518    edit_vect_Callback(hObject, eventdata, handles)
3519    %initiate set_object GUI
3520    data.TITLE='VOLUME';
3521    if isfield(UvData,'CoordType')
3522        data.CoordType=UvData.CoordType;
3523    end
3524    if isfield(UvData,'Mesh')&~isempty(UvData.Mesh)
3525        data.RangeY=UvData.Mesh;
3526        data.RangeX=UvData.Mesh;
3527        data.DX=UvData.Mesh;
3528        data.DY=UvData.Mesh;
3529    elseif isfield(UvData.Field,'AX')&isfield(UvData.Field,'AY')& isfield(UvData.Field,'A')%only image
3530        np=size(UvData.Field.A);
3531        meshx=(UvData.Field.AX(end)-UvData.Field.AX(1))/np(2);
3532        meshy=abs(UvData.Field.AY(end)-UvData.Field.AY(1))/np(1);
3533        data.RangeY=max(meshx,meshy);
3534        data.RangeX=max(meshx,meshy);
3535        data.DX=max(meshx,meshy);
3536    end
3537    data.ParentButton=handles.VOLUME;
3538    PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
3539    [hset_object,UvData.sethandles]=set_object(data,PlotHandles);% call the set_object interface with action on haxes,
3540                                                      % associate the set_object interface handle to the plotting axes
3541    if isfield(UvData.OpenParam,'SetObjectOrigin')                                               
3542    pos_uvmat=get(huvmat,'Position');
3543    pos_set_object(1:2)=UvData.OpenParam.SetObjectOrigin + pos_uvmat(1:2);
3544    pos_set_object(3:4)=UvData.OpenParam.SetObjectSize .* pos_uvmat(3:4); 
3545    set(hset_object,'Position',pos_set_object)
3546    end
3547    UvData.MouseAction='create_object';
3548else
3549    set(handles.VOLUME,'BackgroundColor',[0 1 0])
3550    UvData.MouseAction='none';
3551end
3552set(huvmat,'UserData',UvData)
3553
3554%-------------------------------------------------------
3555function edit_vect_Callback(hObject, eventdata, handles)
3556%-------------------------------------------------------
3557%
3558% UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3559if isequal(get(handles.edit_vect,'Value'),1)
3560    test_civ2=isequal(get(handles.civ2,'BackgroundColor'),[1 1 0]);
3561    test_civ1=isequal(get(handles.VelType,'BackgroundColor'),[1 1 0]);
3562    if ~test_civ2 && ~test_civ1
3563        msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
3564    end
3565    set(handles.record,'Visible','on')
3566    set(handles.edit_vect,'BackgroundColor',[1 1 0])
3567    set(handles.edit_object,'Value',0)
3568    set(handles.CheckZoom,'Value',0)
3569    set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3570%     set(handles.create,'Value',0)
3571%     set(handles.create,'BackgroundColor',[0 1 0])
3572    set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
3573    set(gcf,'Pointer','arrow')
3574%     UvData.MouseAction='edit_vect';
3575else
3576    set(handles.record,'Visible','off')
3577    set(handles.edit_vect,'BackgroundColor',[0.7 0.7 0.7])
3578%     UvData.MouseAction='none';
3579end
3580% set(handles.uvmat,'UserData',UvData)
3581
3582%----------------------------------------------
3583function save_mask_Callback(hObject, eventdata, handles)
3584%-----------------------------------------------------------------------
3585UvData=get(handles.uvmat,'UserData');
3586
3587flag=1;
3588npx=size(UvData.Field.A,2);
3589npy=size(UvData.Field.A,1);
3590xi=0.5:npx-0.5;
3591yi=0.5:npy-0.5;
3592[Xi,Yi]=meshgrid(xi,yi);
3593if isfield(UvData,'Object')
3594    for iobj=1:length(UvData.Object)
3595        ObjectData=UvData.Object{iobj};
3596        if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
3597            flagobj=1;
3598            testphys=0; %coordinates in pixels by default
3599            if isfield(ObjectData,'CoordType') && isequal(ObjectData.CoordType,'phys')
3600                if isfield(UvData,'XmlData')&& isfield(UvData.XmlData,'GeometryCalib')
3601                    Calib=UvData.XmlData.GeometryCalib;
3602                    testphys=1;
3603                end
3604            end
3605            if isfield(ObjectData,'Coord')& isfield(ObjectData,'Style')
3606                if isequal(ObjectData.Style,'polygon')
3607                    X=ObjectData.Coord(:,1);
3608                    Y=ObjectData.Coord(:,2);
3609                    if testphys
3610                        [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
3611                    end
3612                    flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside                 
3613                elseif isequal(ObjectData.Style,'ellipse')
3614                    if testphys
3615                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3616                    end
3617                    RangeX=max(ObjectData.RangeX);
3618                    RangeY=max(ObjectData.RangeY);
3619                    X2Max=RangeX*RangeX;
3620                    Y2Max=RangeY*RangeY;
3621                    distX=(Xi-ObjectData.Coord(1,1));
3622                    distY=(Yi-ObjectData.Coord(1,2));
3623                    flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
3624                elseif isequal(ObjectData.Style,'rectangle')
3625                    if testphys
3626                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3627                    end
3628                    distX=abs(Xi-ObjectData.Coord(1,1));
3629                    distY=abs(Yi-ObjectData.Coord(1,2));
3630                    flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
3631                end
3632                if isequal(ObjectData.ProjMode,'mask_outside')
3633                    flagobj=~flagobj;
3634                end
3635                flag=flag & flagobj;
3636            end
3637        end
3638    end
3639end
3640% flag=~flag;
3641%mask name
3642RootPath=get(handles.RootPath,'String');
3643RootFile=get(handles.RootFile,'String');
3644if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
3645        RootFile(1)=[];
3646end
3647filebase=fullfile(RootPath,RootFile);
3648list=get(handles.masklevel,'String');
3649masknumber=num2str(length(list));
3650maskindex=get(handles.masklevel,'Value');
3651mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
3652imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
3653imflag=flipdim(imflag,1);
3654% imflag=uint8(255*flag);% =0 for flag=0 (vectors=0 when 20<imflag<200)
3655msgbox_uvmat('CONFIRMATION',[mask_name ' saved'])
3656imwrite(imflag,mask_name,'BitDepth',8);
3657
3658%display the mask
3659%update_mask(handles,num_i1,num_j1)
3660figure;
3661vec=linspace(0,1,256);%define a linear greyscale colormap
3662map=[vec' vec' vec'];
3663colormap(map)
3664
3665image(imflag);
3666
3667%-------------------------------------------------------------------
3668%-------------------------------------------------------------------
3669%  - FUNCTIONS FOR SETTING PLOTTING PARAMETERS
3670
3671%------------------------------------------------------------------
3672
3673
3674
3675%------------------------------------------------------------------
3676% --- Executes on selection change in ListColorScalar: choice of the color code.
3677%
3678function ListColorScalar_Callback(hObject, eventdata, handles)
3679%------------------------------------------------------------------
3680% edit the choice for color code
3681list_code=get(handles.ListColorScalar,'String');% list menu fields
3682index_code=get(handles.ListColorScalar,'Value');% selected string index
3683col_code= list_code{index_code(1)}; % selected field
3684if isequal(col_code,'black') || isequal(col_code,'white')
3685   set(handles.Slider1,'Visible','off')
3686   set(handles.Slider2,'Visible','off')
3687   set(handles.num_ColCode1,'Visible','off')
3688   set(handles.num_ColCode2,'Visible','off')
3689   set(handles.CheckFixVecColor,'Visible','off')
3690   set_vec_col_bar(handles)
3691else
3692   set(handles.Slider1,'Visible','on')
3693   set(handles.Slider2,'Visible','on')
3694   set(handles.num_ColCode1,'Visible','on')
3695   set(handles.num_ColCode2,'Visible','on')
3696   set(handles.CheckFixVecColor,'Visible','on') 
3697   if isequal(col_code,'ima_cor')
3698       set(handles.CheckFixVecColor,'Value',0)%fixed scale by default
3699       set(handles.VecColBar,'Value',0)% 3 colors r,g,b by default
3700       set(handles.Slider1,'Min',0);
3701       set(handles.Slider1,'Max',1);
3702       set(handles.Slider2,'Min',0);
3703       set(handles.Slider2,'Max',1);
3704 %      set(handles.min_title_vec,'String','0')
3705       set(handles.num_MaxVec,'String','1')
3706       set(handles.num_ColCode1,'String','0.333')
3707       num_ColCode1_Callback(hObject, eventdata, handles)
3708       set(handles.num_ColCode2,'String','0.666')
3709       num_ColCode2_Callback(hObject, eventdata, handles)
3710   else
3711       set(handles.CheckFixVecColor,'Value',1)%auto scale between min,max by default
3712       set(handles.VecColBar,'Value',1)% colormap 'jet' by default
3713       minval=get(handles.Slider1,'Min');
3714       maxval=get(handles.Slider1,'Max');
3715       set(handles.Slider1,'Value',minval)
3716       set(handles.Slider2,'Value',maxval)
3717       set_vec_col_bar(handles)
3718   end
3719%    slider_update(handles)
3720end
3721%replot the current graph
3722run0_Callback(hObject, eventdata, handles)
3723
3724
3725%----------------------------------------------------------------
3726% -- Executes on slider movement to set the color code
3727%
3728function Slider1_Callback(hObject, eventdata, handles)
3729%------------------------------------------------------------------
3730slider1=get(handles.Slider1,'Value');
3731min_val=str2num(get(handles.num_MinVec,'String'));
3732max_val=str2num(get(handles.num_MaxVec,'String'));
3733col=min_val+(max_val-min_val)*slider1;
3734set(handles.num_ColCode1,'String',num2str(col))
3735if(get(handles.Slider2,'Value') < col)%move also the second slider at the same value if needed
3736    set(handles.Slider2,'Value',col)
3737    set(handles.num_ColCode2,'String',num2str(col))
3738end
3739num_ColCode1_Callback(hObject, eventdata, handles)
3740
3741%----------------------------------------------------------------
3742% Executes on slider movement to set the color code
3743%----------------------------------------------------------------
3744function Slider2_Callback(hObject, eventdata, handles)
3745slider2=get(handles.Slider2,'Value');
3746min_val=str2num(get(handles.num_MinVec,'String'));
3747max_val=str2num(get(handles.num_MaxVec,'String'));
3748col=min_val+(max_val-min_val)*slider2;
3749set(handles.num_ColCode2,'String',num2str(col))
3750if(get(handles.Slider1,'Value') > col)%move also the first slider at the same value if needed
3751    set(handles.Slider1,'Value',col)
3752    set(handles.num_ColCode1,'String',num2str(col))
3753end
3754num_ColCode2_Callback(hObject, eventdata, handles)
3755
3756%----------------------------------------------------------------
3757% --- Execute on return carriage on the edit box corresponding to slider 1
3758%----------------------------------------------------------------
3759function num_ColCode1_Callback(hObject, eventdata, handles)
3760set_vec_col_bar(handles)
3761update_plot(handles);
3762
3763%----------------------------------------------------------------
3764% --- Execute on return carriage on the edit box corresponding to slider 2
3765%----------------------------------------------------------------
3766function num_ColCode2_Callback(hObject, eventdata, handles)
3767set_vec_col_bar(handles)
3768update_plot(handles);
3769%------------------------------------------------------------------------
3770%-------------------------------------------------------
3771% --- Executes on button press in CheckFixVecColor.
3772%-------------------------------------------------------
3773function VecColBar_Callback(hObject, eventdata, handles)
3774set_vec_col_bar(handles)
3775
3776%-------------------------------------------------------------
3777% --- Executes on selection change in transform_fct.
3778function transform_fct_Callback(hObject, eventdata, handles)
3779%-------------------------------------------------------------
3780UvData=get(handles.uvmat,'UserData');
3781menu=get(handles.transform_fct,'String');
3782ind_coord=get(handles.transform_fct,'Value');
3783coord_option=menu{ind_coord};
3784list_transform=get(handles.transform_fct,'UserData');
3785ff=functions(list_transform{end}); 
3786if isequal(coord_option,'more...');
3787    coord_fct='';
3788    prompt = {'Enter the name of the transform function'};
3789    dlg_title = 'user defined transform';
3790    num_lines= 1;
3791    [FileName, PathName] = uigetfile( ...
3792       {'*.m', ' (*.m)';
3793        '*.m',  '.m files '; ...
3794        '*.*', 'All Files (*.*)'}, ...
3795        'Pick a file', ff.file);
3796    if isequal(PathName(end),'/')||isequal(PathName(end),'\')
3797        PathName(end)=[];
3798    end
3799    transform_selected =fullfile(PathName,FileName);
3800    if ~exist(transform_selected,'file')
3801           return
3802    end
3803   [ppp,transform,ext_fct]=fileparts(FileName);% removes extension .m
3804   if ~isequal(ext_fct,'.m')
3805        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
3806        return
3807   end
3808   menu=update_menu(handles.transform_fct,transform);%add the selected fct to the menu
3809   ind_coord=get(handles.transform_fct,'Value');
3810   addpath(PathName)
3811   list_transform{ind_coord}=str2func(transform);% create the function handle corresponding to the newly seleced function
3812   set(handles.transform_fct,'UserData',list_transform)
3813   rmpath(PathName)
3814   % save the new menu in the personal file 'uvmat_perso.mat'
3815   dir_perso=prefdir;%personal Matalb directory
3816   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3817   if exist(profil_perso,'file')
3818       nb_builtin=UvData.OpenParam.NbBuiltin;
3819       for ilist=nb_builtin+1:numel(list_transform)
3820           ff=functions(list_transform{ilist});
3821           transform_fct{ilist-nb_builtin}=ff.file;
3822       end
3823        save (profil_perso,'transform_fct','-append'); %store the root name for future opening of uvmat
3824   end   
3825end
3826
3827%check the current path to the selected function
3828if isa(list_transform{ind_coord},'function_handle')
3829    func=functions(list_transform{ind_coord});
3830    set(handles.path_transform,'String',fileparts(func.file)); %show the path to the senlected function
3831else
3832    set(handles.path_transform,'String','')
3833end
3834
3835set(handles.CheckFixLimits,'Value',0)
3836set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
3837
3838%delete drawn objects
3839hother=findobj('Tag','proj_object');%find all the proj objects
3840for iobj=1:length(hother)
3841    delete_object(hother(iobj))
3842end
3843hother=findobj('Tag','DeformPoint');%find all the proj objects
3844for iobj=1:length(hother)
3845    delete_object(hother(iobj))
3846end
3847hh=findobj('Tag','calib_points');
3848if ~isempty(hh)
3849    delete(hh)
3850end
3851hhh=findobj('Tag','calib_marker');
3852if ~isempty(hhh)
3853    delete(hhh)
3854end
3855if isfield(UvData,'Object')
3856     UvData.Object=UvData.Object(1);
3857end
3858%list_object=get(handles.ListObject,'String');
3859set(handles.ListObject,'Value',1)
3860set(handles.ListObject,'String',{''})
3861%set(handles.list_object_2,'Value',1)
3862%set(handles.list_object_2,'String',{''})
3863%list_object_2_Callback(hObject, eventdata, handles)
3864
3865%delete mask if it is displayed
3866if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
3867   UvData=rmfield(UvData,'MaskName'); %will impose mask refresh 
3868end
3869set(handles.uvmat,'UserData',UvData)
3870run0_Callback(hObject, eventdata, handles)
3871
3872%------------------------------------------------------------------------
3873function histo1_menu_Callback(hObject, eventdata, handles)
3874%--------------------------------------------
3875%plot first histo
3876huvmat=get(handles.histo1_menu,'parent');
3877histo_menu=get(handles.histo1_menu,'String');
3878histo_value=get(handles.histo1_menu,'Value');
3879FieldName=histo_menu{histo_value};
3880update_histo(handles.histo_u,huvmat,FieldName)
3881
3882%------------------------------------------------------------------------
3883function histo2_menu_Callback(hObject, eventdata, handles)
3884%------------------------------------------------------------------------
3885%plot second histo
3886huvmat=get(handles.histo2_menu,'parent');
3887histo_menu=get(handles.histo2_menu,'String');
3888histo_value=get(handles.histo2_menu,'Value');
3889FieldName=histo_menu{histo_value};
3890update_histo(handles.histo_v,huvmat,FieldName)
3891
3892%------------------------------------------------------------------------
3893%read the field .Fieldname stored in UvData and plot its histogram
3894function update_histo(haxes,huvmat,FieldName)
3895%------------------------------------------------------------------------
3896UvData=get(huvmat,'UserData');
3897if ~isfield(UvData.Field,FieldName)
3898    msgbox_uvmat('ERROR',['no field  ' FieldName ' for histogram'])
3899    return
3900end
3901Field=UvData.Field;
3902FieldHisto=eval(['Field.' FieldName]);
3903if isfield(Field,'FF') && ~isempty(Field.FF) && isequal(size(Field.FF),size(FieldHisto))
3904    indsel=find(Field.FF==0);%find values marked as false
3905    if ~isempty(indsel)
3906        FieldHisto=FieldHisto(indsel);
3907    end
3908end
3909if isempty(Field)
3910    msgbox_uvmat('ERROR',['empty field ' FieldName])
3911else
3912    nxy=size(FieldHisto);
3913    Amin=double(min(min(min(FieldHisto))));%min of image
3914    Amax=double(max(max(max(FieldHisto))));%max of image
3915    if isequal(Amin,Amax)
3916        %msgbox_uvmat('WARNING',['uniform field =' num2str(Amin)]);
3917        cla(haxes)
3918    else
3919        Histo.ListVarName={FieldName,'histo'};
3920        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
3921            Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
3922        else
3923            if numel(nxy)==2
3924                Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
3925            else
3926                Histo.VarDimName={FieldName,{FieldName,'rgb'}}; %dimensions for the histogram
3927            end
3928        end
3929        %unit
3930        units=[]; %default
3931        for ivar=1:numel(Field.ListVarName)
3932            if strcmp(Field.ListVarName{ivar},FieldName)
3933                if isfield(Field,'VarAttribute') && numel(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'units')
3934                    units=Field.VarAttribute{ivar}.units;
3935                    break
3936                end
3937            end
3938        end
3939        if ~isempty(units)
3940            Histo.VarAttribute{1}.units=units;
3941        end
3942        eval(['Histo.' FieldName '=linspace(Amin,Amax,50);'])%absissa values for histo
3943        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
3944            C=reshape(double(FieldHisto),1,[]);% reshape in a vector
3945            eval(['Histo.histo(:,1)=hist(C, Histo.' FieldName ');']);  %calculate histogram
3946        else
3947            for col=1:size(FieldHisto,3)
3948                B=FieldHisto(:,:,col);
3949                C=reshape(double(B),1,nxy(1)*nxy(2));% reshape in a vector
3950                eval(['Histo.histo(:,col)=hist(C, Histo.' FieldName ');']);  %calculate histogram
3951            end
3952        end
3953%         set(haxes,'XLimMode','auto')%reset auto mode (after CheckZoom effect)
3954%         set(haxes,'YLimMode','auto')
3955%         PlotParam.Auto_xy=1;
3956        plot_field(Histo,haxes);
3957    end
3958end
3959
3960%------------------------------------------------
3961%CALLBACKS FOR PLOTTING PARAMETERS
3962%-------------------------------------------------
3963
3964%------------------------------------------------------------------------
3965function num_MinX_Callback(hObject, eventdata, handles)
3966%------------------------------------------------------------------------
3967set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3968set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3969update_plot(handles);
3970
3971%------------------------------------------------------------------------
3972function num_MaxX_Callback(hObject, eventdata, handles)
3973%------------------------------------------------------------------------
3974set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3975set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3976update_plot(handles);
3977
3978%------------------------------------------------------------------------
3979function num_MinY_Callback(hObject, eventdata, handles)
3980%------------------------------------------
3981set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3982set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3983update_plot(handles);
3984
3985%------------------------------------------------------------------------
3986function num_MaxY_Callback(hObject, eventdata, handles)
3987%------------------------------------------------------------------------
3988set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3989set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3990update_plot(handles);
3991
3992%------------------------------------------------------------------------
3993function num_MinA_Callback(hObject, eventdata, handles)
3994%------------------------------------------
3995set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3996set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3997MinA=str2double(get(handles.num_MinA,'String'));
3998MaxA=str2double(get(handles.num_MaxA,'String'));
3999if MinA>MaxA% switch minA and maxA in case of error
4000    MinA_old=MinA;
4001    MinA=MaxA;
4002    MaxA=MinA_old;
4003    set(handles.num_MinA,'String',num2str(MinA,5));
4004    set(handles.num_MaxA,'String',num2str(MaxA,5));
4005end
4006update_plot(handles);
4007
4008%------------------------------------------------------------------------
4009function num_MaxA_Callback(hObject, eventdata, handles)
4010%------------------------------------------------------------------------
4011set(handles.CheckFixScalar,'Value',1) %suppress auto mode
4012set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
4013MinA=str2double(get(handles.num_MinA,'String'));
4014MaxA=str2double(get(handles.num_MaxA,'String'));
4015if MinA>MaxA% switch minA and maxA in case of error
4016        MinA_old=MinA;
4017    MinA=MaxA;
4018    MaxA=MinA_old;
4019    set(handles.num_MinA,'String',num2str(MinA,5));
4020    set(handles.num_MaxA,'String',num2str(MaxA,5));
4021end
4022update_plot(handles);
4023
4024%------------------------------------------------------------------------
4025function CheckFixScalar_Callback(hObject, eventdata, handles)
4026%------------------------------------------------------------------------
4027test=get(handles.CheckFixScalar,'Value');
4028if test
4029    set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
4030else
4031    set(handles.CheckFixScalar,'BackgroundColor',[0.7 0.7 0.7])
4032    update_plot(handles);
4033end
4034
4035%-------------------------------------------------------------------
4036function CheckBW_Callback(hObject, eventdata, handles)
4037%-------------------------------------------------------------------
4038update_plot(handles);
4039
4040%-------------------------------------------------------------------
4041function ListContour_Callback(hObject, eventdata, handles)
4042%-------------------------------------------------------------------
4043val=get(handles.ListContour,'Value');
4044if val==2
4045    set(handles.interval_txt,'Visible','on')
4046    set(handles.num_IncrA,'Visible','on')
4047else
4048    set(handles.interval_txt,'Visible','off')
4049    set(handles.num_IncrA,'Visible','off')
4050end
4051update_plot(handles);
4052
4053%-------------------------------------------------------------------
4054function num_IncrA_Callback(hObject, eventdata, handles)
4055%-------------------------------------------------------------------
4056update_plot(handles);
4057
4058%-------------------------------------------------------------------
4059function CheckHideWarning_Callback(hObject, eventdata, handles)
4060%-------------------------------------------------------------------
4061update_plot(handles);
4062
4063%-------------------------------------------------------------------
4064function CheckHideFalse_Callback(hObject, eventdata, handles)
4065%-------------------------------------------------------------------
4066update_plot(handles);
4067
4068%-------------------------------------------------------------------
4069function num_VecScale_Callback(hObject, eventdata, handles)
4070%-------------------------------------------------------------------
4071set(handles.CheckFixVectors,'Value',1);
4072set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
4073update_plot(handles);
4074
4075%-------------------------------------------------------------------
4076function CheckFixVectors_Callback(hObject, eventdata, handles)
4077%-------------------------------------------------------------------
4078test=get(handles.CheckFixVectors,'Value');
4079if test
4080    set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
4081else
4082    update_plot(handles);
4083    %set(handles.num_VecScale,'String',num2str(ScalOut.num_VecScale,3))
4084    set(handles.CheckFixVectors,'BackgroundColor',[0.7 0.7 0.7])
4085end
4086
4087%------------------------------------------------------------------------
4088% --- Executes on selection change in CheckDecimate4 (nb_vec/4).
4089function CheckDecimate4_Callback(hObject, eventdata, handles)
4090%------------------------------------------------------------------------
4091update_plot(handles);
4092
4093%------------------------------------------------------------------------
4094% --- Executes on selection change in ListColorCode menu
4095function ListColorCode_Callback(hObject, eventdata, handles)
4096%------------------------------------------------------------------------
4097set_vec_col_bar(handles)
4098update_plot(handles);
4099
4100%------------------------------------------------------------------------
4101% --- Executes on button press in CheckFixVecColor.
4102function CheckFixVecColor_Callback(hObject, eventdata, handles)
4103%------------------------------------------------------------------------
4104test=get(handles.CheckFixVecColor,'Value');
4105if test
4106    set(handles.CheckFixVecColor,'BackgroundColor',[1 1 0])
4107else
4108    update_plot(handles);
4109    %set(handles.num_VecScale,'String',num2str(ScalOut.num_VecScale,3))
4110    set(handles.CheckFixVecColor,'BackgroundColor',[0.7 0.7 0.7])
4111end
4112
4113%------------------------------------------------------------------------
4114% --- Executes on selection change in num_MaxVec.
4115function num_MinVec_Callback(hObject, eventdata, handles)
4116%------------------------------------------------------------------------
4117max_vec_Callback(hObject, eventdata, handles)
4118
4119%------------------------------------------------------------------------
4120% --- Executes on selection change in num_MaxVec.
4121function num_MaxVec_Callback(hObject, eventdata, handles)
4122%------------------------------------------------------------------------
4123set(handles.CheckFixVecColor,'Value',1)
4124CheckFixVecColor_Callback(hObject, eventdata, handles)
4125min_val=str2num(get(handles.num_MinVec,'String'));
4126max_val=str2num(get(handles.num_MaxVec,'String'));
4127slider1=get(handles.Slider1,'Value');
4128slider2=get(handles.Slider2,'Value');
4129colcode1=min_val+(max_val-min_val)*slider1;
4130colcode2=min_val+(max_val-min_val)*slider2;
4131set(handles.num_ColCode1,'String',num2str(colcode1))
4132set(handles.num_ColCode2,'String',num2str(colcode2))
4133update_plot(handles);
4134
4135%------------------------------------------------------------------------
4136% --- update the display of color code for vectors
4137function set_vec_col_bar(handles)
4138%------------------------------------------------------------------------
4139%get the image of the color display button 'VecColBar' in pixels
4140set(handles.VecColBar,'Unit','pixel');
4141pos_vert=get(handles.VecColBar,'Position');
4142set(handles.VecColBar,'Unit','Normalized');
4143width=ceil(pos_vert(3));
4144height=ceil(pos_vert(4));
4145
4146%get slider indications
4147list=get(handles.ListColorCode,'String');
4148ichoice=get(handles.ListColorCode,'Value');
4149colcode.ListColorCode=list{ichoice};
4150colcode.MinVec=str2num(get(handles.num_MinVec,'String'));
4151colcode.MaxVec=str2num(get(handles.num_MaxVec,'String'));
4152test3color=strcmp(colcode.ListColorCode,'rgb') || strcmp(colcode.ListColorCode,'bgr');
4153if test3color
4154    colcode.ColCode1=str2num(get(handles.num_ColCode1,'String'));
4155    colcode.ColCode2=str2num(get(handles.num_ColCode2,'String'));
4156end
4157% colcode.FixedCbounds=0;
4158%colcode.CheckFixVecColor=1;
4159vec_C=colcode.MinVec+(colcode.MaxVec-colcode.MinVec)*(0.5:width-0.5)/width;%sample of vec_C values from min to max
4160[colorlist,col_vec]=set_col_vec(colcode,vec_C);
4161oneheight=ones(1,height);
4162A1=colorlist(col_vec,1)*oneheight;
4163A2=colorlist(col_vec,2)*oneheight;
4164A3=colorlist(col_vec,3)*oneheight;
4165A(:,:,1)=A1';
4166A(:,:,2)=A2';
4167A(:,:,3)=A3';
4168set(handles.VecColBar,'Cdata',A)
4169
4170%-------------------------------------------------------------------
4171function update_plot(handles)
4172%-------------------------------------------------------------------
4173UvData=get(handles.uvmat,'UserData');
4174AxeData=UvData.axes3;% retrieve the current plotted data
4175PlotParam=read_GUI(handles.uvmat);
4176[PP,PlotParamOut]= plot_field(AxeData,handles.axes3,PlotParam);
4177write_plot_param(handles,PlotParamOut); %update the auto plot parameters
4178
4179% %-------------------------------------------------------------------
4180% % --- Executes on button press in grid.
4181% function grid_Callback(hObject, eventdata, handles)
4182
4183
4184%-------------------------------------------------------------------
4185% --- Executes on selection change in edit_object.
4186function edit_object_Callback(hObject, eventdata, handles)
4187%-------------------------------------------------------------------
4188UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4189test=get(handles.edit_object,'Value');
4190if test
4191    set(handles.edit_object,'BackgroundColor',[1,1,0]) 
4192    %suppress the other options
4193    set(handles.CheckZoom,'Value',0)
4194    CheckZoom_Callback(hObject, eventdata, handles)
4195    hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4196    if ishandle(hgeometry_calib)
4197        hhgeometry_calib=guidata(hgeometry_calib);
4198        set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4199        set(hhgeometry_calib.edit_append,'BackgroundColor',[0.7 0.7 0.7])
4200    end
4201else
4202    UvData.MouseAction='none';
4203    set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7])   
4204%     hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
4205%     if ~isempty(hset_object)
4206%         delete(hset_object)% delete the current GUI set_object
4207%     end
4208end
4209set(handles.uvmat,'UserData',UvData);
4210hset_object=findobj(allchild(0),'Tag','set_object');
4211if ~isempty(hset_object)
4212    hhset_object=guidata(hset_object);
4213    if test
4214        set(hhset_object.PLOT,'enable','on');
4215    else
4216       set(hhset_object.PLOT,'enable','off');
4217    end
4218end
4219
4220%------------------------------------------------------------------------
4221% --- Executes on selection change in ListObject.
4222function ListObject_Callback(hObject, eventdata, handles)
4223%------------------------------------------------------------------------
4224
4225list_str=get(handles.ListObject,'String');
4226IndexObj_old=get(handles.ListObject,'UserData');%retrieve previous selection
4227IndexObj=get(handles.ListObject,'Value');
4228if length(IndexObj)>2
4229     IndexObj=[IndexObj(end-1) IndexObj(end)];%keeps only the last two selected items at most
4230end
4231if length(IndexObj)==1
4232    if length(IndexObj_old)>=2 && isequal(IndexObj_old(1),IndexObj)       
4233        IndexObj=IndexObj_old(2);
4234    elseif length(IndexObj_old)>=2 && isequal(IndexObj_old(2),IndexObj)
4235        IndexObj=IndexObj_old(1);
4236    else
4237        IndexObj=[IndexObj_old(1) IndexObj];
4238    end
4239end
4240set(handles.ListObject,'Value',IndexObj); %keeps only the two first selected objects
4241set(handles.ListObject,'UserData',IndexObj)
4242 %desactivate the edit object mode
4243set(handles.edit_object,'Value',0)
4244edit_object_Callback(hObject, eventdata, handles)
4245UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4246if numel(UvData.Object)<max(IndexObj);
4247    msgbox_uvmat('ERROR','invalid object list')
4248    return
4249end
4250UvData.Object=update_obj(UvData,IndexObj(1),IndexObj(2));
4251set(handles.uvmat,'UserData',UvData)
4252
4253%project on the selected object and update the corresponding plot
4254hview_field=findobj(allchild(0),'tag','view_field');
4255ViewObjectAxes=[];%default
4256if ~isequal(IndexObj(1),IndexObj_old(1))
4257update_object(handles,IndexObj(1),handles.axes3,list_str{IndexObj(1)})%plot the projection in uvmat
4258end
4259if length(IndexObj)==2 && (length(IndexObj_old)==1 || ~isequal(IndexObj(2),IndexObj_old(2)))
4260    hview_field=findobj(allchild(0),'tag','view_field');
4261    if isempty(hview_field)
4262        hview_field=view_field;
4263    end
4264    PlotHandles=guidata(hview_field);
4265    update_object(handles,IndexObj(2),PlotHandles.axes3,list_str{IndexObj(2)})%plot the projection in view_field
4266end
4267update_object_color(handles.axes3,PlotHandles.axes3,UvData.Object{IndexObj(2)}.DisplayHandle_uvmat)
4268
4269%------------------------------------------------------------------------
4270function update_object(handles,IndexObj,ViewObjectAxes,ObjectName)
4271%------------------------------------------------------------------------
4272UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4273ObjectData=UvData.Object{IndexObj};
4274ObjectData.Name=ObjectName;
4275if isequal(get(handles.edit_object,'Value'),1)
4276    ObjectData.enable_plot=1; % desable the PLOT option in the set_object GUI (editing mode
4277end
4278ZBounds=0; % default
4279if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4280    ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4281    ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4282end
4283hset_object=findobj(allchild(0),'tag','set_object');
4284if ~isempty(hset_object)
4285    delete(hset_object)% delete existing version of set_object
4286    hset_object=set_object(ObjectData,[],ZBounds);
4287end
4288edit_test=get(handles.edit_object,'Value');
4289if edit_test
4290    ObjectData.enable_plot=1;
4291else
4292    if isfield(ObjectData,'enable_plot')
4293        ObjectData=rmfield(ObjectData,'enable_plot');
4294    end
4295end
4296
4297uistack(ViewObjectAxes,'top')% display the plotting axes at the top
4298ProjData= proj_field(UvData.Field,ObjectData);%project the current interface field on ObjectData
4299plot_field(ProjData,ViewObjectAxes,read_GUI(get(ViewObjectAxes,'Parent')));%read plotting parameters on the uvmat interfacPlotHandles);
4300%
4301% UvData.Object=update_obj(UvData,IndexObj(1),IndexObj(2));
4302% set(handles.uvmat,'UserData',UvData)
4303
4304%------------------------------------------------------------------------
4305%--- update the representation of objects
4306function update_object_color(axes_uvmat,axes_view_field,DisplayHandle)
4307%------------------------------------------------------------------------
4308hother=[findobj(axes_uvmat,'Tag','proj_object') ;findobj(axes_view_field,'Tag','proj_object')] ;%find all the proj objects
4309hother=[hother ;findobj(axes_uvmat,'Tag','DeformPoint'); findobj(axes_view_field,'Tag','DeformPoint')];
4310for iobj=1:length(hother)
4311    if isequal(get(hother(iobj),'Type'),'rectangle')||isequal(get(hother(iobj),'Type'),'patch')
4312        set(hother(iobj),'EdgeColor','b')
4313        if isequal(get(hother(iobj),'FaceColor'),'m')
4314            set(hother(iobj),'FaceColor','b')
4315        end
4316    elseif isequal(get(hother(iobj),'Type'),'image')
4317        Acolor=get(hother(iobj),'CData');
4318        Acolor(:,:,1)=zeros(size(Acolor,1),size(Acolor,2));
4319        set(hother(iobj),'CData',Acolor);
4320    else
4321        set(hother(iobj),'Color','b')
4322    end
4323    set(hother(iobj),'Selected','off')
4324end
4325linetype=get(DisplayHandle,'Type');
4326if isequal(linetype,'line')
4327    set(DisplayHandle,'Color','m'); %set the selected object to magenta color
4328elseif isequal(linetype,'rectangle')
4329    set(DisplayHandle,'EdgeColor','m'); %set the selected object to magenta color
4330elseif isequal(linetype,'patch')
4331    set(DisplayHandle,'FaceColor','m'); %set the selected object to magenta color
4332end
4333SubObjectData=get(DisplayHandle,'UserData');
4334if isfield(SubObjectData,'SubObject') & ishandle(SubObjectData.SubObject)
4335    for iobj=1:length(SubObjectData.SubObject)
4336        hsub=SubObjectData.SubObject(iobj);
4337        if isequal(get(hsub,'Type'),'rectangle')
4338            set(hsub,'EdgeColor','m'); %set the selected object to magenta color
4339        elseif isequal(get(hsub,'Type'),'image')
4340            Acolor=get(hsub,'CData');
4341            Acolor(:,:,1)=Acolor(:,:,3);
4342            set(hsub,'CData',Acolor);
4343        else
4344            set(hsub,'Color','m')
4345        end
4346    end
4347end
4348if isfield(SubObjectData,'DeformPoint') & ishandle(SubObjectData.DeformPoint)
4349    set(SubObjectData.DeformPoint,'Color','m')
4350end
4351
4352%         SubObjectData=get(ObjectData.DisplayHandle_uvmat,'UserData');
4353
4354
4355
4356
4357
4358
4359
4360%------------------------------------------------------
4361% --- Executes on button press in Menu/Export/field in workspace.
4362%------------------------------------------------------
4363function MenuExportField_Callback(hObject, eventdata, handles)
4364global Data_uvmat
4365Data_uvmat=get(handles.uvmat,'UserData');
4366evalin('base','global Data_uvmat')%make CurData global in the workspace
4367display('current field :')
4368evalin('base','Data_uvmat') %display CurData in the workspace
4369commandwindow; %brings the Matlab command window to the front
4370
4371%------------------------------------------------------
4372% --- Executes on button press in Menu/Export/extract figure.
4373%------------------------------------------------------
4374function MenuExport_plot_Callback(hObject, eventdata, handles)
4375huvmat=get(handles.MenuExport_plot,'parent');
4376UvData=get(huvmat,'UserData');
4377hfig=figure;
4378newaxes=copyobj(handles.axes3,hfig);
4379map=colormap(handles.axes3);
4380colormap(map);%transmit the current colormap to the zoom fig
4381colorbar
4382
4383
4384% --------------------------------------------------------------------
4385function Insert_Callback(hObject, eventdata, handles)
4386
4387
4388% --------------------------------------------------------------------
4389function MenuHelp_Callback(hObject, eventdata, handles)
4390% --------------------------------------------------------------------
4391path_to_uvmat=which ('uvmat');% check the path of uvmat
4392pathelp=fileparts(path_to_uvmat);
4393helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
4394if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
4395else
4396    addpath (fullfile(pathelp,'uvmat_doc'))
4397    web(helpfile);
4398end
4399
4400%------------------------------------------------------------------------
4401% --------------------------------------------------------------------
4402function MenuExportMovie_Callback(hObject, eventdata, handles)
4403% --------------------------------------------------------------------
4404set(handles.MenuExportMovie,'BusyAction','queue')% activate the button
4405huvmat=get(handles.run0,'parent');
4406UvData=get(huvmat,'UserData');
4407[xx,xx,FileBase]=read_file_boxes(handles);
4408 %read the current input file name
4409prompt = {'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)'};
4410dlg_title = 'select properties of the output avi movie';
4411num_lines= 1;
4412% nbfield_cell=get(handles.last_i,'String');
4413def     = {[FileBase '_out.avi'];'10';'1';'[0.03 0.05 0.95 0.92]';'10'};
4414answer = inputdlg(prompt,dlg_title,num_lines,def,'on');
4415aviname=answer{1};
4416fps=str2double(answer{2});
4417% check for existing file with output name aviname
4418if exist(aviname,'file')
4419    backup=aviname;
4420    testexist=2;
4421    while testexist==2
4422        backup=[backup '~'];
4423        testexist=exist(backup,'file');     
4424    end
4425    [success,message]=copyfile(aviname,backup);%make backup of the existing file
4426    if isequal(success,1)
4427        delete(aviname)%delete existing file
4428    else
4429        msgbox_uvmat('ERROR',message)
4430        return
4431    end
4432end
4433%create avi open
4434aviobj=avifile(aviname,'Compression','None','fps',fps);
4435
4436%display first view for tests
4437newfig=figure;
4438newaxes=copyobj(handles.axes3,newfig);%new plotting axes in the new figure
4439set(newaxes,'Tag','movieaxes')
4440nbpix=[512 384]*str2double(answer{3});
4441set(gcf,'Position',[1 1 nbpix])% resolution XVGA
4442set(newaxes,'Position',eval(answer{4}));
4443map=colormap(handles.axes3);
4444colormap(map);%transmit the current colormap to the zoom fig
4445msgbox_uvmat('INPUT_Y-N',{['adjust figure ' num2str(newfig) ' with its matlab edit menu '] ;...
4446        ['then press OK to get the avi movie as a copy of figure ' num2str(newfig) ' display']});
4447UvData.plotaxes=newaxes;% the axis in the new figure becomes the current main plotting axes
4448set(huvmat,'UserData',UvData);
4449increment=str2double(get(handles.increment_scan,'String')); %get the field increment d
4450if isnan(increment)
4451    set(handles.increment_scan,'String','1')%default value
4452    increment=1;
4453end
4454set(handles.STOP,'Visible','on')
4455set(handles.speed,'Visible','on')
4456set(handles.speed_txt,'Visible','on')
4457set(handles.Movie,'BusyAction','queue')
4458
4459%imin=str2double(get(handles.i1,'String'));
4460imax=str2double(answer{5});
4461% if isfield(UvData,'Time')
4462htitle=get(newaxes,'Title');
4463xlim=get(newaxes,'XLim');
4464ylim=get(newaxes,'YLim');
4465set(htitle,'Position',[xlim(2)+0.07*(xlim(2)-xlim(1)) ylim(2)-0.05*(ylim(2)-ylim(1)) 0])
4466time_str=get(handles.abs_time,'String');
4467set(htitle,'String',['t=' time_str])
4468set(handles.speed,'Value',1)
4469for i=1:imax
4470    if get(handles.speed,'Value')~=0 && isequal(get(handles.MenuExportMovie,'BusyAction'),'queue') % enable STOP command
4471            runpm(hObject,eventdata,handles,increment)% run plus
4472            drawnow
4473            time_str=get(handles.abs_time,'String');
4474            if ishandle(htitle)
4475             set(htitle,'String',['t=' time_str])
4476            end
4477            mov=getframe(newfig);
4478            aviobj=addframe(aviobj,mov);
4479    end
4480end
4481aviobj=close(aviobj);
4482UvData=rmfield(UvData,'plotaxes');
4483%UvData.Object{1}.plotaxes=handles.axes3;
4484set(huvmat,'UserData',UvData);
4485msgbox_uvmat('CONFIRMATION',{['movie ' aviname ' created '];['with ' num2str(imax) ' frames']})
4486
4487%------------------------------------------------------------------------
4488function MenuCalib_Callback(hObject, eventdata, handles)
4489%------------------------------------------------------------------------
4490
4491UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4492
4493%suppress competing options
4494set(handles.CheckZoom,'Value',0)
4495set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
4496set(handles.ListObject,'Value',1)     
4497% initiate display of GUI geometry_calib
4498data=[]; %default
4499if isfield(UvData,'CoordType')
4500    data.CoordType=UvData.CoordType;
4501end
4502pos=get(handles.uvmat,'Position');
4503pos(1)=pos(1)+pos(3)-0.311+0.04; %0.311= width of the geometry_calib interface (units relative to the srcreen)
4504pos(2)=pos(2)-0.02;
4505[FileName,RootPath,FileBase,FileIndices,FileExt,SubDir]=read_file_boxes(handles);
4506set(handles.view_xml,'Backgroundcolor',[1 1 0])%indicate the reading of the current xml file by geometry_calib
4507if isfield(UvData.OpenParam,'CalOrigin')
4508    pos_uvmat=get(handles.uvmat,'Position');
4509    pos_cal(1)=pos_uvmat(1)+UvData.OpenParam.CalOrigin(1)*pos_uvmat(3);
4510    pos_cal(2)=pos_uvmat(2)+UvData.OpenParam.CalOrigin(2)*pos_uvmat(4);
4511    pos_cal(3:4)=UvData.OpenParam.CalSize .* pos_uvmat(3:4);
4512end
4513geometry_calib(FileName,pos_cal);% call the geometry_calib interface   
4514set(handles.view_xml,'Backgroundcolor',[1 1 1])%indicate the end of reading of the current xml file by geometry_calib
4515set(handles.MenuCalib,'checked','on')% indicate that MenuCalib is activated, test used by mouse action
4516
4517%------------------------------------------------------------------------
4518function MenuMask_Callback(hObject, eventdata, handles)
4519%------------------------------------------------------------------------
4520UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4521ListObj=UvData.Object;
4522select=zeros(1,numel(ListObj));
4523for iobj=1:numel(ListObj);
4524    if strcmp(ListObj{iobj}.ProjMode,'mask_inside')||strcmp(ListObj{iobj}.ProjMode,'mask_outside')
4525        select(iobj)=1;
4526    end
4527end
4528val=find(select);
4529if isempty(val)
4530    msgbox_uvmat('ERROR','polygons must be first created by Projection object/mask polygon in the menu bar');
4531    return
4532else
4533    set(handles.ListObject,'Max',2);%allow multiple selection
4534    set(handles.ListObject,'Value',val);
4535    flag=1;
4536    npx=size(UvData.Field.A,2);
4537    npy=size(UvData.Field.A,1);
4538    xi=0.5:npx-0.5;
4539    yi=0.5:npy-0.5;
4540    [Xi,Yi]=meshgrid(xi,yi);
4541    if isfield(UvData,'Object')
4542        for iobj=1:length(UvData.Object)
4543            ObjectData=UvData.Object{iobj};
4544            if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
4545                flagobj=1;
4546                testphys=0; %coordinates in pixels by default
4547                if isfield(ObjectData,'CoordUnit') && ~isequal(ObjectData.CoordUnit,'pixel')
4548                    if isfield(UvData,'XmlData')&& isfield(UvData.XmlData,'GeometryCalib')
4549                        Calib=UvData.XmlData.GeometryCalib;
4550                        testphys=1;
4551                    end
4552                end
4553                if isfield(ObjectData,'Coord')&& isfield(ObjectData,'Style')
4554                    if isequal(ObjectData.Style,'polygon')
4555                        X=ObjectData.Coord(:,1);
4556                        Y=ObjectData.Coord(:,2);
4557                        if testphys
4558                            [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
4559                        end
4560                        flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside
4561                    elseif isequal(ObjectData.Style,'ellipse')
4562                        if testphys
4563                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4564                        end
4565                        RangeX=max(ObjectData.RangeX);
4566                        RangeY=max(ObjectData.RangeY);
4567                        X2Max=RangeX*RangeX;
4568                        Y2Max=RangeY*RangeY;
4569                        distX=(Xi-ObjectData.Coord(1,1));
4570                        distY=(Yi-ObjectData.Coord(1,2));
4571                        flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
4572                    elseif isequal(ObjectData.Style,'rectangle')
4573                        if testphys
4574                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4575                        end
4576                        distX=abs(Xi-ObjectData.Coord(1,1));
4577                        distY=abs(Yi-ObjectData.Coord(1,2));
4578                        flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
4579                    end
4580                    if isequal(ObjectData.ProjMode,'mask_outside')
4581                        flagobj=~flagobj;
4582                    end
4583                    flag=flag & flagobj;
4584                end
4585            end
4586        end
4587    end
4588    %mask name
4589    RootPath=get(handles.RootPath,'String');
4590    RootFile=get(handles.RootFile,'String');
4591    if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
4592        RootFile(1)=[];
4593    end
4594    filebase=fullfile(RootPath,RootFile);
4595    list=get(handles.masklevel,'String');
4596    masknumber=num2str(length(list));
4597    maskindex=get(handles.masklevel,'Value');
4598    mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
4599    imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
4600    imflag=flipdim(imflag,1);
4601
4602    %display the mask
4603    hfigmask=figure;
4604    set(hfigmask,'Name','mask image')
4605    vec=linspace(0,1,256);%define a linear greyscale colormap
4606    map=[vec' vec' vec'];
4607    colormap(map)
4608    image(imflag);
4609    answer=msgbox_uvmat('INPUT_TXT','mask file name:', mask_name);
4610    if ~strcmp(answer,'Cancel')
4611        mask_dir=fileparts(answer);
4612        if ~exist(mask_dir,'dir')
4613            msgbox_uvmat('ERROR',['directory ' mask_dir ' does not exist'])
4614            return
4615        end
4616        imwrite(imflag,answer,'BitDepth',8);
4617    end
4618    set(handles.ListObject,'Value',1)
4619    set(handles.ListObject,'Max',1)
4620end
4621
4622%------------------------------------------------------------------------
4623%-- open the GUI set_grid.fig to create grid
4624function MenuGrid_Callback(hObject, eventdata, handles)
4625%------------------------------------------------------------------------
4626%suppress the other options if grid is chosen
4627set(handles.edit_vect,'Value',0)
4628edit_vect_Callback(hObject, eventdata, handles)
4629set(handles.edit_object,'BackgroundColor',[0.7 0.7 0.7])
4630set(handles.ListObject,'Value',1)     
4631
4632%prepare display of the set_grid GUI
4633FileName=read_file_boxes(handles);
4634CoordList=get(handles.transform_fct,'String');
4635val=get(handles.transform_fct,'Value');
4636set_grid(FileName,CoordList{val});% call the set_object interface
4637
4638%------------------------------------------------------------------------
4639% open the GUI 'series'
4640function MenuSeries_Callback(hObject, eventdata, handles)
4641%------------------------------------------------------------------------
4642series; %first display of the GUI to fill waiting time
4643[param.FileName]=read_file_boxes(handles);
4644if isequal(get(handles.SubField,'Value'),1)
4645    FileName_1=read_file_boxes_1(handles);%
4646    if ~isequal(FileName_1,param.FileName)
4647        param.FileName_1=FileName_1;
4648    end
4649end
4650param.NomType=get(handles.NomType,'String');
4651% param.NomType=get(handles.FileIndex,'UserData');
4652param.NomType_1=get(handles.NomType_1,'String');
4653% param.NomType_1=get(handles.FileIndex_1,'UserData');
4654param.comp_input=get(handles.fix_pair,'Value');
4655huvmat=get(handles.MenuSeries,'parent');
4656UvData=get(huvmat,'UserData');
4657if isfield(UvData,'Time')
4658    param.Time=UvData.XmlData.Time;
4659end
4660if isequal(get(handles.scan_i,'Value'),1)
4661    param.incr_i=str2double(get(handles.increment_scan,'String'));
4662elseif isequal(get(handles.scan_j,'Value'),1)
4663    param.incr_j=str2double(get(handles.increment_scan,'String'));
4664end
4665param.list_fields=get(handles.Fields,'String');% list menu fields
4666param.list_fields(1)=[]; %suppress  'image' option
4667param.index_fields=get(handles.Fields,'Value');% selected string index
4668if param.index_fields>1
4669    param.index_fields=param.index_fields-1;
4670end
4671param.list_fields_1=get(handles.Fields_1,'String');% list menu fields
4672param.list_fields_1(1)=[]; %suppress  'image' option
4673param.index_fields_1=get(handles.Fields_1,'Value')-1;% selected string index
4674if param.index_fields_1>1
4675    param.index_fields_1=param.index_fields_1-1;
4676end
4677param.menu_coord_str=get(handles.transform_fct,'String');
4678param.menu_coord_val=get(handles.transform_fct,'Value');
4679series(param); %run the series interface
4680
4681%------------------------------------------------------------------------
4682% -- open the GUI civ.fig for civx (PIV)
4683function MenuPIV_Callback(hObject, eventdata, handles)
4684%------------------------------------------------------------------------
4685 FileName=read_file_boxes(handles);
4686%[FileName,RootPath,filebase,FileIndices,ext,SubDir]=read_file_boxes(handles)
4687% num1=stra2num(get(handles.i1,'String'));
4688% num2=stra2num(get(handles.i2,'String'));
4689% num_a=stra2num(get(handles.j1,'String'));
4690% num_b=stra2num(get(handles.j2,'String'));
4691% NomType=get(handles.FileIndex,'UserData');
4692% ind_opening=1; % default (images): will advice civ1 option by default in the civ interface
4693% if isequal(ext,'.nc') ||  isequal(ext,'.cdf')% netcdf files
4694%     ind_opening=2;% propose 'fix' as the default option
4695% % +read the current netcdf rootfile
4696%     Data=nc2struct(FileName,'ListGlobalAttribute','fix','patch','civ2','fix2');
4697%     if isfield(Data,'fix') && isequal(Data.fix,1)
4698%         ind_opening=3;
4699%     end
4700%     if isfield(Data,'patch') && isequal(Data.patch,1)
4701%         ind_opening=4;
4702%     end
4703%     if isfield(Data,'civ2') && isequal(Data.civ2,1)
4704%         ind_opening=5;
4705%     end
4706%     if isfield(Data,'fix2') && isequal(Data.fix2,1)
4707%         ind_opening=6;
4708%     end
4709% end     
4710% param.RootName=filebase;
4711% param.NomType=NomType;
4712% param.num1=num1;
4713% param.num2=num2;
4714% param.num_a=num_a;
4715% param.num_b=num_b;
4716% param.SubDir=SubDir;
4717% param.IndOpening=ind_opening;% A REVOIR +TRANSMETTRE IMADOC INFO
4718% param.ImaExt=ext;
4719civ(FileName);% interface de civ(not in the uvmat file)
4720
4721%------------------------------------------------------------------------
4722function MenuTools_Callback(hObject, eventdata, handles)
4723%------------------------------------------------------------------------
4724
4725%------------------------------------------------------------------------
4726function MenuEditObject_Callback(hObject, eventdata, handles)
4727%------------------------------------------------------------------------
4728set(handles.edit_object,'Value',1)
4729edit_Callback(hObject, eventdata, handles)
4730
4731%------------------------------------------------------------------------
4732function enable_transform(handles,state)
4733%------------------------------------------------------------------------
4734set(handles.transform_fct,'Visible',state)
4735set(handles.TRANSFORM_txt,'Visible',state)   
4736set(handles.transform_fct,'Visible',state) 
4737set(handles.path_transform,'Visible',state)
4738set(handles.pxcmx_txt,'Visible',state)
4739set(handles.pxcmy_txt,'Visible',state)
4740set(handles.pxcm,'Visible',state)
4741set(handles.pycm,'Visible',state)
4742
4743%------------------------------------------------------------------------
4744function MenuEditVectors_Callback(hObject, eventdata, handles)
4745%------------------------------------------------------------------------
4746set(handles.edit_vect,'Visible','on')
4747set(handles.edit_vect,'Value',1)
4748edit_vect_Callback(hObject, eventdata, handles)
4749
4750% -----------------------------------------------------------------------
4751function Menupoints_Callback(hObject, eventdata, handles)
4752%------------------------------------------------------------------------
4753data.Style='points';
4754data.ProjMode='projection';%default
4755create_object(data,handles)
4756
4757% -----------------------------------------------------------------------
4758function Menuline_Callback(hObject, eventdata, handles)
4759%------------------------------------------------------------------------
4760data.Style='line';
4761data.ProjMode='projection';%default
4762create_object(data,handles)
4763
4764%------------------------------------------------------------------------
4765function Menupolyline_Callback(hObject, eventdata, handles)
4766%------------------------------------------------------------------------
4767data.Style='polyline';
4768data.ProjMode='projection';%default
4769create_object(data,handles)
4770
4771%------------------------------------------------------------------------
4772function Menupolygon_Callback(hObject, eventdata, handles)
4773%------------------------------------------------------------------------
4774data.Style='polygon';
4775data.ProjMode='inside';%default
4776create_object(data,handles)
4777
4778%------------------------------------------------------------------------
4779function Menurectangle_Callback(hObject, eventdata, handles)
4780%------------------------------------------------------------------------
4781data.Style='rectangle';
4782data.ProjMode='inside';%default
4783create_object(data,handles)
4784
4785%------------------------------------------------------------------------
4786function Menuellipse_Callback(hObject, eventdata, handles)
4787%------------------------------------------------------------------------
4788data.Style='ellipse';
4789data.ProjMode='inside';%default
4790create_object(data,handles)
4791
4792%------------------------------------------------------------------------
4793function MenuMaskObject_Callback(hObject, eventdata, handles)
4794%------------------------------------------------------------------------
4795data.Style='polygon';
4796data.StyleMenu={'polygon'};
4797data.ProjMode='mask_inside';%default
4798data.ProjMenu={'mask_inside';'mask_outside'};
4799create_object(data,handles)
4800
4801%------------------------------------------------------------------------
4802function Menuplane_Callback(hObject, eventdata, handles)
4803%------------------------------------------------------------------------
4804data.Style='plane';
4805data.ProjMode='projection';%default
4806
4807create_object(data,handles)
4808
4809%------------------------------------------------------------------------
4810function Menuvolume_Callback(hObject, eventdata, handles)
4811%------------------------------------------------------------------------
4812data.Style='volume';
4813data.ProjMode='interp';%default
4814% set(handles.create,'Visible','on')
4815% set(handles.create,'Value',1)
4816% VOLUME_Callback(hObject,eventdata,handles)
4817create_object(data,handles)
4818
4819%------------------------------------------------------------------------
4820function MenuBrowseObject_Callback(hObject, eventdata, handles)
4821%------------------------------------------------------------------------
4822%get the object file
4823[FileName, PathName, filterindex] = uigetfile( ...
4824       {'*.xml;*.mat', ' (*.xml,*.mat)';
4825       '*.xml',  '.xml files '; ...
4826        '*.mat',  '.mat matlab files '}, ...
4827        'Pick an xml Object file',get(handles.RootPath,'String'));
4828fileinput=[PathName FileName];%complete file name
4829% testblank=findstr(fileinput,' ');%look for blanks
4830% if ~isempty(testblank)
4831%     msgbox_uvmat('ERROR','forbidden input file name: contain blanks')
4832%     return
4833% end
4834sizf=size(fileinput);
4835if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
4836
4837%read the file
4838t=xmltree(fileinput);
4839data=convert(t);
4840data.enable_plot=1;
4841[pp,data.Name]=fileparts(FileName);
4842%PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
4843hset_object=findobj(allchild(0),'tag','set_object');
4844if ~isempty(hset_object)
4845    delete(hset_object)% delete existing version of set_object
4846end
4847% UvData=get(handles.uvmat,'UserData');
4848set_object(data);% call the set_object interface
4849% %position the set_object GUI with respect to uvmat
4850% pos_uvmat=get(handles.uvmat,'Position');
4851% if isfield(UvData,'SetObjectOrigin')
4852%     pos_set_object(1:2)=UvData.SetObjectOrigin + pos_uvmat(1:2);
4853%     pos_set_object(3:4)=UvData.SetObjectSize .* pos_uvmat(3:4);
4854%     set(hset_object,'Position',pos_set_object)
4855% end
4856set(handles.edit_object,'Value',0); %suppress the object edit mode
4857set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4858set(handles.MenuObject,'checked','on')
4859%UvData.MouseAction='create_object';
4860% set(handles.uvmat,'UserData',UvData)
4861set(handles.delete_object,'Visible','on')
4862% set(handles.uvmat_title,'Visible','on')
4863% set(handles.view_field_title,'Visible','on')
4864
4865%------------------------------------------------------------------------
4866% --- generic function used for the creation of a projection object
4867function create_object(data,handles)
4868%------------------------------------------------------------------------
4869hset_object=findobj(allchild(0),'tag','set_object');
4870if ~isempty(hset_object)
4871    delete(hset_object)% delete existing version of set_object
4872end
4873hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4874if ishandle(hgeometry_calib)
4875    hhgeometry_calib=guidata(hgeometry_calib);
4876    set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4877    set(hhgeometry_calib.edit_append,'BackgroundColor',[0.7 0.7 0.7])
4878end
4879UvData=get(handles.uvmat,'UserData');
4880set(handles.edit_object,'Value',0); %suppress the object edit mode
4881set(handles.edit_object,'BackgroundColor',[0.7,0.7,0.7]) 
4882data.enable_plot=1;
4883transform_list=get(handles.transform_fct,'String');
4884val=get(handles.transform_fct,'Value');
4885%data.CoordType=transform_list{val};
4886if isfield(UvData,'Field')
4887    Field=UvData.Field;
4888    if isfield(Field,'Mesh')&&~isempty(Field.Mesh)
4889        data.RangeX=Field.Mesh;
4890        data.RangeY=Field.Mesh;
4891        data.DX=Field.Mesh;
4892        data.DY=Field.Mesh;
4893    elseif isfield(Field,'AX')&& isfield(Field,'AY')&& isfield(Field,'A')%only image
4894        np=size(Field.A);
4895        meshx=(Field.AX(end)-Field.AX(1))/np(2);
4896        meshy=abs(Field.AY(end)-Field.AY(1))/np(1);
4897        data.RangeY=max(meshx,meshy);
4898        data.RangeX=max(meshx,meshy);
4899        data.DX=max(meshx,meshy);
4900    end
4901    if isfield(Field,'NbDim')
4902        data.NbDim=Field.NbDim;
4903    end
4904    if isfield(Field,'CoordUnit')
4905        data.CoordUnit=Field.CoordUnit;
4906    end
4907end
4908data.Coord=[0 0 0]; %default
4909if isfield(data,'Style') && isequal(data.Style,'line')
4910    if isfield(data,'DX')
4911        data.Coord=[[0 0 0];[data.DX 0 0]]; %default
4912    else
4913        data.Coord=[[0 0 0];[1 0 0]]; %default
4914    end
4915end
4916if ishandle(handles.UVMAT_title)
4917    delete(handles.UVMAT_title)%delete the initial display of uvmat if no field has been entered
4918end
4919%PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
4920set_object(data,handles);% call the set_object interface
4921set(handles.MenuObject,'checked','on')
4922set(handles.uvmat,'UserData',UvData)
4923set(handles.CheckZoom,'Value',0)
4924CheckZoom_Callback(handles.uvmat, [], handles)
4925set(handles.delete_object,'Visible','on')
4926% set(handles._title,'Visible','on')
4927% set(handles.view_field_title,'Visible','on')
4928
4929%------------------------------------------------------------------------
4930function MenuRuler_Callback(hObject, eventdata, handles)
4931%------------------------------------------------------------------------
4932set(handles.CheckZoom,'Value',0)
4933CheckZoom_Callback(handles.uvmat, [], handles)
4934set(handles.MenuRuler,'checked','on')
4935UvData=get(handles.uvmat,'UserData');
4936UvData.MouseAction='ruler';
4937set(handles.uvmat,'UserData',UvData);
4938
4939%------------------------------------------------------------------------
4940% --- executed when closing: set the parent interface button to value 0
4941function closefcn(gcbo,eventdata)
4942%------------------------------------------------------------------------
4943%delete all the associated figures if exist
4944hh=findobj(allchild(0),'tag','view_field');
4945if ~isempty(hh)
4946    delete(hh)
4947end
4948hh=findobj(allchild(0),'tag','geometry_calib');
4949if ~isempty(hh)
4950    delete(hh)
4951end
4952hh=findobj(allchild(0),'tag','set_object');
4953if ~isempty(hh)
4954    hhh=findobj(hh,'tag','PLOT');
4955    set(hhh,'enable','off')
4956end
4957
4958%------------------------------------------------------------------------
4959% --- Executes on button press in delete_object.
4960function delete_object_Callback(hObject, eventdata, handles)
4961%------------------------------------------------------------------------
4962IndexObj=get(handles.ListObject,'Value');
4963if IndexObj(end)>1
4964    delete_object(IndexObj(end))
4965end
4966
4967% --- Executes on button press in FixVelType.
4968function FixVelType_Callback(hObject, eventdata, handles)
4969val=get(handles.FixVelType,'Value');
4970if ~val
4971    run0_Callback(hObject, eventdata, handles)
4972end
4973
4974
4975% --- Executes on button press in ViewObject.
4976function ViewObject_Callback(hObject, eventdata, handles)
4977IndexObj=get(handles.ListObject,'Value');
4978IndexObj=IndexObj(end); %keeps only the secodn value
4979UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4980if numel(UvData.Object)<IndexObj;% error in UvData
4981    msgbox_uvmat('ERROR','invalid object list')
4982    return
4983end
4984ObjectData=UvData.Object{IndexObj};
4985ZBounds=0; % default
4986if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4987    ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4988    ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4989end
4990hset_object=findobj(allchild(0),'tag','set_object');
4991if ~isempty(hset_object)
4992    delete(hset_object)% delete existing version of set_object
4993end
4994hset_object=set_object(ObjectData,[],ZBounds);
4995
4996
4997
4998function NomType_Callback(hObject, eventdata, handles)
4999
5000
5001function NomType_1_Callback(hObject, eventdata, handles)
5002
Note: See TracBrowser for help on using the repository browser.