source: trunk/src/uvmat.m @ 342

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

various bugs corrected

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