source: trunk/src/uvmat.m @ 334

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

bugs corrected in fileparts_uvmat and find_file_series
name2dispaly replaced by fileparts_uvmat in uvmat, but not in other functions
bug corrected in plot_field, introduction of FileType? in read_field

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