source: trunk/src/uvmat.m @ 319

Last change on this file since 319 was 319, checked in by sommeria, 9 years ago

civ: bugs for displacement mode repaired
civ and civ_matlab prepared for batch in Matlab (file .civ.xml created)

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