source: trunk/src/civ.m @ 446

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

series rationalized. TO BE TESTED.

File size: 192.7 KB
Line 
1
2%'civ': function associated with the interface 'civ.fig' for PIV, spline interpolation and stereo PIV (patch)
3%------------------------------------------------------------------------
4%  provides an interface for the software menucivx
5% function varargout = civ(varargin)
6% provides an interface for the software menucivx
7%
8%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
9%  Copyright Joel Sommeria, 2011, LEGI / CNRS-UJF-INPG, sommeria@legi.grenoble-inp.fr
10%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
11%     This file is part of the toolbox UVMAT.
12%
13%     UVMAT is free software; you can redistribute it and/or modify
14%     it under the terms of the GNU General Public License as published by
15%     the Free Software Foundation; either version 2 of the License, or
16%     (at your option) any later version.
17%
18%     UVMAT is distributed in the hope that it will be useful,
19%     but WITHOUT ANY WARRANTY; without even the implied warranty of
20%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
22%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
23function varargout = civ(varargin)
24%TODO: search range
25
26% Last Modified by GUIDE v2.5 03-Jun-2012 22:16:42
27% Begin initialization code - DO NOT EDIT
28gui_Singleton = 1;
29gui_State = struct('gui_Name',       mfilename, ...
30    'gui_Singleton',  gui_Singleton, ...
31    'gui_OpeningFcn', @civ_OpeningFcn, ...
32    'gui_OutputFcn',  @civ_OutputFcn, ...
33    'gui_LayoutFcn',  [] , ...
34    'gui_Callback',   []);
35if nargin && ischar(varargin{1}) && ~isempty(regexp(varargin{1},'_Callback$','once'))
36    gui_State.gui_Callback = str2func(varargin{1});
37end
38
39if nargout
40    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
41else
42    gui_mainfcn(gui_State, varargin{:});
43end
44% End initialization code - DO NOT EDIT
45
46%------------------------------------------------------------------------
47% --- Executes just before civ is made visible.
48function civ_OpeningFcn(hObject, eventdata, handles, fileinput)
49%------------------------------------------------------------------------
50% This function has no output args, see OutputFcn.
51
52%% General settings
53handles.output = hObject;
54guidata(hObject, handles); % Update handles structure
55set(hObject,'WindowButtonDownFcn',{'mouse_down'}) % allows mouse action with right button (zoom for uicontrol display)
56
57%% Adjust the GUI according to the binaries available in PARAM.xml
58path_civ=fileparts(which('civ')); %path to civ
59addpath (path_civ) ; %add the path to civ, (useful in case of change of working directory after civ has been s opened in the working directory)
60errormsg=[];%default error message
61xmlfile='PARAM.xml';
62if exist(xmlfile,'file')
63    try
64        t=xmltree(xmlfile);
65        sparam=convert(t);
66    catch ME
67        errormsg={' Unable to read the file PARAM.xml defining the civx binaries:';ME.message};
68    end
69else
70    errormsg=[xmlfile ' not found: path to civx binaries undefined'];
71end
72if ~isempty(errormsg)
73    msgbox_uvmat('WARNING',errormsg);
74end
75test_batch=0;%default: ,no batch mode available
76if isfield(sparam,'BatchParam') && isfield(sparam.BatchParam,'BatchMode')
77    test_batch=strcmp(sparam.BatchParam.BatchMode,'sge'); %sge is currently the only implemented batch mod
78end
79if test_batch==0
80    set(handles.BATCH,'Enable','off')% put the BATCH button in grey (unactivated)
81    set(handles.BATCH,'BackgroundColor',[0.831 0.816 0.784])% put the BATCH button in grey (unactivated)
82end
83if isfield(sparam.RunParam,'CivBin')
84    if ~exist(sparam.RunParam.CivBin,'file')
85        sparam.RunParam.CivBin=fullfile(path_civ,sparam.RunParam.CivBin);
86    end
87else
88    sparam.RunParam.CivBin='';
89end
90
91%% load the list of previously browsed files in the upper bar menu Open/
92dir_perso=prefdir; % path to the directory .matlab for personal data
93profil_perso=fullfile(dir_perso,'uvmat_perso.mat');% personal data file uvmauvmat_perso.mat' in .matlab
94if exist(profil_perso,'file')
95    h=load (profil_perso);
96    if isfield(h,'MenuFile')
97        for ifile=1:min(length(h.MenuFile),5)
98            eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',h.MenuFile{ifile});'])
99        end
100    end
101end
102
103%% prepare the GUI with parameters from the input file if opened from uvmat
104if exist('fileinput','var')% && isfield(param,'RootName') && ~isempty(param.RootName)
105    set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
106    errormsg=display_file_name(handles,fileinput);
107    if ~isempty(errormsg)
108        msgbox_uvmat('ERROR',errormsg)
109    end
110    set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
111end
112
113%------------------------------------------------------------------------
114% --- Outputs from this function are returned to the command line.
115function varargout = civ_OutputFcn(hObject, eventdata, handles)
116%------------------------------------------------------------------------
117% Get default command line output from handles structure
118varargout{1} = handles.output;
119
120%------------------------------------------------------------------------
121% --- Function activated by the Open/Browse... option in the upper menu bar.
122function MenuBrowse_Callback(hObject, eventdata, handles)
123%------------------------------------------------------------------------
124%% get the current input root file name to initiate the browser
125filebase=get(handles.RootPath,'String');
126oldfile=''; %default
127if isempty(filebase)|| isequal(filebase,'')%loads the previously stored root file name
128    dir_perso=prefdir;
129    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
130    if exist(profil_perso,'file')
131        h=load (profil_perso);
132        if isfield(h,'filebase')&& ischar(h.filebase)
133            oldfile=h.filebase;
134        end
135        if isfield(h,'RootPath') && ischar(h.RootPath)
136            oldfile=h.RootPath;
137        end
138    end
139else
140    oldfile=filebase;
141end
142
143%% get the new input file with the browser
144menu={'*.xml;*.civ;*.png;*.jpg;*.tif;*.avi;*.AVI;*.nc;', ' (*.xml,*.civ,*.png,*.jpg ,.tif, *.avi,*.nc)';
145    '*.xml',  '.xml files '; ...
146    '*.civ',  '.civ files '; ...
147    '*.png','.png image files'; ...
148    '*.jpg',' jpeg image files'; ...
149    '*.tif','.tif image files'; ...
150    '*.avi;*.AVI','.avi movie files'; ...
151    '*.nc','.netcdf files'; ...
152    '*.*',  'All Files (*.*)'};
153[FileName, PathName, filtindex] = uigetfile( menu, 'Pick a file',oldfile);
154fileinput=[PathName FileName];%complete file name
155sizf=size(fileinput);
156if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
157
158%% case of the xml file opened as input (TODO: check and see whether it is useful)
159[path,name,ext]=fileparts(fileinput);
160testeditxml=0;
161% if isequal(ext,'.xml')
162%     testeditxml=1;
163%     t_browse=xmltree(fileinput);
164%     head_element=get(t_browse,1);
165%     if isfield(head_element,'name')&& isequal(head_element.name,'ImaDoc')
166%         testeditxml=0;
167%     end
168% end
169% if testeditxml==1 || isequal(ext,'.xls')
170%     heditxml=editxml({fileinput});
171%     set(heditxml,'Tag','browser')
172%     waitfor(heditxml,'Tag','idle')
173%     if ~ishandle(heditxml)
174%         return
175%     end
176%     attr=findobj(get(heditxml,'children'),'Tag','CurrentAttributes');
177%     set(handles.browse,'UserData',fileinput)% store for future opening with browser
178%     fileinput=get(attr,'UserData');
179%     if ~exist(fileinput,'file')
180%         return
181%     end
182% end
183[tild,tild,tild,i1,i2,j1,j2,FileExt,NomType]=fileparts_uvmat(fileinput);
184
185%% prepare the GUI with parameters from the input file
186set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
187errormsg=display_file_name(handles,fileinput);
188if ~isempty(errormsg)
189    msgbox_uvmat('ERROR',erromsg)
190end
191set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
192
193%------------------------------------------------------------------------
194% --- Open again the file whose name has been recorded in MenuFile_1
195function MenuFile_1_Callback(hObject, eventdata, handles)
196%------------------------------------------------------------------------
197set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
198fileinput=get(handles.MenuFile_1,'Label');
199errormsg=display_file_name(handles,fileinput);
200if ~isempty(errormsg)
201    msgbox_uvmat('ERROR',errormsg)
202end
203set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
204
205% -----------------------------------------------------------------------
206% --- Open again the file whose name has been recorded in MenuFile_2
207function MenuFile_2_Callback(hObject, eventdata, handles)
208%------------------------------------------------------------------------
209set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
210fileinput=get(handles.MenuFile_2,'Label');
211errormsg=display_file_name(handles,fileinput);
212if ~isempty(errormsg)
213    msgbox_uvmat('ERROR',errormsg)
214end
215set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
216
217% -----------------------------------------------------------------------
218% --- Open again the file whose name has been recorded in MenuFile_3
219function MenuFile_3_Callback(hObject, eventdata, handles)
220%------------------------------------------------------------------------
221set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
222fileinput=get(handles.MenuFile_3,'Label');
223errormsg=display_file_name(handles,fileinput);
224if ~isempty(errormsg)
225    msgbox_uvmat('ERROR',errormsg)
226end
227set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
228
229% -----------------------------------------------------------------------
230% --- Open again the file whose name has been recorded in MenuFile_4
231function MenuFile_4_Callback(hObject, eventdata, handles)
232%------------------------------------------------------------------------
233set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
234fileinput=get(handles.MenuFile_4,'Label');
235errormsg=display_file_name(handles,fileinput);
236if ~isempty(errormsg)
237    msgbox_uvmat('ERROR',errormsg)
238end
239set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
240
241% -----------------------------------------------------------------------
242% --- Open again the file whose name has been recorded in MenuFile_5
243function MenuFile_5_Callback(hObject, eventdata, handles)
244%------------------------------------------------------------------------
245set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
246fileinput=get(handles.MenuFile_5,'Label');
247errormsg=display_file_name(handles,fileinput);
248if ~isempty(errormsg)
249    msgbox_uvmat('ERROR',errormsg)
250end
251set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
252
253% -----------------------------------------------------------------------
254% -----------------------------------------------------------------------
255% --- Open the help html file
256function MenuHelp_Callback(hObject, eventdata, handles)
257% -----------------------------------------------------------------------
258path_civ=fileparts(which ('civ'));
259helpfile=fullfile(path_civ,'uvmat_doc','uvmat_doc.html');
260if isempty(dir(helpfile))
261    msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
262else
263    addpath (fullfile(path_civ,'uvmat_doc'))
264    web([helpfile '#civ'])
265end
266
267%------------------------------------------------------------------------
268% --- Function activated when a new filebase (image series) is introduced
269function RootPath_Callback(hObject, eventdata, handles)
270%------------------------------------------------------------------------
271set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
272RootPath=get(handles.RootPath,'String');
273SubdirImages=get(handles.SubdirImages,'String');
274RootFile=get(handles.RootFile,'String');
275ref_i=str2num(get(handles.ref_i,'String'));
276ref_j=str2num(get(handles.ref_j,'String'));
277NomType=get(handles.NomType,'String');
278ImaExt=get(handles.ImaExt,'String');
279fileinput=fullfile_uvmat(RootPath,SubdirImages,RootFile,ImaExt,NomType,ref_i,[],ref_j);
280errormsg=display_file_name(handles,fileinput);
281if ~isempty(errormsg)
282    msgbox_uvmat('ERROR',errormsg)
283end
284set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
285
286%------------------------------------------------------------------------
287% --- general function activated for an input file series
288function errormsg=display_file_name(handles,fileinput)
289%------------------------------------------------------------------------
290set(handles.ListCompareMode,'Visible','on')
291errormsg='';%default empty error message
292drawnow
293
294%% enable RUN, BATCH button and 'status' display
295set(handles.RUN, 'Enable','On')
296set(handles.RUN,'BackgroundColor',[1 0 0])%set RUN button to red color
297set(handles.BATCH,'Enable','On')
298set(handles.BATCH,'BackgroundColor',[1 0 0])%set BATCH button to red color
299if isfield(handles,'status')
300    set(handles.status,'Value',0);       %suppress the 'status' display
301    status_Callback([], [], handles)
302end
303
304%% determine nomenclature types and extension of the input files
305[RootPath,SubDir,RootFile,i1,i2,j1,j2,ExtInput,NomTypeInput]=fileparts_uvmat(fileinput);
306NomTypeNc='';%default
307
308%% case of xml file as input, read the civ parameters
309ind_opening=0;%default
310if strcmp(ExtInput,'.xml')
311    Param=xml2struct(fileinput);
312    fill_GUI(Param,handles);%fill the GUI with the parameters retrieved from the xml file
313    return
314end
315
316%% case of netcdf file as input, get the civ processing stage and look for a coresponding image
317if strcmp(ExtInput,'.nc')
318    NomTypeNc=NomTypeInput;
319    if isempty(regexp(NomTypeInput,'[ab|AB|-]'))
320        set(handles.ListCompareMode,'Value',2) %mode displacement advised if the nomencalture does not involve index pairs
321      %  [RootPath,SubDir]=fileparts(RootPath);
322        set(handles.RootFile_1,'Visible','On');
323    else
324        set(handles.ListCompareMode,'Value',1)
325        set(handles.RootFile_1,'Visible','Off');
326    end
327    Data=nc2struct(fileinput,'ListGlobalAttribute','Conventions','absolut_time_T0','CivStage','Civ2_ImageA','Civ1_ImageA','Civ2_ImageB','Civ1_ImageB','fix','patch','civ2','fix2');
328    if isfield(Data,'Txt')
329        errormsg=Data.Txt;
330        return
331    end
332    % settings for  new civ data,
333    if strcmp(Data.Conventions,'uvmat/civdata')% case of new civ data,
334        set(handles.ListProgram,'Value',2) %select civ/Matlab by default
335        ListProgram_Callback([],[], handles)
336        if ~isempty(Data.CivStage)%test for civ files
337            ind_opening=Data.CivStage;
338        end
339        if  ~isempty(Data.Civ2_ImageB)%get the corresponding input image in the netcdf file
340            imageinput=Data.Civ2_ImageB;
341            [tild,ImaName,ImaExt]=fileparts(Data.Civ2_ImageA);
342            set(handles.RootFile_1,'String',[ImaName ImaExt])
343        elseif ~isempty(Data.Civ1_ImageB)
344            imageinput=Data.Civ1_ImageB;
345            [tild,ImaName,ImaExt]=fileparts(Data.Civ1_ImageA);
346            set(handles.RootFile_1,'String',[ImaName ImaExt])
347        end
348        % settings for civx data,
349    elseif ~isempty(Data.absolut_time_T0')% case of  civx data,
350        set(handles.ListProgram,'Value',1) %select Cix by default
351        ListProgram_Callback([],[], handles)
352        if ~isempty(Data.fix2)
353            ind_opening=5;
354        elseif ~isempty(Data.civ2)
355            ind_opening=4;
356        elseif ~isempty(Data.patch)
357            ind_opening=3;
358        elseif ~isempty(Data.fix)
359            ind_opening=2;
360        end
361    else
362        errormsg='the input netcdf file is not civ data';
363        return
364    end
365    % look for the corresponding input images
366    check_letter=~isempty(regexp(NomTypeInput,'[ab|AB]$','once'));%detect pair label by letter
367    NomTypeIma=NomTypeInput;
368    if check_letter
369        NomTypeIma=NomTypeInput(1:end-1);
370    else
371        r=regexp(NomTypeIma,'.-(?<num2>\d+)$','names');
372        if ~isempty(r)
373            NomTypeIma=regexprep(NomTypeIma,['-' r.num2],'');
374        end
375        r=regexp(NomTypeIma,'.-(?<num2>\d+)','names');
376        if ~isempty(r)
377            NomTypeIma=regexprep(NomTypeIma,['-' r.num2],'');
378        end
379    end
380    imageinput=fullfile_uvmat(RootPath,regexprep(SubDir,'.civ(_?)(\d*)$',''),RootFile,'.png',NomTypeIma,i1,[],j1);
381end
382
383%no corresponding image found, select manually with the browser
384ImaExt=ExtInput;
385if ~isempty(NomTypeNc)
386    %no corresponding image found, select manually with the browser
387    if ~exist(imageinput,'file')
388        menu={'*.png;*.jpg;*.tif;*.avi;*.AVI', '(*.png,*.jpg ,*.tif, *.avi,*.AVI)';
389            '*.png','.png image files'; ...
390            '*.jpg',' jpeg image files'; ...
391            '*.tif','.tif image files'; ...
392            '*.avi;*.AVI','.avi movie files'; ...
393            '*.*',  'All Files (*.*)'};
394        [FileName, PathName] = uigetfile( menu, 'Pick an input image file',fileparts(fileparts(fileinput)));
395        imageinput=[PathName FileName];%complete file name
396     
397    end   
398    fileinput=imageinput;
399end
400
401%% scan the image file series
402[FilePath,FileName,ImaExt]=fileparts(fileinput);
403% detect the file type, get the movie object if relevant, and look for the corresponding file series:
404% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
405[RootPath,SubdirImages,RootFile,i1_series,tild,j1_series,tild,NomTypeIma,FileType,Object,i1,i2,j1,j2]=find_file_series(FilePath,[FileName ImaExt]);
406
407switch FileType
408    case {'image','multimage','video','mmreader'}
409    otherwise
410        errormsg='invalid input file: enter an image, a movie or civ .nc file';
411        return
412end
413set(handles.RootPath,'String',RootPath)
414set(handles.SubdirImages,'String',SubdirImages)
415set(handles.RootFile,'String',RootFile)
416if strcmp(ExtInput,'.nc')
417    SubDirCiv=regexprep(SubDir,[SuddirImages '^'],'');%suppress the root  SuddirImages;
418else
419    SubDirCiv= '.civ';
420end
421set(handles.SubdirCiv1,'String',SubDirCiv)
422set(handles.SubdirCiv2,'String',SubDirCiv)
423browse=get(handles.RootPath,'UserData');
424browse.incr_pair=[0 0];%default
425
426%% fill reference indices from the input file indices
427num_ref_i=i1;%efaulmt ref index
428if ~isempty(i2)
429    num_ref_i=floor((num_ref_i+i2)/2);
430end
431num_ref_j=j1;
432if ~isempty(j2)
433    num_ref_j=floor((num_ref_j+j2)/2);
434end
435
436%% scan the images if a civ file has been opened
437MinIndex_i=min(i1_series(i1_series>0));
438MinIndex_j=min(j1_series(j1_series>0));
439MaxIndex_i=max(i1_series(i1_series>0));
440MaxIndex_j=max(j1_series(j1_series>0));
441
442%% look for an image documentation file
443ext_imadoc='';%default
444SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
445filexml=fullfile(RootPath,[SubDirBase '.xml']);% new convention: xml above the image dir
446if ~exist(filexml,'file')
447    filexml=fullfile(RootPath,SubDir,[RootFile '.xml']);%old convention: xml within the image directroy
448end
449RootName=fullfile(RootPath,RootFile);
450if exist(filexml,'file')
451    ext_imadoc='.xml';
452elseif exist(fullfile(RootPath,SubDir,[RootFile '.civ']),'file')
453    ext_imadoc='.civ';
454    fileciv=fullfile(RootPath,SubDir,[RootFile '.civ']);
455elseif exist([RootName '.avi'],'file')
456    ext_imadoc='.avi';
457elseif exist([RootName '.AVI'],'file')
458    ext_imadoc='.AVI';
459end
460set(handles.ImaDoc,'String',ext_imadoc)% display the extension name for the image documentation file used
461
462%%  read the time in the image documentation file 
463time=[];
464TimeUnit=''; %default
465CoordUnit='';%default
466pxcm_search=1;
467if ~isempty(ext_imadoc)
468    set(handles.ImaDoc,'BackgroundColor',[1 1 0]) % set edit box to yellow cloro to indicate that the file reading is beginning
469    drawnow
470    switch ext_imadoc
471        case '.xml'
472            [XmlData,warntext]=imadoc2struct(filexml);
473            ext_ima_read=[];
474            nom_type_read=[];
475            if isfield(XmlData,'Heading')&&isfield(XmlData.Heading','ImageName')&&ischar(XmlData.Heading.ImageName)% get image nom type and extension from the xml file
476                %[PP,FF,fc,str2,str_a,str_b,ext_ima_read,nom_type_read]=name2display(XmlData.Heading.ImageName);
477                [tild,tild,tild,tild,tild,tild,tild,tild,nom_type_read]=fileparts_uvmat(XmlData.Heading.ImageName);
478                fullname=fullfile(fileparts(RootName),XmlData.Heading.ImageName); %full name (including path) of the first image defined by the xmle file,
479                if ~exist(fullname,'file')
480                    msgbox_uvmat('WARNING',['FirstImage ' fullname ' defined in the xml file does not exist'])
481                end
482            end
483            if isfield(XmlData,'Time')
484                time=XmlData.Time;
485                %transform .Time to a column vector if it is a line vector thenomenclature uses a single index: correct possible bug in xml
486                if isequal(MaxIndex_i,1) && ~isequal(MaxIndex_j,1)% .Time is a line vector
487                    if numel(nom_type_read)>=2 && isempty(regexp(nom_type_read(2:end),'\D','once'))
488                        time=time';
489                        MaxIndex_i=MaxIndex_j;
490                        MaxIndex_j=1;
491                    end
492                end
493            end
494            if isfield(XmlData,'TimeUnit')
495                TimeUnit=XmlData.TimeUnit;
496            end
497
498            if isfield(XmlData,'GeometryCalib')
499                tsai=XmlData.GeometryCalib;
500                if isfield(tsai,'fx_fy') 
501                    pxcm_search=max(tsai.fx_fy(1),tsai.fx_fy(2));%pixels:cm estimated for the search range
502                end
503                if isfield(tsai,'CoordUnit')
504                    CoordUnit=tsai.CoordUnit;
505                end
506            end
507        case '.civ'% OBSOLETE: case of .civ image documentation file
508            [error,time,TimeUnit,mode,npx,npy]=read_imatext(fileciv);
509            if error==2, msgbox_uvmat('WARNING',['no file ' fileciv]);
510            elseif error==1, msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
511            end
512            nom_type_ima='001a';
513        case {'.avi','.AVI'}
514            nom_type_ima='*';
515            ImaExt=ext_imadoc;
516            set(handles.ListPairMode,'Value',1);
517            set(handles.ListPairMode,'String',{'series(Di)'})
518            dt=0.04;%default
519            if exist([RootName ext_imadoc],'file')==2
520                hhh=which('videoreader');
521                if isempty(hhh)%use old video function of matlab
522                    imainfo=aviinfo([RootName ext_imadoc]);%read infos on the avi movie TO REPLACE mmreader
523                    dt=1/imainfo.FramesPerSecond;%time interval between successive frames
524                    MaxIndex_i=imainfo.NumFrames;%number of frames
525                    %         XmlData.Time=(0:1/imainfo.FramesPerSecond:(imainfo.NumFrames-1)/imainfo.FramesPerSecond)';
526                    %         nbfield=imainfo.NumFrames;
527                    %         set(handles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FramesPerSecond) 'ms']);%display the elementary time interval in millisec
528                    %         ColorType=imainfo.ImageType;%='truecolor' for color images
529                else %use video function videoreader of matlab
530                    imainfo=get(videoreader([RootName ext_imadoc]));%read infos on the avi movie
531                    dt=1/imainfo.FrameRate;%time interval between successive frames
532                    MaxIndex_i=imainfo.NumberOfFrames;%number of frames
533                    %         XmlData.Time=(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames-1)/imainfo.FrameRate)';
534                    %         nbfield=imainfo.NumberOfFrames;
535                    %         set(handles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FrameRate) 'ms']);%display the elementary time interval in millisec
536                    %         ColorType='truecolor';
537                end
538               
539                time=(dt*(0:MaxIndex_i-1))';%list of image times
540                TimeUnit='s';
541            end
542            set(handles.ImaDoc,'BackgroundColor',[1 1 1])% set display box back to whiter
543    end
544end
545%% timing display
546%show the reference image edit box if relevant (not needed for movies or in the absence of time information
547if numel(time)>=2 % if there are at least two time values to define dt
548    MaxIndex_i=min(size(time,1),MaxIndex_i);
549    MaxIndex_j=min(size(time,2),MaxIndex_j);
550    time=[zeros(size(time,1),1) time]; %insert a vertical line of zeros (to deal with zero file indices)
551    time=[zeros(1,size(time,2)); time]; %insert a horizontal line of zeros
552    set(handles.ImaDoc,'UserData',time); %store the matrix of times
553    set(handles.dt_unit,'String',['dt in m' TimeUnit]);
554    set(handles.TimeUnit,'String',TimeUnit);
555else
556    set(handles.ImaDoc,'String',''); %xml file not used for timing
557    time=(i1_series(:,1)+0:size(i1_series,1)-1);% time=index i
558    time=time'*ones(1,size(i1_series,2),1); %makes a time matrix with the same time for all j indices
559    TimeUnit='frame';
560end
561set(handles.ImaDoc,'UserData',time); %store the matrix of times
562set(handles.dt_unit,'String',['dt in m' TimeUnit]);%display dt in unit 10-3 of the time (e.g ms)
563set(handles.TimeUnit,'String',TimeUnit);
564set(handles.nb_field,'String',num2str(MaxIndex_i));
565set(handles.nb_field2,'String',num2str(MaxIndex_j));
566set(handles.CoordUnit,'String',CoordUnit)
567set(handles.SearchRange,'UserData', pxcm_search);
568set(handles.ImaExt,'String',ImaExt)
569set(handles.NomType,'String',NomTypeIma)
570set(handles.ref_i,'String',num2str(num_ref_i))
571set(handles.ref_j,'String',num2str(num_ref_j))
572
573%% update i and j index range if a nc file has been opened or pb withmin max image indices:
574% then set first and last to the inputfile index by default
575first_i=str2num(get(handles.first_i,'String'));
576last_i=str2num(get(handles.last_i,'String'));
577if isempty(first_i) || isempty(last_i)||isempty(MinIndex_i)||isempty(MaxIndex_i)
578    set(handles.first_i,'String',num2str(num_ref_i));
579    set(handles.last_i,'String',num2str(num_ref_i));%
580end
581if ind_opening~=0 || isempty(first_i) || isempty(last_i)|| first_i<MinIndex_i || last_i>MaxIndex_i
582    set(handles.first_i,'String',num2str(num_ref_i));
583    set(handles.last_i,'String',num2str(num_ref_i));%
584end
585
586%j index range
587first_j=str2num(get(handles.first_j,'String'));
588last_j=str2num(get(handles.last_i,'String'));
589if isempty(first_j) || isempty(last_j)||isempty(MinIndex_j)||isempty(MaxIndex_j)
590    set(handles.first_j,'String',num2str(num_ref_j));
591    set(handles.last_j,'String',num2str(num_ref_j));%
592elseif ind_opening~=0 || first_j<MinIndex_j || last_j>MaxIndex_j
593    set(handles.first_j,'String',num2str(num_ref_j));
594set(handles.last_j,'String',num2str(num_ref_j));%
595end
596
597%% set the civ options depending on the input file content when a nc file has been opened
598ListOptions={'CheckCiv1', 'CheckFix1' 'CheckPatch1', 'CheckCiv2', 'CheckFix2', 'CheckPatch2'};
599if ind_opening~=0
600    for index = 1:ind_opening
601        set(handles.(ListOptions{index}),'value',0)
602    end
603end
604for index = ind_opening+2:6
605    set(handles.(ListOptions{index}),'value',0)
606end
607set(handles.(ListOptions{min(ind_opening+1,6)}),'value',1)
608update_CivOptions(handles,ind_opening)
609
610%%  set the menus of image pairs and default selection for civ   %%%%%%%%%%%%%%%%%%%
611%check_letter=~isempty(regexp(NomTypeIma,'[ab|AB]$'));%detect pair label by letter
612if  isequal(NomTypeNc,'_1-2')||isempty(MaxIndex_j)|| (MaxIndex_j==1)
613    set(handles.ListPairMode,'Value',1)
614    set(handles.ListPairMode,'String',{'series(Di)'})   
615elseif  MaxIndex_i==1 && MaxIndex_j>1% simple series in j
616    set(handles.ListPairMode,'String',{'pair j1-j2';'series(Dj)'})
617    if  MaxIndex_j <= 10
618        set(handles.ListPairMode,'Value',1)% advice 'pair j1-j2' except in MaxIndex_j is large
619    end
620else
621    set(handles.ListPairMode,'String',{'pair j1-j2';'series(Dj)';'series(Di)'})%multiple choice
622    if strcmp(NomTypeNc,'_1-2_1')
623        set(handles.ListPairMode,'Value',3)% advise 'series(Di)'
624    elseif  MaxIndex_j <= 10
625        set(handles.ListPairMode,'Value',1)% advice 'pair j1-j2' except in MaxIndex_j is large
626    end
627end
628
629%% scan files to update the subdirectory list display
630listot=dir(RootPath);%directory of RootPath
631idir=0;
632listdir={''};%default
633% get the list of existing civ subdirectories in the path of theinput root  file
634for ilist=1:length(listot)
635    if listot(ilist).isdir
636        name=listot(ilist).name;
637        if ~isequal(name,'.') && ~isequal(name,'..')
638            idir=idir+1;
639            listdir{idir,1}=listot(ilist).name;
640        end
641    end
642end
643
644%% store info
645set(handles.RootPath,'UserData',browse)% store the nomenclature type
646
647%% list the possible index pairs, depending on the option set in ListPairMode
648ListPairMode_Callback([], [], handles)
649
650%% store the root input filename for future opening
651profil_perso=fullfile(prefdir,'uvmat_perso.mat');
652if exist(profil_perso,'file')
653    save (profil_perso,'RootPath','-append'); %store the root name for future opening of uvmat
654else
655    txt=ver('MATLAB');
656    Release=txt.Release;
657    relnumb=str2double(Release(3:4));
658    if relnumb >= 14
659        save (profil_perso,'RootPath','-V6'); %store the root name for future opening of uvmat
660    else
661        save (profil_perso,'RootPath'); %store the root name for future opening of uvmat
662    end
663end
664set(handles.RootPath,'BackgroundColor',[1 1 1])
665
666%------------------------------------------------------------------------
667% --- Executes on carriage return on the subdir checkciv1 edit window
668function SubdirCiv1_Callback(hObject, eventdata, handles)
669%------------------------------------------------------------------------
670SubDir=get(handles.SubdirCiv1,'String');
671menu_str=get(handles.ListSubdirCiv1,'String');% read the list of subdirectories for update
672ichoice=find(strcmp(SubDir,menu_str),1);
673if isempty(ichoice)
674    ilist=numel(menu_str); %select 'new...' in the menu
675else
676    ilist=ichoice;
677end
678set(handles.ListSubdirCiv1,'Value',ilist)% select the selected subdir in the menu
679if get(handles.CheckCiv1,'Value')% if Civ1 is performed
680    set(handles.SubdirCiv2,'String',SubDir);% set by default civ2 directory the same as civ1
681%     set(handles.ListSubdirCiv2,'Value',ilist)
682else % if Civ1 data already exist
683    errormsg=find_netcpair_civ(handles,1); %update the list of available pairs from netcdf files in the new directory
684    if ~isempty(errormsg)
685    msgbox_uvmat('ERROR',errormsg)
686    end
687end
688
689%------------------------------------------------------------------------
690% --- Executes on carriage return on the SubDir checkciv1 edit window
691function SubdirCiv2_Callback(hObject, eventdata, handles)
692%------------------------------------------------------------------------
693SubDir=get(handles.SubdirCiv1,'String');
694menu_str=get(handles.ListSubdirCiv2,'String');% read the list of subdirectories for update
695ichoice=find(strcmp(SubDir,menu_str),1);
696if isempty(ichoice)
697    ilist=numel(menu_str); %select 'new...' in the menu
698else
699    ilist=ichoice;
700end
701set(handles.ListSubdirCiv2,'Value',ilist)% select the selected subdir in the menu
702%update the list of available pairs from netcdf files in the new directory
703if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
704    errormsg=find_netcpair_civ(handles,2);
705        if ~isempty(errormsg)
706    msgbox_uvmat('ERROR',errormsg)
707    end
708end
709
710%------------------------------------------------------------------------
711% --- Executes on button press in CheckCiv1.
712function CheckCiv1_Callback(hObject, eventdata, handles)
713%------------------------------------------------------------------------
714update_CivOptions(handles,0)
715
716%------------------------------------------------------------------------
717% --- Executes on button press in CheckFix1.
718function CheckFix1_Callback(hObject, eventdata, handles)
719%------------------------------------------------------------------------
720update_CivOptions(handles,0)
721
722%------------------------------------------------------------------------
723% --- Executes on button press in CheckPatch1.
724function CheckPatch1_Callback(hObject, eventdata, handles)
725%------------------------------------------------------------------------
726update_CivOptions(handles,0)
727
728%------------------------------------------------------------------------
729% --- Executes on button press in CheckCiv2.
730function CheckCiv2_Callback(hObject, eventdata, handles)
731%------------------------------------------------------------------------
732update_CivOptions(handles,0)
733
734%------------------------------------------------------------------------
735% --- Executes on button press in CheckFix2.
736function CheckFix2_Callback(hObject, eventdata, handles)
737%------------------------------------------------------------------------
738update_CivOptions(handles,0)
739
740%------------------------------------------------------------------------
741% --- Executes on button press in CheckPatch2.
742function CheckPatch2_Callback(hObject, eventdata, handles)
743%------------------------------------------------------------------------
744update_CivOptions(handles,0)
745
746%------------------------------------------------------------------------
747% --- activated by any checkbox controling the selection of Civ1,Fix1,Patch1,Civ2,Fix2,Patch2
748function update_CivOptions(handles,opening)
749%------------------------------------------------------------------------
750checkbox=zeros(1,6);
751checkbox(1)=get(handles.CheckCiv1,'Value');
752checkbox(2)=get(handles.CheckFix1,'Value');
753checkbox(3)=get(handles.CheckPatch1,'Value');
754checkbox(4)=get(handles.CheckCiv2,'Value');
755checkbox(5)=get(handles.CheckFix2,'Value');
756checkbox(6)=get(handles.CheckPatch2,'Value');
757ind_selected=find(checkbox,1);
758if ~isempty(ind_selected)
759    RootPath=get(handles.RootPath,'String');
760    if isempty(RootPath)
761        msgbox_uvmat('ERROR','Please open an image or PIV .nc file with the upper bar menu Open/Browse...')
762        return
763    end
764end
765set(handles.PairIndices,'Visible','on')
766set(handles.SubdirCiv1,'Visible','on')
767set(handles.TitleSubdirCiv1,'Visible','on')
768if opening==0
769    errormsg=find_netcpair_civ(handles,1); % select the available netcdf files
770    if ~isempty(errormsg)
771        msgbox_uvmat('ERROR',errormsg)
772    end
773end
774if max(checkbox(4:6))% case of civ2 pair choice needed
775    set(handles.TitlePairCiv2,'Visible','on')
776    set(handles.TitleSubdirCiv2,'Visible','on')
777    set(handles.SubdirCiv2,'Visible','on')
778    %set(handles.ListSubdirCiv2,'Visible','on')
779    set(handles.ListPairCiv2,'Visible','on')
780    if ~opening
781        errormsg=find_netcpair_civ(handles,2); % select the available netcdf files
782        if ~isempty(errormsg)
783            msgbox_uvmat('ERROR',errormsg)
784        end
785    end
786else
787    set(handles.TitleSubdirCiv2,'Visible','off')
788    set(handles.SubdirCiv2,'Visible','off')
789    set(handles.ListPairCiv2,'Visible','off')
790end
791options={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
792for ilist=1:length(options)
793    if checkbox(ilist)
794        set(handles.(options{ilist}),'Visible','on')
795    else
796        set(handles.(options{ilist}),'Visible','off')
797    end
798end
799
800%------------------------------------------------------------------------
801% --- Executes on button press in RUN: processing on local computer
802function RUN_Callback(hObject, eventdata, handles)
803%------------------------------------------------------------------------
804set(handles.RUN, 'Enable','Off')
805set(handles.RUN,'BackgroundColor',[0.831 0.816 0.784])
806batch=0;
807errormsg=launch_jobs(hObject, eventdata, handles,batch);
808set(handles.RUN, 'Enable','On')
809set(handles.RUN,'BackgroundColor',[1 0 0])
810
811% display errors or start status callback to visualise results
812if ~isempty(errormsg)
813    display(errormsg)
814    msgbox_uvmat('ERROR',errormsg)
815elseif  isfield(handles,'status') %&& ~isequal(get(handles.ListPairMode,'Value'),3)
816    set(handles.status,'Value',1);%suppress status display
817    status_Callback(hObject, eventdata, handles)
818end
819
820%------------------------------------------------------------------------
821% --- Executes on button press in BATCH: remote processing
822function BATCH_Callback(hObject, eventdata, handles)
823% -----------------------------------------------------------------------
824set(handles.BATCH, 'Enable','Off')
825set(handles.BATCH,'BackgroundColor',[0.831 0.816 0.784])
826batch=1;
827errormsg=launch_jobs(hObject, eventdata, handles, batch);
828set(handles.BATCH, 'Enable','On')
829set(handles.BATCH,'BackgroundColor',[1 0 0])
830
831% display errors or start status callback to visualise results
832if ~isempty(errormsg)
833    display(errormsg)
834    msgbox_uvmat('ERROR',errormsg)
835elseif isfield(handles,'status')
836    set(handles.status,'Value',1);%suppress status display
837    status_Callback(hObject, eventdata, handles)
838end
839
840%-------------------------------------------------------------------
841% --- Executes on button press in status.
842function status_Callback(hObject, eventdata, handles)
843%-------------------------------------------------------------------
844val=get(handles.status,'Value');
845if val==0
846    set(handles.status,'BackgroundColor',[0 1 0])
847    hfig=findobj(allchild(0),'name','civ_status');
848    if ~isempty(hfig)
849        delete(hfig)
850    end
851    return
852end
853set(handles.status,'BackgroundColor',[1 1 0])
854drawnow
855listtype={'civ1','fix1','patch1','civ2','fix2','patch2'};
856Param.CheckCiv1=get(handles.CheckCiv1,'Value');
857Param.CheckFix1=get(handles.CheckFix1,'Value');
858Param.CheckPatch1=get(handles.CheckPatch1,'Value');
859Param.CheckCiv2=get(handles.CheckCiv2,'Value');
860Param.CheckFix2=get(handles.CheckFix2,'Value');
861Param.CheckPatch2=get(handles.CheckPatch2,'Value');
862box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
863
864option_civ=find(box_test,1,'last');%last selected option (non-zero index of box_test)
865filecell=get(handles.civ,'UserData');%retrieve the list of output files expected for PIV
866test_new=0;
867if ~isfield(filecell,'nc')
868    test_new=1;
869    [ref_i,ref_j,errormsg]=find_ref_indices(handles);
870    if ~isempty(errormsg)
871        msgbox_uvmat('ERROR',errormsg)
872        return
873    end
874    filecell=set_civ_filenames(handles,ref_i,ref_j,box_test);%determine the output file expected from the GUI status
875end
876if ~isequal(box_test(4:6),[0 0 0])
877    civ_files=filecell.nc.civ2;%case of civ2 operations
878else
879    civ_files=filecell.nc.civ1;
880end
881[root,filename,ext]=fileparts(civ_files{1});
882[rootroot,SubDir,extdir]=fileparts(root);
883hfig=findobj(allchild(0),'name','civ_status');
884if isempty(hfig)
885    hfig=figure('DeleteFcn',@stop_status);
886    set(hfig,'MenuBar','none')% suppress the menu bar
887    set(hfig,'NumberTitle','off')%suppress the fig number in the title
888    set(hfig,'name','civ_status')
889    set(hfig,'tag','civ_status')
890    set(hfig,'UserData',civ_files)
891    hlist= uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', {'open_uvmat'},'tag','list');
892    uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','msgbox','Max',2,'String','checking files...');
893    uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
894    uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@close_GUI);
895    hrefresh=uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.1 0.01 0.2 0.07],'String','Refresh','FontWeight','bold','FontUnits','normalized','FontSize',0.9,'Callback',@refresh_GUI);
896    BarPosition=[0.05 0.81 0.01 0.05];
897    uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
898    drawnow
899end
900set(hrefresh,'UserData',option_civ)
901        filepath=fileparts(civ_files{1});
902set(hlist,'UserData',fileparts(filepath))
903refresh_GUI(hrefresh,[])
904
905%------------------------------------------------------------------------   
906% launched by refreshing the status figure
907function refresh_GUI(hObject, eventdata)
908%------------------------------------------------------------------------
909Tabchar={};
910BarPosition=[0.05 0.81 0.01 0.05];
911hfig=get(hObject,'parent');
912civ_files=get(hfig,'UserData');
913        [filepath,filename,ext]=fileparts(civ_files{1});
914        [tild,SubDir,extdir]=fileparts(filepath);
915        SubDir=[SubDir extdir];
916option_civ=get(hObject,'UserData');
917nbfiles=numel(civ_files);
918count=0;
919testrecent=0;
920% while count<nbfiles
921    count=0;
922    datnum=zeros(1,nbfiles);
923    for ifile=1:nbfiles
924        detect=exist(civ_files{ifile},'file'); % check the existence of the file
925        option=0;
926        if detect==0
927            option_str='not created';
928        else
929            datfile=dir(civ_files{ifile});
930            if isfield(datfile,'datenum')
931                datnum(ifile)=datfile.datenum;%only available in recent matlab versions
932                testrecent=1;
933            end
934            filefound(ifile)={datfile.name};
935            lastfield='';
936            % check the content  netcdf file
937            Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','CivStage','patch2','fix2','civ2','patch','fix');
938            option_list={'civ1','fix1','patch1','civ2','fix2','patch2'};
939            if ~isempty(Data.CivStage)
940                option=Data.CivStage;%case of Matlab civ
941            else
942                if ~isempty(Data.patch2) && isequal(Data.patch2,1)
943                    option=6;
944                elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
945                    option=5;
946                elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
947                    option=4;
948                elseif ~isempty(Data.patch) && isequal(Data.patch,1);
949                    option=3;
950                elseif ~isempty(Data.fix) && isequal(Data.fix,1);
951                    option=2;
952                else
953                    option=1;
954                end
955            end
956            option_str=option_list{option};
957        end
958        if option >= option_civ
959            count=count+1;
960        end
961        [filepath,filename,ext]=fileparts(civ_files{ifile});
962        Tabchar{ifile,1}=[fullfile(SubDir,filename) ext  '...' option_str];
963    end
964    datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
965    if isempty(datnum)
966        if testrecent
967            message='no civ result created yet';
968        else
969            message='';
970        end
971    else
972        datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
973        [first,ind]=min(datnum);
974        [last,indlast]=max(datnum);
975%         if test_new
976%             message='existing file status, no processing launched yet';
977%         else
978        message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
979            ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
980%         end
981    end
982    %hfig=findobj(allchild(0),'name','civ_status');
983%     if isempty(hfig)% the status list has been deleted
984%         return
985%     else
986        hlist=findobj(hfig,'tag','list');
987        hmsgbox=findobj(hfig,'tag','msgbox');
988        hwaitbar=findobj(hfig,'tag','waitbar');
989        set(hlist,'String',Tabchar)
990        set(hmsgbox,'String', message)
991        if count>0 %&& ~test_new
992            BarPosition(3)=0.9*count/nbfiles;
993            set(hwaitbar,'Position',BarPosition)
994        end
995%     end
996%     [root,filename,ext]=fileparts(civ_files{1});
997% [rootroot,SubDir,extdir]=fileparts(root);
998%
999%     set(hlist,'UserData',rootroot)
1000%     if count<10||(nbfiles-count)<10
1001%     pause(.5)% wait 0.5 seconds for next check
1002%     else
1003%         pause(10)% wait 10 seconds for next check
1004%     end
1005% end
1006
1007%------------------------------------------------------------------------   
1008% launched by deleting the status figure
1009function stop_status(hObject, eventdata)
1010%------------------------------------------------------------------------
1011hciv=findobj(allchild(0),'tag','civ');
1012hhciv=guidata(hciv);
1013set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
1014set(hhciv.status,'BackgroundColor',[0 1 0])
1015
1016%------------------------------------------------------------------------   
1017% launched by pressing OK on the status figure
1018function close_GUI(hObject, eventdata)
1019%------------------------------------------------------------------------
1020    delete(gcbf)
1021
1022
1023%------------------------------------------------------------------------
1024% --- Main lauch command, called by RUN and BATCH
1025function errormsg=launch_jobs(hObject, eventdata, handles, batch)
1026%------------------------------------------------------------------------
1027errormsg='';%default
1028
1029%% read the input parameters from the  GUI civ
1030Param=read_GUI(handles.civ);
1031
1032%% check the selected list of operations:
1033operations={'Civ1','Fix1','Patch1','Civ2','Fix2','Patch2'};
1034box_test=[Param.CheckCiv1 Param.CheckFix1 Param.CheckPatch1 Param.CheckCiv2 Param.CheckFix2 Param.CheckPatch2];
1035index_first=find(box_test==1,1);
1036if isempty(index_first)
1037    errormsg='no selected operation';
1038    return
1039end
1040index_last=find(box_test==1,1,'last');
1041box_used=box_test(index_first : index_last);
1042[box_missing,ind_missing]=min(box_used);
1043if isequal(box_missing,0); %there is a missing step in the sequence of operations
1044    errormsg=['missing' cell2mat(operations(ind_missing))];
1045    return
1046end
1047
1048%% check mask if selecetd
1049%could be included in get_mask callback ?
1050if isequal(get(handles.CheckMask,'Value'),1)
1051    maskname=get(handles.Mask,'String');
1052    if ~exist(maskname,'file')
1053        get_mask_civ1_Callback(hObject, eventdata, handles);
1054    end
1055end
1056if isequal(get(handles.CheckMask,'Value'),1)
1057    maskname=get(handles.Mask,'String');
1058    if ~exist(maskname,'file')
1059        get_mask_fix1_Callback(hObject, eventdata, handles);
1060    end
1061end
1062if isequal(get(handles.CheckMask,'Value'),1)
1063    maskname=get(handles.Mask,'String');
1064    if ~exist(maskname,'file')
1065        get_mask_civ2_Callback(hObject, eventdata, handles);
1066    end
1067end
1068if isequal(get(handles.CheckMask,'Value'),1)
1069    maskname=get(handles.Mask,'String');
1070    if ~exist(maskname,'file')
1071        get_mask_fix2_Callback(hObject, eventdata, handles);
1072    end
1073end
1074
1075%% reinitialise status callback
1076if isfield(handles,'status')
1077    set(handles.status,'Value',0);%suppress status display
1078    status_Callback([], [], handles)
1079end
1080
1081%% read the PARAM.xml file to get the binaries (and batch_mode if batch)
1082path_civ=fileparts(which('civ')); %path to the source directory of uvmat
1083xmlfile='PARAM.xml';
1084if exist(xmlfile,'file')% search parameter xml file in the whole matlab path
1085    t=xmltree(xmlfile);
1086    s=convert(t);
1087else
1088    errormsg=['no file ' xmlfile];
1089    return
1090end
1091test_interp=0; %eviter les variables test_ (LG)
1092if batch
1093    if isfield(s,'BatchParam')
1094        Param.xml=s.BatchParam;
1095        if isfield(Param.xml,'BatchMode')
1096            batch_mode=Param.xml.BatchMode;
1097            if ~ismember(batch_mode,{'sge','oar'})
1098                errormsg=['batch mode ' batch_mode ' not supported by UVMAT'];
1099                return
1100            end
1101        end
1102    else
1103        errormsg='no batch civ binaries defined in PARAM.xml';
1104        return
1105    end
1106else % run
1107    if isfield(s,'RunParam')
1108        Param.xml=s.RunParam;
1109    else
1110        errormsg='no run civ binaries defined in PARAM.xml';
1111        return
1112    end
1113end
1114
1115%% check batch mode supported
1116if batch
1117    switch batch_mode
1118        case 'sge'
1119            test_command='qstat';
1120        case 'oar'
1121            test_command='oarstat';
1122    end   
1123    [s,w]=system(test_command);
1124    if ~isequal(s,0)
1125        errormsg=[batch_mode ' batch system not available'];
1126        return
1127    end
1128end
1129
1130%% check if the binaries exist
1131ListProgram=get(handles.ListProgram,'String');
1132CivMode=ListProgram{get(handles.ListProgram,'Value')};
1133binary_list={};
1134switch CivMode
1135    case 'CivX'
1136        binary_list={'Civ1Bin','Civ2Bin','PatchBin','FixBin'};
1137    case 'CivAll'% desactivated option
1138        binary_list={'Civ'};
1139    case 'Matlab'
1140        if batch
1141            binary_list={'CivmBin'};
1142            % verifier MenuMatlab installe sur le cluster
1143            % difficile a faire a priori
1144        end         
1145end
1146for bin_name=binary_list %loop on the list of binaries
1147    if isfield(Param.xml,bin_name{1})% bin_name{1} =current name in the list
1148        if exist(Param.xml.(bin_name{1}),'file')
1149            [path,name,ext]=fileparts(Param.xml.(bin_name{1}));
1150            currentdir=pwd;
1151            if exist(path,'dir')
1152                cd(path);
1153                binpath=pwd;%path of the binary
1154                Param.xml.(bin_name{1})=fullfile(binpath,[name ext]);
1155                cd(currentdir)
1156            else
1157                errormsg=['path ' path ' for binaries defined in PARAM.xml does not exist'];
1158                return
1159            end
1160        else  %look for the full path if the file name has been defined with a relative path in PARAM.xm
1161            fullname=fullfile(path_civ,Param.xml.(bin_name{1}));
1162            if exist(fullname,'file')
1163                Param.xml.(bin_name{1})=fullname;
1164            else
1165                errormsg=['Binary ' Param.xml.(bin_name{1}) ' defined in PARAM.xml does not exist'];
1166                return
1167            end
1168        end
1169    end
1170end
1171display('files OK, processing...')
1172
1173%% set the list of files and check them
1174display('checking the files...')
1175[ref_i,ref_j,errormsg]=find_ref_indices(handles);
1176if ~isempty(errormsg)
1177    return
1178end
1179[filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,tild,tild,compare,errormsg]=...
1180    set_civ_filenames(handles,ref_i,ref_j,box_test);
1181if ~isempty(errormsg)
1182    return
1183end
1184% if isempty(filecell)% (error message displayed in fct set_civ_filenames)
1185%     return
1186% end
1187Rootbat=fileparts(filecell.nc.civ1{1,1});%output netcdf file (without extention)
1188set(handles.civ,'UserData',filecell);%store for futur use of status callback
1189nbfield=numel(i1_civ1);
1190nbslice=numel(j1_civ1);
1191if ~strcmp(CivMode,'CivX')
1192    if Param.CheckCiv1
1193        [Param.Civ1.FileTypeA,FileInfo,Param.Civ1.ImageA]=get_file_type(filecell.ima1.civ1{1});
1194        [Param.Civ1.FileTypeB,FileInfo,Param.Civ1.ImageB]=get_file_type(filecell.ima2.civ1{1});
1195    end
1196    if Param.CheckCiv2
1197        [Param.Civ2.FileTypeA,FileInfo,Param.Civ2.ImageA]=get_file_type(filecell.ima1.civ2{1});
1198        [Param.Civ2.FileTypeB,FileInfo,Param.Civ2.ImageB]=get_file_type(filecell.ima2.civ2{1});
1199    end
1200end
1201
1202%% MAIN LOOP
1203time=get(handles.ImaDoc,'UserData'); %get the set of times
1204TimeUnit=get(handles.TimeUnit,'String');
1205checkframe=strcmp(TimeUnit,'frame');
1206batch_file_list=[];%should be renamed file_list, can be used for xml or bash files
1207 
1208for ifile=1:nbfield
1209    for j=1:nbslice
1210        % initiate system command
1211        switch CivMode
1212            case 'CivX'
1213                if isunix % check: necessaire aussi en RUN?
1214                    cmd=['#!/bin/bash \n '...
1215                        '#$ -cwd \n '...
1216                        'hostname && date \n '...
1217                        'umask 002 \n'];%allow writting access to created files for user group
1218                else
1219                    cmd=[];
1220                end
1221            case 'CivAll'
1222                CivAllxml=xmltree;% xml contents,  all parameters
1223                CivAllCmd='';
1224                CivAllxml=set(CivAllxml,1,'name','CivDoc');
1225        end
1226           
1227        % define output file name
1228        if Param.CheckCiv2==1 || Param.CheckFix2==1 || Param.CheckPatch2==1
1229            OutputFile=filecell.nc.civ2{ifile,j};
1230        else
1231            OutputFile=filecell.nc.civ1{ifile,j};
1232        end
1233        OutputFile=regexprep(OutputFile,'.nc','');
1234       
1235        if Param.CheckCiv1
1236            % read image-dependent parameters
1237           
1238            if ~checkframe% && size(time,1)>=i2_civ1(ifile) && size(time,2)>=j2_civ1(j)
1239                Param.Civ1.Dt=(time(i2_civ1(ifile)+1,j2_civ1(j)+1)-time(i1_civ1(ifile)+1,j1_civ1(j)+1));
1240            else
1241                Param.Civ1.Dt=1;
1242            end
1243            Param.Civ1.Time=((time(i2_civ1(ifile)+1,j2_civ1(j)+1)+time(i1_civ1(ifile)+1,j1_civ1(j)+1))/2);
1244            if strcmp(CivMode,'CivX')
1245                Param.Civ1.term_a=num2stra(j1_civ1(j),nom_type_nc);%UTILITE?
1246                Param.Civ1.term_b=num2stra(j2_civ1(j),nom_type_nc);%
1247            end
1248            if isfield(Param.Civ1,'FileTypeA')&&(strcmp(Param.Civ1.FileTypeA,'video')|| strcmp(Param.Civ1.FileTypeA,'mmreader'))
1249                %   ImageInfo=get(VideoReader(fullfile(Param.RootPath,[Param.RootFile Param.ImaExt])));
1250                ImageInfo=get(Param.Civ1.ImageA);
1251                %                 elseif strcmp(Param.Civ1.FileTypeA,'mmreader')
1252                %                     ImageInfo=get(mmreader(fullfile(Param.RootPath,[Param.RootFile Param.ImaExt])));
1253                Param.Civ1.ImageBitDepth=ImageInfo.BitsPerPixel/3;
1254                if batch
1255                    Param.Civ1.ImageA=filecell.ima1.civ1{ifile,j};%file name must be used for batch instead of video object
1256                    Param.Civ1.ImageB=filecell.ima2.civ1{ifile,j};
1257                end
1258            else
1259                Param.Civ1.ImageA=filecell.ima1.civ1{ifile,j};
1260                Param.Civ1.ImageB=filecell.ima2.civ1{ifile,j};
1261               % form=imformats(regexprep(get(handles.ImaExt,'String'),'^.',''));%look for image formats
1262                ImageInfo=imfinfo(filecell.ima1.civ1{1,1});%read the first image to get the size
1263                Param.Civ1.ImageBitDepth=ImageInfo.BitDepth;
1264            end
1265            Param.Civ1.ImageWidth=ImageInfo.Width;
1266            Param.Civ1.ImageHeight=ImageInfo.Height;
1267            Param.Civ1.FrameIndexA=i1_civ1(ifile);
1268            Param.Civ1.FrameIndexB=i2_civ1(ifile);
1269            % read mask )parameters
1270            if Param.Civ1.CheckMask % the lines below should be changed with the new gui
1271                if ~exist(Param.Civ1.Mask,'file')
1272                    maskbase=[filecell.filebase '_' Param.Civ1.Mask]; %
1273                    nbslice_mask=str2double(Param.Civ1.Mask(1:end-4)); %
1274                    i1_mask=mod(i1_civ1(ifile)-1,nbslice_mask)+1;
1275                    [RootPathMask,RootFileMask]=fileparts(maskbase);
1276                    Param.Civ1.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
1277                end
1278            end
1279            % read grid parameters
1280            if Param.Civ1.CheckGrid
1281                if numel(Param.Civ1.Grid)>=4 && isequal(Param.Civ1.Grid(end-3:end),'grid')
1282                    nbslice_grid=str2double(Param.Civ1.Grid(1:end-4)); %
1283                    if ~isnan(nbslice_grid)
1284                        i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
1285                        Param.Civ1.Grid=[filecell.filebase '_' fullfile_uvmat('','',Param.Civ1.Grid,'.grid','_1',i1_grid)];
1286                        %                         Param.Civ1.Grid=[filecell.filebase '_' name_generator(Param.Civ1.Grid,i1_grid,1,'.grid','_i')];
1287                        if ~exist(Param.Civ1.GridName,'file')
1288                            errormsg='grid file absent for civ1';
1289                            return
1290                        end
1291                    elseif ~exist(Param.Civ1.Grid,'file')
1292                        errormsg='grid file absent for civ1';
1293                        return
1294                    end
1295                end
1296            end
1297           
1298            % send command
1299            switch CivMode
1300                case 'CivX'
1301                    [cmd_civ,errormsg]=cmd_civ1(filecell.nc.civ1{ifile,j},Param);
1302                    cmd=[cmd cmd_civ '\n'];
1303                    if ~isempty(errormsg)
1304                        return
1305                    end
1306                case 'CivAll'
1307                    CivAllCmd=[CivAllCmd ' civ1 '];
1308                    str=CIV1_CMD_Unified(filecell.nc.civ1{ifile,j},'',Param.Civ1);
1309                    fieldnames=fields(str);
1310                    [CivAllxml,uid_civ1]=add(CivAllxml,1,'element','civ1');
1311                    for ilist=1:length(fieldnames)
1312                        val=eval(['str.' fieldnames{ilist}]);
1313                        if ischar(val)
1314                            [CivAllxml,uid_t]=add(CivAllxml,uid_civ1,'element',fieldnames{ilist});
1315                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1316                        end
1317                    end
1318            end
1319        end
1320       
1321        if Param.CheckFix1
1322            switch CivMode
1323                case 'CivX'
1324                    cmd=[cmd...
1325                        cmd_fix(filecell.nc.civ1{ifile,j},Param,'Fix1') '\n'];
1326                case 'CivAll'%to abandon
1327                    fix1.inputFileName=filecell.nc.civ1{ifile,j} ;
1328                    fix1.fi1=num2str(param.fix1.flagindex1(1));
1329                    fix1.fi2=num2str(param.fix1.flagindex1(2));
1330                    fix1.fi3=num2str(param.fix1.flagindex1(3));
1331                    fix1.threshC=num2str(param.fix1.thresh_vecC1);
1332                    fix1.threshV=num2str(param.fix1.thresh_vel1);
1333                    fieldnames=fields(fix1);
1334                    [CivAllxml,uid_fix1]=add(CivAllxml,1,'element','fix1');
1335                    for ilist=1:length(fieldnames)
1336                        val=eval(['fix1.' fieldnames{ilist}]);
1337                        if ischar(val)
1338                            [CivAllxml,uid_t]=add(CivAllxml,uid_fix1,'element',fieldnames{ilist});
1339                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1340                        end
1341                    end
1342                    CivAllCmd=[CivAllCmd ' fix1 '];
1343            end
1344        end
1345       
1346        %CheckPatch1
1347        if Param.CheckPatch1==1
1348            switch CivMode
1349                case 'CivX'
1350                    cmd=[cmd...
1351                        cmd_patch(filecell.nc.civ1{ifile,j},Param,'Patch1') '\n'];
1352                case 'CivAll'
1353                    patch1.inputFileName=filecell.nc.civ1{ifile,j} ;
1354                    patch1.nopt=subdomain_patch1;
1355                    patch1.maxdiff=thresh_patch1;
1356                    patch1.ro=rho_patch1;
1357                    test_grid=get(handles.get_gridpatch1,'Value');
1358                    if test_grid
1359                        patch1.gridflag='y';
1360                        gridname=get(handles.grid_patch1,'String');
1361                        if isequal(gridname(end-3:end),'grid')
1362                            nbslice_grid=str2double(gridname(1:end-4)); %
1363                            if ~isnan(nbslice_grid)
1364                                i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
1365                                patch1.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
1366%                                 patch1.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
1367                                if ~exist(patch1.gridPatch,'file')
1368                                    errormsg='grid file absent for patch1';
1369                                    return
1370                                end
1371                            elseif exist(gridname,'file')
1372                                patch1.gridPatch=gridname;
1373                            else
1374                                errormsg='grid file absent for patch1';
1375                                return
1376                            end
1377                        end
1378                    else
1379                        patch1.gridPatch='none';
1380                        patch1.gridflag='n';
1381                        patch1.m=nx_patch1;
1382                        patch1.n=ny_patch1;
1383                    end
1384                    patch1.convectFlow='n';
1385                    fieldnames=fields(patch1);
1386                    [CivAllxml,uid_patch1]=add(CivAllxml,1,'element','patch1');
1387                    for ilist=1:length(fieldnames)
1388                        val=eval(['patch1.' fieldnames{ilist}]);
1389                        if ischar(val)
1390                            [CivAllxml,uid_t]=add(CivAllxml,uid_patch1,'element',fieldnames{ilist});
1391                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1392                        end
1393                    end
1394                    CivAllCmd=[CivAllCmd ' patch1 '];
1395            end
1396        end
1397        if Param.CheckCiv2==1
1398            if isfield(Param.Civ2,'FileTypeA') &&(strcmp(Param.Civ2.FileTypeA,'video')|| strcmp(Param.Civ2.FileTypeA,'mmreader'))
1399                %   ImageInfo=get(VideoReader(fullfile(Param.RootPath,[Param.RootFile Param.ImaExt])));
1400                ImageInfo=get(Param.Civ2.ImageA);
1401                %                 elseif strcmp(Param.Civ1.FileTypeA,'mmreader')
1402                %                     ImageInfo=get(mmreader(fullfile(Param.RootPath,[Param.RootFile Param.ImaExt])));
1403                Param.Civ2.ImageBitDepth=ImageInfo.BitsPerPixel/3;
1404                if batch
1405                    Param.Civ2.ImageA=filecell.ima1.civ2{ifile,j};%file name must be used for batch instead of video object
1406                    Param.Civ2.ImageB=filecell.ima2.civ2{ifile,j};
1407                end
1408            else
1409                Param.Civ2.ImageA=filecell.ima1.civ2{ifile,j};
1410                Param.Civ2.ImageB=filecell.ima2.civ2{ifile,j};
1411                form=imformats(regexprep(get(handles.ImaExt,'String'),'^.',''));%look for image formats
1412                ImageInfo=imfinfo(filecell.ima1.civ2{1,1});%read the first image to get the size
1413                Param.Civ2.ImageBitDepth=ImageInfo.BitDepth;
1414            end
1415           
1416            if ~checkframe %&& size(time,1)>=i2_civ2(ifile) && size(time,2)>=j2_civ2(j)
1417                Param.Civ2.Dt=time(i2_civ2(ifile)+1,j2_civ2(j)+1)-time(i1_civ2(ifile)+1,j1_civ2(j)+1);
1418            else
1419                Param.Civ2.Dt=1;
1420            end
1421            Param.Civ2.Time=(time(i2_civ2(ifile)+1,j2_civ2(j)+1)+time(i1_civ2(ifile)+1,j1_civ2(j)+1))/2;
1422            if strcmp(CivMode,'CivX')
1423            Param.Civ2.term_a=num2stra(j1_civ2(j),nom_type_nc);
1424            Param.Civ2.term_b=num2stra(j2_civ2(j),nom_type_nc);
1425            end
1426            Param.Civ2.filename_nc1=filecell.nc.civ1{ifile,j};
1427            Param.Civ2.filename_nc1(end-2:end)=[]; % remove '.nc'
1428           
1429            % mask
1430            if Param.Civ2.CheckMask
1431                if ~exist(Param.Civ2.Mask,'file')
1432                    maskbase=[filecell.filebase '_' Param.Civ2.Mask]; %
1433                    nbslice_mask=str2double(Param.Civ2.Mask(1:end-4)); %
1434                    i1_mask=mod(i1_civ2(ifile)-1,nbslice_mask)+1;
1435                    [RootPathMask,RootFileMask]=fileparts(maskbase);
1436                    Param.Civ2.Mask=fullfile_uvmat(RootPathMask,[],RootFileMask,'.png','_1',i1_mask);
1437%                     Param.Civ2.Mask=name_generator(maskbase,i1_mask,1,'.png','_i');
1438                end
1439            end
1440            %grid
1441            if Param.Civ2.CheckGrid
1442                if numel(Param.Civ2.Grid)>=4 && isequal(Param.Civ2.Grid(end-3:end),'grid')
1443                    nbslice_grid=str2double(Param.Civ2.Grid(1:end-4)); %
1444                    if ~isnan(nbslice_grid)
1445                        i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
1446                        Param.Civ2.Grid=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
1447%                         Param.Civ2.Grid=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
1448                    end
1449                end
1450            end
1451            form=imformats(regexprep(get(handles.ImaExt,'String'),'^.',''));%look for image formats
1452            if isempty(form)
1453               % ImageInfo=get(VideoReader(fullfile());
1454                Param.Civ2.ImageBitDepth=ImageInfo.BitsPerPixel/3;
1455            else
1456                ImageInfo=imfinfo(filecell.ima1.civ2{1,1});%read the first image to get the size
1457                Param.Civ2.ImageBitDepth=ImageInfo.BitDepth;
1458            end
1459            Param.Civ2.ImageWidth=ImageInfo.Width;
1460            Param.Civ2.ImageHeight=ImageInfo.Height;
1461            Param.Civ2.FrameIndexA=i1_civ2(ifile);
1462             Param.Civ2.FrameIndexB=i2_civ2(ifile);
1463%             Param.Civ2.i1=i1_civ2(ifile);
1464%             Param.Civ2.i2=i2_civ2(ifile);
1465            switch CivMode
1466                case 'CivX'
1467                    cmd=[cmd...
1468                        cmd_civ2(filecell.nc.civ2{ifile,j},Param) '\n'];
1469                case 'CivAll'
1470                    CivAllCmd=[CivAllCmd ' civ2 '];
1471                    str=CIV2_CMD_Unified(filecell.nc.civ2{ifile,j},'',Param.Civ2);
1472                    fieldnames=fields(str);
1473                    [CivAllxml,uid_civ2]=add(CivAllxml,1,'element','civ2');
1474                    for ilist=1:length(fieldnames)
1475                        val=eval(['str.' fieldnames{ilist}]);
1476                        if ischar(val)
1477                            [CivAllxml,uid_t]=add(CivAllxml,uid_civ2,'element',fieldnames{ilist});
1478                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1479                        end
1480                    end
1481            end
1482        end
1483       
1484        % CheckFix2
1485        if Param.CheckFix2==1
1486            switch CivMode
1487                case 'CivX'
1488                    cmd=[cmd...
1489                        cmd_fix(filecell.nc.civ2{ifile,j},Param,'Fix2') '\n'];
1490                case 'CivAll'
1491                    fix2.inputFileName=filecell.nc.civ2{ifile,j} ;
1492                    fix2.fi1=num2str(flagindex2(1));
1493                    fix2.fi2=num2str(flagindex2(2));
1494                    fix2.fi3=num2str(flagindex2(3));
1495                    fix2.threshC=num2str(thresh_vec2C);
1496                    fix2.threshV=num2str(thresh_vel2);
1497                    fieldnames=fields(fix2);
1498                    [CivAllxml,uid_fix2]=add(CivAllxml,1,'element','fix2');
1499                    for ilist=1:length(fieldnames)
1500                        val=eval(['fix2.' fieldnames{ilist}]);
1501                        if ischar(val)
1502                            [CivAllxml,uid_t]=add(CivAllxml,uid_fix2,'element',fieldnames{ilist});
1503                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1504                        end
1505                    end
1506                    CivAllCmd=[CivAllCmd ' fix2 '];
1507            end
1508        end
1509       
1510        %CheckPatch2
1511        if Param.CheckPatch2==1
1512           
1513            switch CivMode
1514               
1515                case 'CivX'
1516                    cmd=[cmd...
1517                        cmd_patch(filecell.nc.civ1{ifile,j},Param,'Patch2') '\n'];
1518                   
1519                case 'CivAll'
1520                    patch2.inputFileName=filecell.nc.civ1{ifile,j} ;
1521                    patch2.nopt=subdomain_patch2;
1522                    patch2.maxdiff=thresh_patch2;
1523                    patch2.ro=rho_patch2;
1524                    test_grid=get(handles.get_gridpatch2,'Value');
1525                    if test_grid
1526                        patch2.gridflag='y';
1527                        gridname=get(handles.grid_patch2,'String');
1528                        if isequal(gridname(end-3:end),'grid')
1529                            nbslice_grid=str2double(gridname(1:end-4)); %
1530                            if ~isnan(nbslice_grid)
1531                                i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
1532                                patch2.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
1533%                                 patch2.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
1534                                if ~exist(patch2.gridPatch,'file')
1535                                    errormsg='grid file absent for patch2';
1536                                    return
1537                                end
1538                            elseif exist(gridname,'file')
1539                                patch2.gridPatch=gridname;
1540                            else
1541                                errormsg='grid file absent for patch2';
1542                                return
1543                            end
1544                        end
1545                    else
1546                        patch2.gridPatch='none';
1547                        patch2.gridflag='n';
1548                        patch2.m=nx_patch2;
1549                        patch2.n=ny_patch2;
1550                    end
1551                    patch2.convectFlow='n';
1552                    fieldnames=fields(patch2);
1553                    [CivAllxml,uid_patch2]=add(CivAllxml,1,'element','patch2');
1554                    for ilist=1:length(fieldnames)
1555                        val=eval(['patch2.' fieldnames{ilist}]);
1556                        if ischar(val)
1557                            [CivAllxml,uid_t]=add(CivAllxml,uid_patch2,'element',fieldnames{ilist});
1558                            [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
1559                        end
1560                    end
1561                    CivAllCmd=[CivAllCmd ' patch2 '];
1562            end
1563        end
1564       
1565        switch CivMode
1566           
1567            case {'CivX','CivAll'}
1568                if isequal(CivMode,'CivAll')
1569                    save(CivAllxml,[OutputFile '.xml']);
1570                    cmd=[cmd sparam.CivBin ' -f ' OutputFile '.xml '  CivAllCmd ' >' OutputFile '.log' '\n'];
1571                end             
1572                % create the .bat file used in run or batch
1573                filename_bat=[OutputFile '.bat'];
1574                [fid,message]=fopen(filename_bat,'w');
1575                if isequal(fid,-1)
1576                    errormsg=['creation of .bat file: ' message];
1577                    return
1578                end
1579                fprintf(fid,cmd);
1580                fclose(fid);           
1581                if isunix
1582                    system(['chmod +x ' filename_bat]);
1583                end             
1584                batch_file_list{length(batch_file_list)+1}=filename_bat;
1585               
1586            case 'Matlab'
1587                drawnow
1588                if ~strcmp(compare,'stereo PIV')
1589                    filename_xml=[OutputFile '.civ.xml'];
1590                    t=struct2xml(Param);           
1591                    save(t,filename_xml)
1592                    if batch   
1593                        path_civ=fileparts(which('civ'));
1594                        filename_bat=[OutputFile '.bat'];
1595                        [fid,message]=fopen(filename_bat,'w');
1596                        if isequal(fid,-1)
1597                            errormsg= ['creation of .bat file: ' message];
1598                            return
1599                        end
1600%                         text_matlabscript=[...
1601%                         '#!/bin/bash \n'...
1602%                         '. /etc/sysprofile \n'...
1603%                         'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
1604%                         'cd(''' path_civ '''); \n'...
1605%                         'civ_matlab(''' filename_xml ''',''' OutputFile '.nc''); \n'...
1606%                         'exit \n'...
1607%                         'END_MATLAB \n'];
1608                        cmd=['#!/bin/bash \n '...
1609                        '#$ -cwd \n '...
1610                        'hostname && date \n '...
1611                        'umask 002 \n'...
1612                         Param.xml.CivmBin ' ' Param.xml.RunTime ' ' filename_xml ' ' OutputFile '.nc'];%allow writting access to created files for user group
1613                   
1614                        fprintf(fid,cmd);
1615                        fclose(fid);
1616                        if isunix
1617                            system(['chmod +x ' filename_bat]);
1618                        end
1619                        batch_file_list{length(batch_file_list)+1}=filename_bat;
1620                    else
1621                        [tild,errormsg]=civ_matlab(Param,filecell.nc.civ1{ifile,j});
1622                        if isempty(errormsg)
1623                            display([filecell.nc.civ1{ifile,j} ' written'])
1624                        end
1625                    end
1626                end
1627        end
1628    end
1629end
1630
1631if batch 
1632    switch batch_mode   
1633       
1634        case 'sge' %at the moment only psmn ENS Lyon uses it
1635            for p=1:length(batch_file_list)
1636                %cmd=['!qsub -p ' pvalue ' -q civ.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
1637                cmd=['!qsub -q piv1,piv2,piv3 '...
1638                    '-e ' regexprep(batch_file_list{p},'.bat','.errors') ' -o ' regexprep(batch_file_list{p},'.bat','.log ')...
1639                    ' -v ' 'LD_LIBRARY_PATH=/home/sjoubaud/matlab_sylvain/civx/lib ' batch_file_list{p}];               
1640                display(cmd);eval(cmd);
1641            end           
1642        case 'oar_old'
1643                for p=1:length(batch_file_list)
1644                    oar_command=['!oarsub -n CIVX -q nicejob '...
1645                   '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
1646                    '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
1647                display(oar_command);eval(oar_command);
1648                end               
1649        case 'oar'
1650           
1651            max_walltime=3600*12; % 12h max
1652            oar_modes={'oar-parexec','oar-dispatch','mpilauncher'};
1653            text={'Batch processing on servcalcul3 LEGI';...
1654                'Please choose one of the followint modes';...
1655                '* oar-parexec : default and best choice';...
1656                '* oar-dispatch : jobs in a container of several cores';...
1657                '* mpilauncher : one single parallel mpi job using several cores';...
1658                '**********************************'...
1659                };
1660            [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
1661                'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
1662            switch oar_modes{S}
1663                case 'oar-parexec' %oar-dispatch.pl
1664                    answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
1665                    ncores=str2double(answer{1});
1666                    extra_oar=answer{2};
1667                    walltime_onejob=600;%seconds
1668                    filename_joblist=fullfile(Rootbat,'job_list.txt');
1669                    fid=fopen(filename_joblist,'w');
1670                    for p=1:length(batch_file_list)
1671                        fprintf(fid,[batch_file_list{p} '\n']);
1672                    end
1673                    fclose(fid)
1674                    oar_command=['oarsub -n CIVX '...
1675                        '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
1676                        '-l /core=' num2str(ncores) ','...
1677                            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,max_walltime/86400),13) ' '...
1678                        '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1679                        '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1680                        extra_oar ' '...
1681                        '"oar-parexec -s -f ' filename_joblist ' '...
1682                            '-l ' filename_joblist '.log"'];
1683                    filename_oarcommand=fullfile(Rootbat,'oar_command');
1684                    fid=fopen(filename_oarcommand,'w');
1685                    fprintf(fid,[oar_command '\n']);
1686                    fclose(fid);
1687                    display(oar_command);
1688                    eval(['! . ' filename_oarcommand])
1689                case 'oar-dispatch' %oar-dispatch.pl
1690                    ncores=str2double(...
1691                        inputdlg('Number of cores (max 36)','oarsub parameter',1,{'6'})...
1692                        );
1693                    walltime_onejob=600;%seconds
1694                    filename_joblist=fullfile(Rootbat,'job_list.txt');
1695                    fid=fopen(filename_joblist,'w');
1696                    for p=1:length(batch_file_list)
1697                        oar_command=['oarsub -n CIVX '...
1698                            '-E ' regexprep(batch_file_list{p},'\.bat\>','.stderr') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.stdout ')...
1699                            '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
1700                        fprintf(fid,[oar_command '\n']);
1701                    end
1702                    fclose(fid);
1703                    oar_command=['oarsub -t container -n civx-container '...
1704                        '-l /core=' num2str(ncores)...
1705                        ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13) ' '...
1706                        '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1707                        '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1708                        '"oar-dispatch -f ' filename_joblist '"'];
1709                    filename_oarcommand=fullfile(Rootbat,'oar_command');
1710                    fid=fopen(filename_oarcommand,'w');
1711                    fprintf(fid,[oar_command '\n']);
1712                    fclose(fid);
1713                    display(oar_command);
1714                    eval(['! . ' filename_oarcommand])
1715                case 'mpilauncher'
1716                    filename_joblist=fullfile(Rootbat,'job_list.txt');
1717                    fid=fopen(filename_joblist,'w');
1718                   
1719                    for p=1:length(batch_file_list)
1720                        fprintf(fid,[batch_file_list{p} '\n']);
1721                    end
1722                    fclose(fid)
1723                    text_oarscript=[...
1724                        '#!/bin/bash \n'...
1725                        '#OAR -n Mylauncher \n'...
1726                        '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
1727                        '#OAR -E ' fullfile(Rootbat,'stderrfile.log') ' \n'...
1728                        '#OAR -O ' fullfile(Rootbat,'stdoutfile.log') ' \n'...
1729                        '# ========================================================= \n'...
1730                        '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
1731                        '# application for coriolis PIV post-processing. \n'...
1732                        '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
1733                        '# This wrapper assert that the user has the same environment on all the \n'...
1734                        '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
1735                        '# \n'...
1736                        '# REQUIREMENT: \n'...
1737                        '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
1738                        '# If a different location is used, change the line following the comment "Bidouille" \n'...
1739                        '# ========================================================= \n'...
1740                        '#   USER should only modify these 2 lines  \n'...
1741                        'WORKDIR=' pwd ' \n'...
1742                        'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
1743                        '# ========================================================= \n'...
1744                        '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
1745                        'echo "job starting on: "`hostname` \n'...
1746                        'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
1747                        'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
1748                        '#========== Bidouille ============== \n'...
1749                        'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
1750                        'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
1751                        'echo "I run: $CMD"  \n'...
1752                        '$CMD \n'...
1753                        'echo "job ending" \n'...
1754                        ];
1755                    %                 oarsub -S ./oar.sub
1756                    filename_oarscript=fullfile(Rootbat,'oar_command');
1757                    fid=fopen(filename_oarscript,'w');
1758                    fprintf(fid,[text_oarscript]);
1759                    fclose(fid);
1760                    eval(['!chmod +x  ' filename_oarscript]);
1761                    eval(['!oarsub -S ' filename_oarscript]);
1762            end
1763    end
1764else
1765    if ~isequal(CivMode,'Matlab')
1766        filename_superbat=fullfile(Rootbat,'job_list.bat');
1767        fid=fopen(filename_superbat,'w');
1768        if fid==-1
1769            msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1770            return
1771        end
1772        for p=1:length(batch_file_list)
1773            if isunix
1774                fprintf(fid,['sh ' batch_file_list{p} '\n']);
1775            else
1776                fprintf(fid,['@call "' regexprep(batch_file_list{p},'\\','\\\\') '"' '\n']);
1777            end
1778        end
1779        fclose(fid);
1780        if(isunix)
1781            system(['chmod +x ' filename_superbat]);
1782        end
1783        system([filename_superbat ' &']);% execute main commmand
1784    end
1785end
1786
1787
1788%% save interface state
1789if isfield(filecell,'nc')
1790    if isfield(filecell.nc,'civ2')
1791        fileresu=filecell.nc.civ2{1,1};
1792    else
1793        fileresu=filecell.nc.civ1{1,1};
1794    end
1795end
1796[RootPath,SubDir,RootFile]=fileparts_uvmat(fileresu);
1797namedoc=fullfile(RootPath,SubDir,RootFile);
1798detect=1;
1799while detect==1
1800    namefigfull=[namedoc '.fig'];
1801    hh=dir(namefigfull);
1802    if ~isempty(hh)
1803        detect=1;
1804        namedoc=[namedoc '.0'];
1805    else
1806        detect=0;
1807    end
1808end
1809Param=rmfield(Param,'status');
1810Param=rmfield(Param,'xml');
1811t=struct2xml(Param);
1812t=set(t,1,'name','Civ');% set the head label
1813save(t,[namedoc '.civ.xml']); %save GUI  parameters as xml file
1814saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
1815
1816%Save info in personal profile (initiate browser next time) TODO
1817MenuFile={};
1818dir_perso=prefdir;
1819profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1820if exist(profil_perso,'file')
1821    hh=load (profil_perso);
1822      if isfield(hh,'MenuFile')
1823          MenuFile=hh.MenuFile;
1824      end
1825      if isfield(filecell.nc,'civ2')
1826          MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
1827      else
1828           MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
1829      end
1830      save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
1831else
1832    MenuFile=filecell.ima1.civ1(1,1);
1833    save (profil_perso,'MenuFile')
1834end
1835
1836%------------------------------------------------------------------------
1837% --- determine the list of reference indices of processing file
1838function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
1839%------------------------------------------------------------------------
1840errormsg=''; %default error message
1841first_i=str2double(get(handles.first_i,'String'));%first index i
1842last_i=str2double(get(handles.last_i,'String'));%last index i
1843incr_i=str2double(get(handles.incr_i,'String'));% increment
1844if isequal(get(handles.first_j,'Visible'),'on')
1845    first_j=str2double(get(handles.first_j,'String'));%first index j
1846    last_j=str2double(get(handles.last_j,'String'));%last index j
1847    incr_j=str2double(get(handles.incr_j,'String'));% increment
1848else
1849    first_j=1;
1850    last_j=1;
1851    incr_j=1;
1852end
1853ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
1854ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
1855if isnan(first_i)||isnan(first_j)
1856    errormsg='first field number not defined';
1857elseif isnan(last_i)||isnan(last_j)
1858    errormsg='last field number not defined';
1859elseif isnan(incr_i)||isnan(incr_j)
1860    errormsg='increment in field number not defined';
1861elseif last_i < first_i || last_j < first_j
1862    errormsg='last field number must be larger than the first one';
1863end
1864
1865%------------------------------------------------------------------------
1866% --- determine the list of filenames and indices needed for launch_job
1867%------------------------------------------------------------------------
1868% OUTPUT:
1869% filecell: structure of cell arrays {ref_i,ref_j} containing all the filenames involved in the civ process
1870%    the indices ref_i and ref_j correspond to the list of reference indices
1871%       .filebase=fullfile(RootPath,RootFile) used to construct mask names, grid names, CivDoc xml file
1872%       .ima1.civ1,.ima1.civ2: first image for civ1 and civ2 respectively (possibly different)
1873%       .ima2.civ1,.ima2.civ2: second image for civ1 and civ2 respectively (possibly different)
1874%       .nc.civ1,.nc.civ2: netcdf files containing civ1 and civ2 data respectively (possibly different)
1875% i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2: arrays of files indices, needed for timing records
1876function [filecell,i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2,NomType_nc,file_ref_fix1,file_ref_fix2,compare,errormsg]=...
1877    set_civ_filenames(handles,ref_i,ref_j,checkbox)
1878%------------------------------------------------------------------------
1879filecell=[];%default
1880errormsg='';
1881ListProgram=get(handles.ListProgram,'String');
1882CivMode=ListProgram{get(handles.ListProgram,'Value')};%Program to use , CivX or Matlab
1883
1884%% get the root name and check dir
1885RootPath=get(handles.RootPath,'String');
1886SubdirImages=get(handles.SubdirImages,'String');
1887RootFile=get(handles.RootFile,'String');
1888filecell.filebase=fullfile(RootPath,SubdirImages,RootFile);
1889if isempty(filecell.filebase)
1890    errormsg='please open an image with the upper menu option Open/Browse...';
1891    return
1892end
1893if ~exist(RootPath,'dir')
1894    errormsg=['path to images ' RootPath ' not found'];
1895    return
1896end
1897[tild,message]=fileattrib(RootPath);
1898if ~isempty(message) && ~isequal(message.UserWrite,1)
1899    errormsg=['No writting access to ' RootPath];
1900    return
1901end
1902%check result directory
1903subdir_civ1=regexprep(get(handles.SubdirCiv1,'String'),'^.','');%subdirectory subdir_civ1 for the netcdf output data
1904subdir_civ2=regexprep(get(handles.SubdirCiv2,'String'),'^.','');
1905if isequal(subdir_civ1,''),subdir_civ1='civ'; end% put default subdir
1906% subdir_civ1=[ '.' subdir_civ1];
1907% subdir_civ2=[ '.' subdir_civ2];
1908if isequal(subdir_civ2,''),subdir_civ2=subdir_civ1; end% put default subdir
1909subdir_civ1=[SubdirImages '.' subdir_civ1];
1910subdir_civ2=[SubdirImages '.' subdir_civ2];
1911
1912%% choose root names depending on ListCompareMode =displacement, shift, PIV or stereo PIV
1913ListCompareMode=get(handles.ListCompareMode,'String');
1914compare=ListCompareMode{get(handles.ListCompareMode,'Value')};
1915
1916% set the nomenclature type of the nc files depending on the pair mode
1917if strcmp(compare,'displacement')||strcmp(compare,'shift')
1918    mode='displacement';
1919else
1920    mode_list=get(handles.ListPairMode,'String');
1921    mode_value=get(handles.ListPairMode,'Value');
1922    mode=mode_list{mode_value};
1923end
1924NomType_ima2=get(handles.NomType,'String');
1925NomType_nc=nomtype2pair(NomType_ima2,mode);
1926
1927% set the rootfile and image indexing
1928RootFile_ima2=get(handles.RootFile,'String');%root file for the second image series
1929ext_ima=get(handles.ImaExt,'String'); % image extension (the same for all images)
1930switch compare
1931    case 'PIV'
1932       RootFile_ima1=RootFile_ima2;% root name of the two image series is the same
1933       NomType_ima1=NomType_ima2;% the index of the first image follows the index of the second one
1934       RootFile_nc=RootFile_ima2;
1935    case 'displacement'
1936       RootFile_ima1=get(handles.RootFile_1,'String');% root name of the first image series set by handles.RootFile_1
1937       NomType_ima1='';% no indexing of the first image, a fixed reference for the whole series
1938       RootFile_nc=RootFile_ima2;
1939    case 'shift'
1940       RootFile_ima1=get(handles.RootFile_1,'String');% root name of the first image series set by handles.RootFile_1
1941       NomType_ima1=NomType_ima2;% the index of the first image follows the index of the second one
1942       RootFile_nc=[RootFile_ima1 '-' RootFile_ima2];
1943end
1944
1945%determine the list of file indices involved
1946[i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2]=...
1947    find_pair_indices(handles,ref_i,ref_j,mode);
1948
1949%determine the new filebase for 'displacement' ListPairMode (comparison of two series)
1950%filebase_B=filebase;% root name of the second field series for stereo
1951% filebase_A=filebase;%default
1952% if strcmp(compare,'PIV')
1953%     filebase_AB=filebase;
1954% else
1955%     [Path2,Name2]=fileparts(filebase_B);
1956%     Name1=RootFile_ima1;
1957%     filebase_AB=fullfile(Path2,[Name2 '-' Name1]);   
1958% end
1959% [RootPath_AB,RootFile_AB]=fileparts(filebase_AB);
1960% % [RootPath_ima1,RootFile_ima1]=fileparts(filebase_B);
1961% [RootPath_ima2,RootFile_ima2]=fileparts(filebase_B);
1962% [RootPath_nc,RootFile_nc]=fileparts(filebase_B);%default
1963% if strcmp(compare,'displacement')
1964% %     [RootPath_ima1,RootFile_ima1]=fileparts(filebase_B);
1965% %     [RootPath_ima2,RootFile_ima2]=fileparts(filebase_B);
1966%     [RootPath_nc,RootFile_nc]=fileparts(filebase_B);
1967% elseif strcmp(compare,'shift')
1968%     RootPath_nc=RootPath_AB;
1969%     RootFile_nc=RootFile_AB;
1970% end
1971% else
1972%     filebase_ima1=filebase_B;
1973%     filebase_ima2=filebase_B;
1974%     filebase_nc=filebase_B;
1975% [RootPath_ima1,RootFile_ima1]=fileparts(filebase_ima1);
1976% [RootPath_ima2,RootFile_ima2]=fileparts(filebase_ima2);
1977% [RootPath_nc,RootFile_nc]=fileparts(filebase_nc);
1978% [RootPath_A,RootFile_A]=fileparts(filebase_A);
1979
1980   
1981%% determine reference files for fix:
1982file_ref_fix1={};%default
1983file_ref_fix2={};
1984nbfield=length(i1_civ1);
1985nbslice=length(j1_civ1);
1986if checkbox(2)==1% fix1 performed
1987    ref=get(handles.ref_fix1,'UserData');%read data on the ref file stored by get_ref_fix1_Callback
1988    if ~isempty(ref)
1989        first_i=str2double(get(handles.first_i,'String'));
1990        last_i=str2double(get(handles.last_i,'String'));
1991        incr_i=str2double(get(handles.incr_i,'String'));
1992        first_j=str2double(get(handles.first_j,'String'));
1993        last_j=str2double(get(handles.last_j,'String'));
1994        incr_j=str2double(get(handles.incr_j,'String'));
1995        num_i_ref=first_i:incr_i:last_i;
1996        num_j_ref=first_j:incr_j:last_j;
1997        if isequal(mode,'displacement')
1998            num_i1=num_i_ref;
1999            num_i2=num_i_ref;
2000            num_j1=num_j_ref;
2001            num_j2=num_j_ref;
2002        elseif isequal(mode,'pair j1-j2')% isequal(mode,'st_pair j1-j2')
2003            num_i1=num_i_ref;
2004            num_i2=num_i1;
2005            num_j1=ref.num_a*ones(size(num_i_ref));
2006            num_j2=ref.num_b*ones(size(num_i_ref));
2007        elseif isequal(mode,'series(Di)') % isequal(mode,'st_series(Di)')
2008            delta1=floor((ref.num2-ref.num1)/2);
2009            delta2=ceil((ref.num2-ref.num1)/2);
2010            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
2011            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
2012            if isempty(ref.num_a)
2013                ref.num_a=1;
2014            end
2015            num_j1=ref.num_a*ones(size(num_i1));
2016            num_j2=num_j1;
2017        elseif isequal(mode,'series(Dj)')%| isequal(mode,'st_series(Dj)')
2018            delta1=floor((ref.num_b-ref.num_a)/2);
2019            delta2=ceil((ref.num_b-ref.num_a)/2);
2020            num_i1=ref.num1*ones(size(num_i_ref));
2021            num_i2=num_i1;
2022            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
2023            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
2024        end
2025        for ifile=1:nbfield
2026            for j=1:nbslice
2027                [RootPathRef,RootFile]=fileparts(ref.filebase);
2028                file_ref=fullfile_uvmat(RootPathRef,ref.subdir,RootFile,'.nc',ref.NomType,num_i1(ifile),num_i2(ifile),num_j1(j),num_j2(j));
2029                file_ref_fix1(ifile,j)={file_ref};
2030                if ~exist(file_ref,'file')
2031                    errormsg=['reference file ' file_ref ' not found for fix1'];
2032                    return
2033                end
2034            end
2035        end
2036    end
2037end
2038
2039%% determine reference files for fix2:
2040if checkbox(5)==1% fix2 performed
2041    ref=get(handles.ref_fix2,'UserData');
2042    if ~isempty(ref)
2043        first_i=str2double(get(handles.first_i,'String'));
2044        last_i=str2double(get(handles.last_i,'String'));
2045        incr_i=str2double(get(handles.incr_i,'String'));
2046        first_j=str2double(get(handles.first_j,'String'));
2047        last_j=str2double(get(handles.last_j,'String'));
2048        incr_j=str2double(get(handles.incr_j,'String'));
2049        num_i_ref=first_i:incr_i:last_i;
2050        num_j_ref=first_j:incr_j:last_j;
2051        if isequal(mode,'displacement')
2052            num_i1=num_i_ref;
2053            num_i2=num_i_ref;
2054            num_j1=num_j_ref;
2055            num_j2=num_j_ref;
2056        elseif isequal(mode,'pair j1-j2')
2057            num_i1=num_i_ref;
2058            num_i2=num_i1;
2059            num_j1=ref.num_a;
2060            num_j2=ref.num_b;
2061        elseif isequal(mode,'series(Di)')
2062            delta1=floor((ref.num2-ref.num1)/2);
2063            delta2=ceil((ref.num2-ref.num1)/2);
2064            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
2065            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
2066            num_j1=ref.num_a*ones(size(num_i1));
2067            num_j2=num_j1;
2068        elseif isequal(mode,'series(Dj)')
2069            delta1=floor((ref.num_b-ref.num_a)/2);
2070            delta2=ceil((ref.num_b-ref.num_a)/2);
2071            num_i1=ref.num1*ones(size(num_i_ref));
2072            num_i2=num_i1;
2073            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
2074            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
2075        end
2076        for ifile=1:nbfield
2077            for j=1:nbslice
2078                [RootPathRef,RootFile]=fileparts(ref.filebase);
2079                file_ref=fullfile_uvmat(RootPathRef,ref.subdir,RootFile,'.nc',ref.NomType,num_i1(ifile),num_i2(ifile),num_j1(j),num_j2(j));
2080                file_ref_fix2(ifile,j)={file_ref};
2081                if ~exist(file_ref,'file')
2082                    errormsg=['reference file ' file_ref ' not found for fix2'];
2083                    return
2084                end
2085            end
2086        end
2087    end
2088end
2089
2090%% check the existence of the netcdf and image files involved
2091% %%%%%%%%%%%%  case CheckCiv1 activated   %%%%%%%%%%%%%
2092if checkbox(1)==1;
2093    detect=1;
2094    vers=0;
2095    subdir_civ1_new=subdir_civ1;
2096    while detect==1 %create a new subdir if the netcdf files already exist
2097        for ifile=1:nbfield
2098            for j=1:nbslice
2099                filename=fullfile_uvmat(RootPath,subdir_civ1_new,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2100                detect=exist(filename,'file')==2;
2101                if detect% if a netcdf file already exists
2102                    answer=msgbox_uvmat('INPUT_Y-N',['delete files in ' subdir_civ1_new]);
2103                    if ~strcmp(answer,'Yes')
2104                        r=regexp(subdir_civ1_new,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
2105                        if isempty(r)
2106                            r(1).root=[subdir_civ1_new '_'];
2107                            r(1).num1='0';
2108                        end
2109                        subdir_civ1_new=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
2110                        subdir_civ2=subdir_civ1_new;
2111                    end
2112                    break
2113                end
2114                filecell.nc.civ1(ifile,j)={filename};
2115            end
2116            if detect% if a netcdf file already exists
2117                break
2118            end
2119        end
2120 
2121        %create the new SubdirCiv1
2122        if ~exist(fullfile(RootPath,subdir_civ1_new),'dir')     
2123            [xx,msg1]=mkdir(fullfile(RootPath,subdir_civ1_new));
2124            if ~strcmp(msg1,'')
2125                errormsg=['cannot create ' subdir_civ1_new ': ' msg1];%error message for directory creation
2126                return
2127            elseif isunix         
2128                [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2129                if ~strcmp(msg2,'')
2130                    errormsg=['pb of permission for  ' fullfile(RootPath,subdir_civ1_new) ': ' msg2];%error message for directory creation
2131                    return
2132                end
2133            end
2134        end
2135        if strcmp(compare,'stereo PIV')&&(strcmp(mode,'pair j1-j2')||strcmp(mode,'series(Dj)')||strcmp(mode,'series(Di)'))%check second nc series
2136            for ifile=1:nbfield
2137                for j=1:nbslice
2138                     filename=fullfile_uvmat(RootPath,subdir_civ1_new,RootFile_A,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2139                   % filename=name_generator(filebase_A,i1_civ1(ifile),j1_civ1(j),'.nc',NomType_nc,1,i2_civ1(ifile),j2_civ1(j),subdir_civ1_new);%
2140                    detect=exist(filename,'file')==2;
2141                    if detect% if a netcdf file already exists
2142                       indstr=regexp(subdir_civ1_new,'\D');
2143                       if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
2144                           vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
2145                           subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
2146                       else
2147                           vers=vers+1;
2148                           subdir_civ1_new=[subdir_civ1_new '_' num2str(vers)];
2149                       end
2150                       subdir_civ2=subdir_civ1;
2151                       break
2152                    end
2153                    filecell.ncA.civ1(ifile,j)={filename};
2154                end
2155                if detect% if a netcdf file already exists
2156                    break
2157                end
2158            end
2159            %create the new SubdirCiv1
2160            if ~exist(fullfile(RootPath,subdir_civ1_new),'dir')       
2161                [xx,msg1]=mkdir(fullfile(RootPath,subdir_civ1_new));
2162                if ~strcmp(msg1,'')
2163                    errormsg=['cannot create ' subdir_civ1_new ': ' msg1];
2164                    return
2165                else
2166                    [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2167                    if ~strcmp(msg2,'')
2168                        errormsg=['pb of permission for ' subdir_civ1_new ': ' msg2];%error message for directory creation
2169                        return
2170                    end
2171                end
2172            end
2173        end
2174    end
2175    subdir_civ1=subdir_civ1_new;
2176    % get image names
2177    for ifile=1:nbfield
2178        for j=1:nbslice
2179             filename=fullfile_uvmat(RootPath,SubdirImages,RootFile_ima1,ext_ima,NomType_ima1,i1_civ1(ifile),[],j1_civ1(j));
2180            idetect(j)=exist(filename,'file')==2;
2181            filecell.ima1.civ1(ifile,j)={filename}; %first image
2182            filename=fullfile_uvmat(RootPath,SubdirImages,RootFile_ima2,ext_ima,NomType_ima2,i2_civ1(ifile),[],j2_civ1(j));
2183            idetect_1(j)=exist(filename,'file')==2;
2184            filecell.ima2.civ1(ifile,j)={filename};%second image
2185        end
2186        [idetectmin,indexj]=min(idetect);
2187        if idetectmin==0,
2188            errormsg=[filecell.ima1.civ1{ifile,indexj} ' not found'];
2189            return
2190        end
2191        [idetectmin,indexj]=min(idetect_1);
2192        if idetectmin==0,
2193            errormsg=[filecell.ima2.civ1{ifile,indexj} ' not found'];
2194            return
2195        end
2196    end
2197    if strcmp(compare,'stereo PIV') && (strcmp(mode,'pair j1-j2') || strcmp(mode,'series(Dj)') || strcmp(mode,'series(Di)'))
2198        for ifile=1:nbfield
2199            for j=1:nbslice
2200                filename=fullfile_uvmat(RootPath,'',RootFile_A,ext_ima,NomType_ima1,i1_civ1(ifile),[],j1_civ1(j));
2201                idetect(j)=exist(filename,'file')==2;
2202                filecell.imaA1.civ1(ifile,j)={filename} ;%first image
2203                filename=fullfile_uvmat(RootPath,'',RootFile_A,ext_ima,NomType_ima2,i2_civ1(ifile),[],j2_civ1(j));
2204                idetect_1(j)=exist(filename,'file')==2;
2205                filecell.imaA2.civ1(ifile,j)={filename};%second image
2206            end
2207            [idetectmin,indexj]=min(idetect);
2208            if idetectmin==0,
2209                errormsg=[filecell.imaA1.civ1{ifile,indexj} ' not found'];
2210                return
2211            end
2212            [idetectmin,indexj]=min(idetect_1);
2213            if idetectmin==0,
2214                errormsg=[filecell.imaA2.civ1{ifile,indexj} ' not found'];
2215                return
2216            end
2217        end
2218    end
2219   
2220    %%%%%%%%%%%%%  checkfix1 or checkpatch1 activated but no checkciv1   %%%%%%%%%%%%%
2221elseif (checkbox(2)==1 || checkbox(3)==1);
2222    for ifile=1:nbfield
2223        for j=1:nbslice
2224            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2225            detect=exist(filename,'file')==2;
2226            if detect==0
2227                errormsg=[filename ' not found'];
2228                return
2229            end
2230            filecell.nc.civ1(ifile,j)={filename};
2231        end
2232    end
2233    if strcmp(compare,'stereo PIV')
2234        for ifile=1:nbfield
2235            for j=1:nbslice
2236                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_A,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2237                filecell.ncA.civ1(ifile,j)={filename};
2238                if ~exist(filename,'file')
2239                    errormsg=['input file ' filename ' not found'];
2240                    return
2241                end
2242            end
2243        end
2244    end
2245end
2246
2247%%%%%%%%%%%%%  if checkciv2 performed with pairs different than checkciv1  %%%%%%%%%%%%%
2248testdiff=0;
2249if (checkbox(4)==1)&&...
2250        ((get(handles.ListPairCiv1,'Value')~=get(handles.ListPairCiv2,'Value'))||~strcmp(subdir_civ2,subdir_civ1))
2251    testdiff=1;
2252    detect=1;
2253    vers=0;
2254    subdir_civ2_new=subdir_civ2;
2255    while detect==1 %create a new subdir if the netcdf files already exist
2256        for ifile=1:nbfield
2257            for j=1:nbslice
2258                filename=fullfile_uvmat(RootPath,subdir_civ2_new,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2259                detect=exist(filename,'file')==2;
2260                if detect% if a netcdf file already exists
2261                    indstr=regexp(subdir_civ2,'\D');
2262                    if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2263                        vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2264                        subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2265                    else
2266                        vers=vers+1;
2267                        subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2268                    end
2269                    break
2270                end
2271                filecell.nc.civ2(ifile,j)={filename};
2272            end
2273            if detect% if a netcdf file already exists
2274                break
2275            end
2276        end
2277        %create the new subdir_civ2_new
2278        if ~exist(fullfile(RootPath,subdir_civ2_new),'dir')
2279            [xx,m2]=mkdir(fullfile(RootPath,subdir_civ2_new));
2280            [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2281            if ~isequal(m2,'')
2282                errormsg=['cannot create ' fullfile(RootPath,subdir_civ2_new) ': ' m2];
2283                return
2284            end
2285        end
2286        if strcmp(compare,'stereo PIV')%check second nc series
2287            for ifile=1:nbfield
2288                for j=1:nbslice
2289                    filename=fullfile_uvmat(RootPath,subdir_civ2_new,RootFile_A,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2290                    detect=exist(filename,'file')==2;
2291                    if detect% if a netcdf file already exists
2292                        indstr=regexp(subdir_civ2,'\D');
2293                        if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2294                           vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2295                           subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2296                        else
2297                           vers=vers+1;
2298                           subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2299                        end
2300                        break
2301                    end
2302                    filecell.ncA.civ2(ifile,j)={filename};
2303                end
2304                if detect% if a netcdf file already exists
2305                    break
2306                end
2307            end
2308            subdir_civ2=subdir_civ2_new;
2309            %create the new SubdirCiv1
2310            if ~exist(fullfile(RootPath,subdir_civ2_new),'dir')
2311                [xx,m2]=mkdir(subdir_civ2_new);
2312                 [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2313                if ~isequal(m2,'')
2314                    errormsg= ['cannot create ' fullfile(RootPath,subdir_civ2_new) ': ' m2];%error message for directory creation
2315                    return
2316                end
2317            end
2318        end
2319    end
2320    subdir_civ2=subdir_civ2_new;
2321end
2322
2323%%%%%%%%%%%%%  if checkciv2 results are obtained or used  %%%%%%%%%%%%%
2324if checkbox(4)==1 || checkbox(5)==1 || checkbox(6)==1 %civ2
2325    %check source netcdf file of checkciv1 estimates
2326    if checkbox(1)==0; %no civ1 performed
2327        for ifile=1:nbfield
2328            for j=1:nbslice
2329                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));%
2330                filecell.nc.civ1(ifile,j)={filename};% name of the civ1 file
2331                if ~exist(filename,'file')
2332                    errormsg=['input file ' filename ' not found'];
2333                    return
2334                end
2335                if ~testdiff % civ2 or patch2 are written in the same file as civ1
2336                    if checkbox(4)==0 ; %check the existence of civ2 if it is not calculated
2337                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2338                        if isfield(Data,'Txt')
2339                            errormsg=Data.Txt;
2340                            return
2341                        elseif ~isempty(Data.CivStage)% case of new civ files
2342                            if Data.CivStage<4 %test for civ files
2343                            errormsg=['no civ2 data in ' filename];
2344                            return
2345                            end
2346                        elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2347                            errormsg=['no civ2 data in ' filename];
2348                            return
2349                        end
2350                    elseif checkbox(3)==0; %check the existence of patch if it is not calculated
2351                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','patch');
2352                        if isfield(Data,'Txt')
2353                            errormsg=Data.Txt;
2354                            return
2355                        elseif ~isempty(Data.CivStage)
2356                            if Data.CivStage<3 %test for civ files
2357                                errormsg=['no patch data in ' filename];
2358                                return
2359                            end
2360                        elseif isempty(Data.patch)||isequal(Data.patch,0)
2361                            errormsg=['no patch data in ' filename];
2362                            return
2363                        end
2364                    end
2365                end
2366            end
2367        end
2368        if strcmp(compare,'stereo PIV')
2369            for ifile=1:nbfield
2370                for j=1:nbslice
2371                    filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_A,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2372                    filecell.ncA.civ2(ifile,j)={filename};
2373                    if ~exist(filename,'file')
2374                        errormsg=['input file ' filename ' not found'];
2375                        return
2376                    end
2377                end
2378            end
2379        end
2380    end
2381   
2382    detect=1;
2383    %     while detect==1%creates a new subdir if the netcdf files already contain checkciv2 data
2384    for ifile=1:nbfield
2385        for j=1:nbslice
2386            filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2387            detect=exist(filename,'file')==2;
2388            filecell.nc.civ2(ifile,j)={filename};
2389        end
2390    end
2391    %get first image names for checkciv2
2392    if checkbox(1)==1 && isequal(i1_civ1,i1_civ2) && isequal(j1_civ1,j1_civ2)
2393        filecell.ima1.civ2=filecell.ima1.civ1;
2394    elseif checkbox(4)==1
2395        for ifile=1:nbfield
2396            for j=1:nbslice
2397                filename=fullfile_uvmat(RootPath,[],RootFile_ima1,ext_ima,NomType_ima1,i1_civ2(ifile),[],j1_civ2(j));
2398                idetect_2(j)=exist(filename,'file')==2;
2399                filecell.ima1.civ2(ifile,j)={filename};%first image
2400            end
2401            [idetectmin,indexj]=min(idetect_2);
2402            if idetectmin==0,
2403               errormsg=['input image ' filecell.ima1.civ2{ifile,indexj} ' not found'];
2404                return
2405            end
2406        end
2407    end
2408   
2409    %get second image names for checkciv2
2410    if checkbox(1)==1 && isequal(i2_civ1,i2_civ2) && isequal(j2_civ1,j2_civ2)
2411        filecell.ima2.civ2=filecell.ima2.civ1;
2412    elseif checkbox(4)==1
2413        for ifile=1:nbfield
2414            for j=1:nbslice
2415                filename=fullfile_uvmat(RootPath,[],RootFile_ima2,ext_ima,NomType_ima2,i2_civ2(ifile),[],j2_civ2(j));
2416                idetect_3(j)=exist(filename,'file')==2;
2417                filecell.ima2.civ2(ifile,j)={filename};%first image
2418            end
2419            [idetectmin,indexj]=min(idetect_3);
2420            if idetectmin==0,
2421                errormsg=['input image ' filecell.ima2.civ2{ifile,indexj} ' not found'];
2422                return
2423            end
2424        end
2425    end
2426end
2427if (checkbox(5) || checkbox(6)) && ~checkbox(4)  % need to read an existing netcdf civ2 file
2428    if ~testdiff
2429        filecell.nc.civ2=filecell.nc.civ1;% file already checked
2430    else     % check the civ2 files
2431        for ifile=1:nbfield
2432            for j=1:nbslice
2433                 filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2434                filecell.nc.civ2(ifile,j)={filename};
2435                if ~exist(filename,'file')
2436                    errormsg=['input file ' filename ' not found'];
2437                    return
2438                else
2439                    Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2440                    if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2441                            errormsg=['no civ2 data in ' filename];
2442                            return
2443                    elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2444                        errormsg=['no civ2 data in ' filename];
2445                        return
2446                    end
2447                end
2448            end
2449        end
2450    end
2451end
2452
2453%%%%%%%%%%%%%  if stereo fields are calculated by PATCH %%%%%%%%%%%%%
2454if strcmp(compare,'stereo PIV')
2455    if  checkbox(3) && isequal(get(handles.test_stereo1,'Value'),1)
2456        for ifile=1:nbfield
2457            for j=1:nbslice
2458                 filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_AB,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2459                filecell.st(ifile,j)={filename};
2460            end
2461        end
2462    end
2463    if  checkbox(6) && isequal(get(handles.CheckStereo,'Value'),1)
2464        for ifile=1:nbfield
2465            for j=1:nbslice
2466                 filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_AB,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2467                filecell.st(ifile,j)={filename};
2468            end
2469        end
2470    end
2471end
2472set(handles.SubdirCiv1,'String',regexprep(subdir_civ1,['^' SubdirImages],''));%suppress the root  SuddirImages;);%update the edit box
2473set(handles.SubdirCiv2,'String',regexprep(subdir_civ2,['^' SubdirImages],''));%update the edit box
2474
2475% For CivX COPY IMAGES TO THE FORMAT .png IF NEEDED
2476if strcmp(CivMode,'CivX')
2477    if isequal(NomType_ima1,'*')%case of movie files
2478        NomType_imanew1='_i';
2479    else
2480        NomType_imanew1=NomType_ima1;
2481    end
2482    if isequal(NomType_ima2,'*')%case of movie files
2483        NomType_imanew2='_i';
2484    else
2485        NomType_imanew2=NomType_ima2;
2486    end
2487    if ~isequal(ext_ima,'.png')
2488        %%type of image file
2489        type_ima1='none';%default
2490        movieobject1=[];%default
2491        if strcmpi(ext_ima,'.avi')
2492            if ~isempty(which('mmreader'))% if the mmreader function is found (recent version of matlab)
2493                type_ima1='movie';
2494                movieobject1=mmreader([filecell.filebase ext_ima]);
2495            else
2496                type_ima1='avi';
2497            end
2498        elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2499            form=imformats(ext_ima(2:end));
2500            if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2501                if isequal(NomType_ima1,'*');
2502                    type_ima1='multimage';%image series in a single image file
2503                else
2504                    type_ima1='image';
2505                end
2506            end
2507        end
2508        type_ima2='none';%default
2509        movieobject2=[];
2510        if strcmpi(ext_ima,'.avi')
2511            if ~isempty(which('mmreader'))% if the mmreader function is found (recent version of matlab)
2512                type_ima2='movie';
2513                movieobject2=mmreader([filecell.filebase ext_ima]);
2514            else
2515                type_ima2='avi';
2516            end
2517        elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2518            form=imformats(ext_ima(2:end));
2519            if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2520                if isequal(NomType_ima1,'*');
2521                    type_ima2='multimage';%image series in a single image file
2522                else
2523                    type_ima2='image';
2524                end
2525            end
2526        end
2527        if checkbox(1) %if civ1 is performed
2528            h = waitbar(0,'copy images to the .png format for civ1');% display a wait bar
2529            for ifile=1:nbfield
2530                waitbar(ifile/nbfield);
2531                for j=1:nbslice
2532                    filename=fullfile_uvmat(RootPath,[],RootFile_ima1,'.png',NomType_imanew1,i1_civ1(ifile),[],j1_civ1(j));
2533                    if ~exist(filename,'file')
2534                        A=read_image(filecell.ima1.civ1{ifile,j},type_ima1,i1_civ1(ifile),movieobject1);
2535                        imwrite(A,filename,'BitDepth',16);
2536                    end
2537                    filecell.ima1.civ1(ifile,j)={filename};
2538                    filename=fullfile_uvmat(RootPath,[],RootFile_ima2,'.png',NomType_imanew2,i2_civ1(ifile),[],j2_civ1(j));
2539                    if ~exist(filename,'file')
2540                        A=read_image(filecell.ima2.civ1{ifile,j},type_ima2,i2_civ1(ifile),movieobject2);
2541                        imwrite(A,filename,'BitDepth',16);
2542                    end
2543                    filecell.ima2.civ1(ifile,j)={filename};
2544                end
2545            end
2546            close(h)
2547        end
2548        if checkbox(4) %if civ2 is performed
2549            h = waitbar(0,'copy images to the .png format for civ2');% display a wait bar
2550            for ifile=1:nbfield
2551                waitbar(ifile/nbfield);
2552                for j=1:nbslice
2553                    filename=fullfile_uvmat(RootPath,[],RootFile_ima1,'.png',NomType_imanew1,i1_civ2(ifile),[],j1_civ2(j));
2554                    if ~exist(filename,'file')
2555                        A=read_image(cell2mat(filecell.ima1.civ2(ifile,j)),type_ima2,i1_civ2(ifile));
2556                        imwrite(A,filename,'BitDepth',16);
2557                    end
2558                    filecell.ima1.civ2(ifile,j)={filename};
2559                    filename=fullfile_uvmat(RootPath,[],RootFile_ima2,'.png',NomType_imanew2,i2_civ2(ifile),[],j2_civ2(j));
2560                    if ~exist(filename,'file')
2561                        A=read_image(cell2mat(filecell.ima2.civ2(ifile,j)),type_ima2,i2_civ2(ifile));
2562                        imwrite(A,filename,'BitDepth',16);
2563                    end
2564                    filecell.ima2.civ2(ifile,j)={filename};
2565                end
2566            end
2567            close(h);
2568        end
2569    end
2570end
2571
2572%------------------------------------------------------------------------
2573% --- determine the list of index pairs of processing file
2574function [num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
2575    find_pair_indices(handles,ref_i,ref_j,mode)
2576%------------------------------------------------------------------------
2577
2578list_civ1=get(handles.ListPairCiv1,'String');
2579index_civ1=get(handles.ListPairCiv1,'Value');
2580str_civ1=list_civ1{index_civ1};%string defining the image pairs for civ1
2581if isempty(str_civ1)||isequal(str_civ1,'')
2582    msgbox_uvmat('ERROR','no image pair selected for civ1')
2583    return
2584end
2585list_civ2=get(handles.ListPairCiv2,'String');
2586index_civ2=get(handles.ListPairCiv2,'Value');
2587if index_civ2>length(list_civ2)
2588    list_civ2=list_civ1;
2589    index_civ2=index_civ1;
2590end
2591str_civ2=list_civ2{index_civ2};%string defining the image pairs for civ2
2592
2593if isequal (mode,'series(Di)')
2594    lastfield=str2double(get(handles.nb_field,'String'));
2595    num1_civ1=ref_i-floor(index_civ1/2)*ones(size(ref_i));% set of first image numbers
2596    num2_civ1=ref_i+ceil(index_civ1/2)*ones(size(ref_i));
2597    num_a_civ1=ref_j;
2598    num_b_civ1=ref_j;
2599    num1_civ2=ref_i-floor(index_civ2/2)*ones(size(ref_i));
2600    num2_civ2=ref_i+ceil(index_civ2/2)*ones(size(ref_i));
2601    num_a_civ2=ref_j;
2602    num_b_civ2=ref_j;   
2603   
2604    % adjust the first and last field number
2605    lastfield=str2double(get(handles.nb_field,'String'));
2606    if isnan(lastfield)
2607        indsel=find((num1_civ1 >= 1)&(num1_civ2 >= 1));
2608    else
2609        indsel=find((num2_civ1 <= lastfield)&(num2_civ2 <= lastfield)&(num1_civ1 >= 1)&(num1_civ2 >= 1));
2610    end
2611    if length(indsel)>=1
2612        firstind=indsel(1);
2613        lastind=indsel(end);
2614        set(handles.first_i,'String',num2str(ref_i(firstind)))%update the display of first and last fields
2615        set(handles.last_i,'String',num2str(ref_i(lastind)))
2616        ref_i=ref_i(indsel);
2617        num1_civ1=num1_civ1(indsel);
2618        num1_civ2=num1_civ2(indsel);
2619        num2_civ1=num2_civ1(indsel);
2620        num2_civ2=num2_civ2(indsel);
2621    end
2622elseif isequal (mode,'series(Dj)')
2623    lastfield_j=str2double(get(handles.nb_field2,'String'));
2624    num1_civ1=ref_i;% set of first image numbers
2625    num2_civ1=ref_i;
2626    num_a_civ1=ref_j-floor(index_civ1/2)*ones(size(ref_j));
2627    num_b_civ1=ref_j+ceil(index_civ1/2)*ones(size(ref_j));
2628    num1_civ2=ref_i;
2629    num2_civ2=ref_i;
2630    num_a_civ2=ref_j-floor(index_civ2/2)*ones(size(ref_j));
2631    num_b_civ2=ref_j+ceil(index_civ2/2)*ones(size(ref_j));
2632    % adjust the first and last field number
2633    if isnan(lastfield_j)
2634        indsel=find((num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2635    else
2636        indsel=find((num_b_civ1 <= lastfield_j)&(num_b_civ2 <= lastfield_j)&(num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2637    end
2638    if length(indsel)>=1
2639        firstind=indsel(1);
2640        lastind=indsel(end);
2641        set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
2642        set(handles.last_j,'String',num2str(ref_j(lastind)))
2643        ref_j=ref_j(indsel);
2644        num_a_civ1=num_a_civ1(indsel);
2645        num_b_civ1=num_b_civ1(indsel);
2646        num_a_civ2=num_a_civ2(indsel);
2647        num_b_civ2=num_b_civ2(indsel);
2648    end
2649elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
2650    displ_num=get(handles.ListPairCiv1,'UserData');
2651    num1_civ1=ref_i;
2652    num2_civ1=ref_i;
2653    num_a_civ1=displ_num(1,index_civ1);
2654    num_b_civ1=displ_num(2,index_civ1);
2655    num1_civ2=ref_i;
2656    num2_civ2=ref_i;
2657    num_a_civ2=displ_num(1,index_civ2);
2658    num_b_civ2=displ_num(2,index_civ2);
2659elseif isequal(mode,'displacement')
2660    num1_civ1=ref_i;
2661    num2_civ1=ref_i;
2662    num_a_civ1=ref_j;
2663    num_b_civ1=ref_j;
2664    num1_civ2=ref_i;
2665    num2_civ2=ref_i;
2666    num_a_civ2=ref_j;
2667    num_b_civ2=ref_j;
2668end
2669
2670%------------------------------------------------------------------------
2671% --- Executes on button press in ListCompareMode.
2672function ListCompareMode_Callback(hObject, eventdata, handles)
2673%------------------------------------------------------------------------
2674ListCompareMode=get(handles.ListCompareMode,'String');
2675option=ListCompareMode{get(handles.ListCompareMode,'Value')};
2676if ~strcmp(option,'PIV') % case 'displacement' or 'stereo PIV'
2677    filebase=get(handles.RootPath,'String');
2678    set(handles.sub_txt,'Visible','on')
2679    set(handles.RootFile_1,'Visible','On');%mkes the second file input window visible
2680    mode_store=get(handles.ListPairMode,'String');%get the present 'mode'
2681    set(handles.ListCompareMode,'UserData',mode_store);%store the mode display
2682    set(handles.ListPairMode,'Visible','off')
2683   
2684    %% open an image file with the browser
2685    ind_opening=1;%default
2686    browse.incr_pair=[0 0]; %default
2687    oldfile=get(handles.RootPath,'String');
2688    menu={'*.png;*.jpg;*.tif;*.avi;*.AVI;', ' (*.png,*.jpg ,.tif, *.avi,*.AVI)';
2689        '*.png','.png image files'; ...
2690        '*.jpg',' jpeg image files'; ...
2691        '*.tif','.tif image files'; ...
2692        '*.avi;*.AVI','.avi movie files'; ...
2693        '*.*',  'All Files (*.*)'};
2694    if strcmp(option,'displacement')
2695        comment='Pick the reference file for displacements';
2696    else
2697        comment='Pick a file of the second series';
2698    end
2699    [FileName, PathName] = uigetfile( menu, comment,oldfile);
2700    fileinput=[PathName FileName];%complete file name
2701    sizf=size(fileinput);
2702    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
2703    [path,name,ext]=fileparts(fileinput);
2704    [path1]=fileparts(filebase);
2705    if isunix
2706        [status,path]=system(['readlink ' path]);
2707        [status,path1]=system(['readlink ' path1]);% look for the true path in case of symbolic paths
2708    end
2709    if ~strcmp(path1,path)
2710        msgbox_uvmat('ERROR','The second image or series must be in the same directory as the first one')
2711        return
2712    end
2713    if strcmp(option,'displacement')
2714        [tild,RootFile_1]=fileparts(name);
2715    else
2716        [FilePath,FileName,Ext]=fileparts(fileinput);
2717% detect the file type, get the movie object if relevant, and look for the corresponding file series:
2718% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
2719[RootPath,SubDir,RootFile_1,i1_series,i2_series,j1_series,j2_series,nom_type_1,FileType,Object,i1,i2,j1,j2]=find_file_series(FilePath,[FileName Ext]);
2720       
2721       % [tild,tild,RootFile_1,tild,tild,tild,tild,tild,nom_type_1]=fileparts_uvmat(fileinput);
2722        %[RootFile_1,i1_series,tild,j1_series,tild,nom_type_1,FileType,Object]=find_file_series(PathName,FileName);
2723        %check image nom type
2724        if ~strcmp(nom_type_1,get(handles.NomType,'String'))
2725        msgbox_uvmat('ERROR','The second image series must have the same indexing type as the first one, or use the option displacement for a fixed image')
2726        return
2727        end
2728    end   
2729    %check image  extension
2730    if ~strcmp(ext,get(handles.ImaExt,'String'))
2731        msgbox_uvmat('ERROR','The second image series must have the same extension name as the first one')
2732        return
2733    end
2734    set(handles.RootFile_1,'String',RootFile_1);
2735else
2736    set(handles.ListPairMode,'Visible','on')
2737    set(handles.RootFile_1,'Visible','Off');
2738    set(handles.sub_txt,'Visible','off')
2739    set(handles.RootFile_1,'String',[]);
2740    mode_store=get(handles.ListCompareMode,'UserData');
2741    set(handles.ListPairMode,'Value',1)
2742    set(handles.ListPairMode,'String',mode_store)
2743    set(handles.CheckStereo,'Value',0)
2744    set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2745end
2746% if strcmp(option,'stereo PIV') && get(handles.CheckPatch1,'Value')
2747%     set(handles.CheckStereo,'Visible','on')
2748% else
2749%     set(handles.CheckStereo,'Visible','off')
2750% end
2751% if strcmp(option,'stereo PIV') && get(handles.CheckPatch2,'Value')
2752%     set(handles.CheckStereo,'Visible','on')
2753% else
2754%     set(handles.CheckStereo,'Visible','off')
2755% end
2756ListPairMode_Callback(hObject, eventdata, handles)
2757
2758
2759%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2760% Callbacks in the uipanel Pair Indices
2761%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2762%------------------------------------------------------------------------
2763% --- Executes on button press in ListPairMode.
2764function ListPairMode_Callback(hObject, eventdata, handles)
2765%------------------------------------------------------------------------
2766compare_list=get(handles.ListCompareMode,'String');
2767val=get(handles.ListCompareMode,'Value');
2768compare=compare_list{val};
2769if strcmp(compare,'displacement')||strcmp(compare,'shift')
2770    mode='displacement';
2771else
2772    mode_list=get(handles.ListPairMode,'String');
2773    if ischar(mode_list)
2774        mode_list={mode_list};
2775    end
2776    mode_value=get(handles.ListPairMode,'Value');
2777    mode=mode_list{mode_value};
2778end
2779displ_num=[];%default
2780ref_i=str2double(get(handles.ref_i,'String'));
2781% last_i=str2num(get(handles.last_i,'String'));
2782time=get(handles.ImaDoc,'UserData'); %get the set of times
2783TimeUnit=get(handles.TimeUnit,'String');
2784checkframe=strcmp(TimeUnit,'frame');
2785siztime=size(time);
2786nbfield=siztime(1)-1;
2787nbfield2=siztime(2)-1;
2788indchosen=1;  %%first pair selected by default
2789%displ_num used to define the indices of the civ pairs
2790% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
2791% are relative to the reference indices ref_i and ref_j respectively.
2792if isequal(mode,'pair j1-j2')%| isequal(mode,'st_pair j1-j2')
2793    dt=1;
2794    displ='';
2795    index=0;
2796    numlist_a=[];
2797    numlist_B=[];
2798    %get all the time intervals in bursts
2799    displ_dt=1;%default
2800    nbfield2=min(nbfield2,10);%limitate the number of pairs to 10x10
2801    for numod_a=1:nbfield2-1 %nbfield2 always >=2 for 'pair j1-j2' mode
2802        for numod_b=(numod_a+1):nbfield2
2803            index=index+1;
2804            numlist_a(index)=numod_a;
2805            numlist_b(index)=numod_b;
2806            if size(time,2)>1 && ~checkframe
2807                dt(numod_a,numod_b)=time(ref_i+1,numod_b+1)-time(ref_i+1,numod_a+1);%first time interval dt
2808                displ_dt(index)=dt(numod_a,numod_b);
2809            else
2810                displ_dt(index)=1;
2811            end
2812        end
2813    end
2814    [dtsort,indsort]=sort(displ_dt);
2815    if ~isempty(numlist_a)
2816        displ_num(1,:)=numlist_a(indsort);
2817        displ_num(2,:)=numlist_b(indsort);
2818    end
2819    displ_num(3,:)=0;
2820    displ_num(4,:)=0;
2821    enable_j(handles, 'off')
2822elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)')
2823    index=1:200;
2824    displ_num(1,index)=-floor(index/2);
2825    displ_num(2,index)=ceil(index/2);
2826    displ_num(3:4,index)=zeros(2,200);
2827    enable_j(handles, 'on')
2828elseif isequal(mode,'series(Di)') %| isequal(mode,'st_series(Di)')
2829    index=1:200;
2830    displ_num(1:2,index)=zeros(2,200);
2831    displ_num(3,index)=-floor(index/2);
2832    displ_num(4,index)=ceil(index/2);
2833    enable_i(handles, 'on')
2834    if nbfield2 > 1
2835        enable_j(handles, 'on')
2836    else
2837        enable_j(handles, 'off')
2838    end
2839elseif isequal(mode,'displacement')%the pairs have the same indices
2840    displ_num(1,1)=0;
2841    displ_num(2,1)=0;
2842    displ_num(3,1)=0;
2843    displ_num(4,1)=0;
2844    if nbfield > 1 || nbfield==0
2845        enable_i(handles, 'on')
2846    else
2847        enable_j(handles, 'off')
2848    end
2849    if nbfield2 > 1
2850        enable_j(handles, 'on')
2851    else
2852        enable_j(handles, 'off')
2853    end
2854end
2855set(handles.ListPairCiv1,'UserData',displ_num);
2856errormsg=find_netcpair_civ( handles,1);
2857    if ~isempty(errormsg)
2858    msgbox_uvmat('ERROR',errormsg)
2859    end
2860% find_netcpair_civ2(handles)
2861
2862function enable_i(handles, state)
2863set(handles.itext,'Visible',state)
2864set(handles.first_i,'Visible',state)
2865set(handles.last_i,'Visible',state)
2866set(handles.incr_i,'Visible',state)
2867set(handles.nb_field,'Visible',state)
2868set(handles.ref_i,'Visible',state)
2869
2870function enable_j(handles, state)
2871set(handles.jtext,'Visible',state)
2872set(handles.first_j,'Visible',state)
2873set(handles.last_j,'Visible',state)
2874set(handles.incr_j,'Visible',state)
2875set(handles.nb_field2,'Visible',state)
2876set(handles.ref_j,'Visible',state)
2877
2878
2879%------------------------------------------------------------------------
2880% --- Executes on selection change in ListPairCiv1.
2881function ListPairCiv1_Callback(hObject, eventdata, handles)
2882%------------------------------------------------------------------------
2883%reproduce by default the chosen pair in the checkciv2 menu
2884list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
2885index_pair=get(handles.ListPairCiv1,'Value');
2886displ_num=get(handles.ListPairCiv1,'UserData');
2887% num_a=displ_num(1,index_pair);
2888% num_b=displ_num(2,index_pair);
2889list_pair2=get(handles.ListPairCiv2,'String');%get the menu of image pairs
2890if index_pair<=length(list_pair2)
2891    set(handles.ListPairCiv2,'Value',index_pair);
2892end
2893
2894%update first_i and last_i according to the chosen image pairs
2895mode_list=get(handles.ListPairMode,'String');
2896mode_value=get(handles.ListPairMode,'Value');
2897mode=mode_list{mode_value};
2898if isequal(mode,'series(Di)')
2899    first_i=str2double(get(handles.first_i,'String'));
2900    last_i=str2double(get(handles.last_i,'String'));
2901    incr_i=str2double(get(handles.incr_i,'String'));
2902    num1=first_i:incr_i:last_i;
2903    lastfield=str2double(get(handles.nb_field,'String'));
2904    if ~isnan(lastfield)
2905        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2906            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2907        num1=num1(test_find);
2908    end
2909    set(handles.first_i,'String',num2str(num1(1)));
2910    set(handles.last_i,'String',num2str(num1(end)));
2911elseif isequal(mode,'series(Dj)')
2912    first_j=str2double(get(handles.first_j,'String'));
2913    last_j=str2double(get(handles.last_j,'String'));
2914    incr_j=str2double(get(handles.incr_j,'String'));
2915    num_j=first_j:incr_j:last_j;
2916    lastfield2=str2double(get(handles.nb_field2,'String'));
2917    if ~isnan(lastfield2)
2918        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2919            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2920        num1=num_j(test_find);
2921    end
2922    set(handles.first_j,'String',num2str(num1(1)));
2923    set(handles.last_j,'String',num2str(num1(end)));
2924end
2925
2926%------------------------------------------------------------------------
2927% --- Executes on selection change in ListPairCiv2.
2928function ListPairCiv2_Callback(hObject, eventdata, handles)
2929%------------------------------------------------------------------------
2930index_pair=get(handles.ListPairCiv2,'Value');%get the selected position index in the menu
2931
2932%update first_i and last_i according to the chosen image pairs
2933mode_list=get(handles.ListPairMode,'String');
2934mode_value=get(handles.ListPairMode,'Value');
2935mode=mode_list{mode_value};
2936if isequal(mode,'series(Di)')
2937    first_i=str2double(get(handles.first_i,'String'));
2938    last_i=str2double(get(handles.last_i,'String'));
2939    incr_i=str2double(get(handles.incr_i,'String'));
2940    num1=first_i:incr_i:last_i;
2941    lastfield=str2double(get(handles.nb_field,'String'));
2942    if ~isnan(lastfield)
2943        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2944            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2945        num1=num1(test_find);
2946    end
2947    set(handles.first_i,'String',num2str(num1(1)));
2948    set(handles.last_i,'String',num2str(num1(end)));
2949elseif isequal(mode,'series(Dj)')
2950    first_j=str2double(get(handles.first_j,'String'));
2951    last_j=str2double(get(handles.last_j,'String'));
2952    incr_j=str2double(get(handles.incr_j,'String'));
2953    num_j=first_j:incr_j:last_j;
2954    lastfield2=str2double(get(handles.nb_field2,'String'));
2955    if ~isnan(lastfield2)
2956        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2957            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2958        num1=num_j(test_find);
2959    end
2960    set(handles.first_j,'String',num2str(num1(1)));
2961    set(handles.last_j,'String',num2str(num1(end)));
2962end
2963
2964%------------------------------------------------------------------------
2965function ref_i_Callback(hObject, eventdata, handles)
2966%------------------------------------------------------------------------
2967mode_list=get(handles.ListPairMode,'String');
2968mode_value=get(handles.ListPairMode,'Value');
2969mode=mode_list{mode_value};
2970errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2971if isequal(mode,'series(Di)') || ...% we do patch2 only
2972        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2973    errormsg=find_netcpair_civ( handles,2);
2974end
2975    if ~isempty(errormsg)
2976    msgbox_uvmat('ERROR',errormsg)
2977    end
2978
2979%------------------------------------------------------------------------
2980function ref_j_Callback(hObject, eventdata, handles)
2981%------------------------------------------------------------------------
2982mode_list=get(handles.ListPairMode,'String');
2983mode_value=get(handles.ListPairMode,'Value');
2984mode=mode_list{mode_value};
2985if isequal(get(handles.CheckCiv1,'Value'),0)|| isequal(mode,'series(Dj)')
2986    errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2987end
2988if isequal(mode,'series(Dj)') || ...
2989        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2990    errormsg=find_netcpair_civ(handles,2);
2991end
2992    if ~isempty(errormsg)
2993    msgbox_uvmat('ERROR',errormsg)
2994    end
2995
2996%------------------------------------------------------------------------
2997% determine the menu for checkciv1 pairs depending on existing netcdf file at the middle of
2998% the field series set by first_i, incr, last_i
2999% index=1: look for pairs for civ1
3000% index=2: look for pairs for civ2
3001function errormsg=find_netcpair_civ(handles,index)
3002%------------------------------------------------------------------------
3003set(gcf,'Pointer','watch')% set the mouse pointer to 'watch' (clock)
3004
3005%% initialisation
3006errormsg='';
3007browse=get(handles.RootPath,'UserData');
3008compare_list=get(handles.ListCompareMode,'String');
3009val=get(handles.ListCompareMode,'Value');
3010compare=compare_list{val};
3011if strcmp(compare,'displacement')||strcmp(compare,'shift')
3012    mode='displacement';
3013else
3014    mode_list=get(handles.ListPairMode,'String');
3015    mode_value=get(handles.ListPairMode,'Value');
3016    if isempty(mode_list)
3017        return
3018    end
3019    mode=mode_list{mode_value};
3020end
3021nom_type_ima=get(handles.NomType,'String');
3022
3023%% determine nom_type_nc, nomenclature type of the .nc files:
3024[nom_type_nc]=nomtype2pair(nom_type_ima,mode);
3025
3026%% reads .nc subdirectoy and image numbers from the interface
3027subdir_civ1=get(handles.SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
3028subdir_civ2=get(handles.SubdirCiv2,'String');%subdirectory subdir_civ2 for the netcdf data
3029ref_i=str2double(get(handles.ref_i,'String'));
3030if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
3031    ref_j=0;
3032else
3033    ref_j=str2double(get(handles.ref_j,'String'));
3034    if isnan(ref_j)
3035        ref_j=1;
3036    end
3037end
3038time=get(handles.ImaDoc,'UserData');%get the set of times
3039TimeUnit=get(handles.TimeUnit,'String');
3040checkframe=strcmp(TimeUnit,'frame');
3041displ_num=get(handles.ListPairCiv1,'UserData');
3042
3043%% eliminate the first pairs inconsistent with the position
3044if isempty(displ_num)
3045    nbpair=0;
3046else
3047    nbpair=length(displ_num(1,:));%nbre of displayed pairs
3048    if  isequal(mode,'series(Di)')  %| isequal(mode,'st_series(Di)')
3049        nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
3050    elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3051        nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
3052    end
3053end
3054nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
3055
3056%% case with no Civ1 operation, netcdf files need to exist for reading
3057displ_pair={''};
3058select=ones(size(1:nbpair));%flag for displayed pairs =1 for display
3059testpair=0;
3060RootPath=get(handles.RootPath,'String');
3061RootFile=get(handles.RootFile,'String');
3062if index==1 % case civ1
3063    if ~get(handles.CheckCiv1,'Value') %
3064        if ~exist(fullfile(RootPath,subdir_civ1),'dir')
3065            errormsg=['no civ1 file available: subdirectory ' subdir_civ1 ' does not exist'];
3066            set(handles.ListPairCiv1,'String',{});
3067            return
3068        end
3069        for ipair=1:nbpair
3070            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3071                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3072            select(ipair)=exist(filename,'file')==2;% put flag to 0 if the file does not exist
3073        end
3074        % case of no displayed pair
3075        if isequal(select,zeros(size(1:nbpair)))
3076            if isfield(browse,'incr_pair') && ~isequal(browse.incr_pair,[0 0])
3077                num_i1=ref_i-floor(browse.incr_pair(1)/2);
3078                num_i2=ref_i+ceil(browse.incr_pair(1)/2);
3079                num_j1=ref_j-floor(browse.incr_pair(2)/2);
3080                num_j2=ref_j+ceil(browse.incr_pair(2)/2);
3081                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3082                select(1)=exist(filename,'file')==2;
3083                testpair=1;
3084            else
3085                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3086                    errormsg=['no civ1 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ1];
3087                else
3088                    errormsg=['no civ1 file available for the selected reference indices (i,j)= ' num2str(ref_i) ', ' num2str(ref_j) ' and subdirectory ' subdir_civ1];
3089                end
3090                set(handles.ListPairCiv1,'String',{''});
3091                %COMPLETER CAS STEREO
3092                return
3093            end
3094        end
3095    end
3096else %case civ2 alone
3097    if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
3098        if ~exist(fullfile(RootPath,subdir_civ2),'dir')
3099            msgbox_uvmat('ERROR',['no civ2 file available: subdirectory ' subdir_civ2 ' does not exist'])
3100            set(handles.ListPairCiv2,'Value',1);
3101            set(handles.ListPairCiv2,'String',{''});
3102            return
3103        end
3104        for ipair=1:nbpair
3105            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3106                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3107            select(ipair)=exist(filename,'file')==2;
3108        end
3109        if  isequal(select,zeros(size(1:nbpair)))
3110            if isfield(browse,'incr_pair')
3111                num_i1=ref_i-floor(browse.incr_pair(1)/2);
3112                num_i2=ref_i+floor((browse.incr_pair(1)+1)/2);
3113                num_j1=ref_j-floor(browse.incr_pair(2)/2);
3114                num_j2=ref_j+floor((browse.incr_pair(2)+1)/2);
3115                filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3116                select(1)=exist(filename,'file')==2;
3117            else
3118                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3119                    errormsg=['no civ2 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ2];
3120                else
3121                    errormsg=['no civ2 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ2];
3122                end
3123                set(handles.ListPairCiv2,'Value',1);
3124                set(handles.ListPairCiv2,'String',{''});
3125                return
3126            end
3127        end
3128    end
3129end
3130
3131%% determine the menu display in .ListPairCiv1
3132% the menu depends on the mode defined in ListPairMode_callback through the array displ_num:
3133% displ_num(1,:)=indices j1
3134% displ_num(2,:)=indices j2
3135% displ_num(3,:)=indices i1
3136% displ_num(4,:)=indices i2
3137% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
3138% are relative to the reference indices ref_i and ref_j respectively.
3139if isequal(mode,'series(Di)')
3140    if testpair
3141        displ_pair{1}=['Di= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3142    else
3143        for ipair=1:nbpair
3144            if select(ipair)
3145                displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3146                %if ~checkframe && size(time,1)>=ref_i+1+displ_num(4,ipair) && size(time,2)>=ref_j+1+displ_num(2,ipair)&&displ_num(2,ipair)>=1 &&displ_num(1,ipair)>=1
3147                 %   dt=time(ref_i+1+displ_num(4,ipair),ref_j+1+displ_num(2,ipair))-time(ref_i+1+displ_num(3,ipair),ref_j+1+displ_num(1,ipair));%time interval dt
3148               if ~checkframe && size(time,1)>=ref_i+1+ceil(ipair/2) && size(time,2)>=ref_j+1&& ref_i-floor(ipair/2)>=0 && ref_j>=0
3149                 dt=time(ref_i+1+ceil(ipair/2),ref_j+1)-time(ref_i+1-floor(ipair/2),ref_j+1);%time interval dtref_j+1
3150                else
3151                    dt=1;
3152                end
3153                 displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3154            else
3155                displ_pair{ipair}='...'; %pair not displayed in the menu
3156            end
3157        end
3158    end
3159elseif isequal(mode,'series(Dj)')
3160    if testpair
3161        displ_pair{1}=['Dj= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3162    else
3163        for ipair=1:nbpair
3164            if select(ipair)
3165                displ_pair{ipair}=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3166                if ~checkframe && size(time,1)>=ref_i+1+displ_num(4,ipair) && size(time,2)>=ref_j+1+displ_num(2,ipair)
3167                    dt=time(ref_i+1+displ_num(4,ipair),ref_j+1+displ_num(2,ipair))-time(ref_i+1+displ_num(3,ipair),ref_j+1+displ_num(1,ipair));%time interval dt
3168                    displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3169                end
3170            else
3171                displ_pair{ipair}='...'; %pair not displayed in the menu
3172            end
3173        end
3174    end
3175elseif isequal(mode,'pair j1-j2')%case of pairs
3176    for ipair=1:nbpair
3177        if select(ipair)
3178            if ~checkframe && size(time,2)>1
3179            dt=time(ref_i+1+displ_num(4,ipair),displ_num(2,ipair)+1)-time(ref_i+1+displ_num(3,ipair),displ_num(1,ipair)+1);%time interval dt
3180            else % time set by default to i index
3181                dt=1;
3182            end
3183            displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair),nom_type_ima) '-' num2stra(displ_num(2,ipair),nom_type_ima) ...
3184                ' :dt= ' num2str(dt*1000)];
3185        else
3186            displ_pair{ipair}='...'; %pair not displayed in the menu
3187        end
3188    end
3189elseif isequal(mode,'displacement')
3190    displ_pair={'Di=Dj=0'};
3191end
3192if index==1
3193set(handles.ListPairCiv1,'String',displ_pair');
3194end
3195
3196%% determine the default selection in the pair menu
3197ichoice=find(select,1);% index of selected pair
3198if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3199initial=get(handles.ListPairCiv1,'Value');%initial choice of pair
3200if initial>nbpair || (numel(select)>=initial && ~isequal(select(initial),1))
3201    set(handles.ListPairCiv1,'Value',ichoice);% first valid pair proposed by default in the menu
3202end
3203initial=get(handles.ListPairCiv2,'Value');
3204if initial>length(displ_pair')%|~isequal(select(initial),1)
3205    if ichoice <= length(displ_pair')
3206        set(handles.ListPairCiv2,'Value',ichoice);% same pair proposed by default for civ2
3207    else
3208        set(handles.ListPairCiv2,'Value',1);% same pair proposed by default for civ2
3209    end
3210end
3211set(handles.ListPairCiv2,'String',displ_pair');
3212set(gcf,'Pointer','arrow')
3213
3214
3215   
3216% %------------------------------------------------------------------------   
3217% % call 'view_field.fig' to display the  field selected in the list of 'status'
3218% function open_view_field(hObject, eventdata)
3219% %------------------------------------------------------------------------
3220% list=get(hObject,'String');
3221% index=get(hObject,'Value');
3222% rootroot=get(hObject,'UserData');
3223% filename=list{index};
3224% ind_dot=strfind(filename,'...');
3225% filename=filename(1:ind_dot-1);
3226% filename=fullfile(rootroot,filename);
3227% delete(get(hObject,'parent'))%delete the display figure to stop the check process
3228% if exist(filename,'file')%visualise the vel field if it exists
3229%     uvmat(filename)
3230%     set(gcbo,'Value',1)
3231% end
3232
3233
3234%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3235% Callbacks in the uipanel Reference Indices
3236%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3237%------------------------------------------------------------------------
3238function first_i_Callback(hObject, eventdata, handles)
3239%------------------------------------------------------------------------
3240first_i=str2double(get(handles.first_i,'String'));
3241set(handles.ref_i,'String', num2str(first_i))% reference index for pair dt = first index
3242ref_i_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3243
3244%------------------------------------------------------------------------
3245function first_j_Callback(hObject, eventdata, handles)
3246%------------------------------------------------------------------------
3247first_j=str2num(get(handles.first_j,'String'));
3248set(handles.ref_j,'String', num2str(first_j))% reference index for pair dt = first index
3249ref_j_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3250
3251%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3252% Callbacks in the uipanel Civ1
3253%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3254%------------------------------------------------------------------------
3255% --- Executes on button press in SearchRange: determine the search range num_SearchBoxSize_1,num_SearchBoxSize_2
3256function SearchRange_Callback(hObject, eventdata, handles)
3257%------------------------------------------------------------------------
3258%determine pair numbers
3259if strcmp(get(handles.num_UMin,'Visible'),'off')
3260    set(handles.u_title,'Visible','on')
3261    set(handles.v_title,'Visible','on')
3262    set(handles.num_UMin,'Visible','on')
3263    set(handles.num_UMax,'Visible','on')
3264    set(handles.num_VMin,'Visible','on')
3265    set(handles.num_VMax,'Visible','on')
3266    set(handles.CoordUnit,'Visible','on')
3267    set(handles.TimeUnit,'Visible','on')
3268    set(handles.slash_title,'Visible','on')
3269    set(handles.min_title,'Visible','on')
3270    set(handles.max_title,'Visible','on')
3271    set(handles.unit_title,'Visible','on')
3272else
3273    get_search_range(hObject, eventdata, handles)
3274end
3275
3276%------------------------------------------------------------------------
3277% ---  determine the search range num_SearchBoxSize_1,num_SearchBoxSize_2 and shift
3278function get_search_range(hObject, eventdata, handles)
3279%------------------------------------------------------------------------
3280param_civ1=read_GUI(handles.Civ1);
3281umin=param_civ1.UMin;
3282umax=param_civ1.UMax;
3283vmin=param_civ1.VMin;
3284vmax=param_civ1.VMax;
3285%switch min_title and max_title in case of error
3286if umax<=umin
3287    umin_old=umin;
3288    umin=umax;
3289    umax=umin_old;
3290    set(handles.num_UMin,'String', num2str(umin))
3291    set(handles.num_UMax,'String', num2str(umax))
3292end
3293if vmax<=vmin
3294    vmin_old=vmin;
3295    vmin=vmax;
3296    vmax=vmin_old;
3297    set(handles.num_VMin,'String', num2str(vmin))
3298    set(handles.num_VMax,'String', num2str(vmax))
3299end   
3300if ~(isempty(umin)||isempty(umax)||isempty(vmin)||isempty(vmax))
3301    list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
3302    index=get(handles.ListPairCiv1,'Value');
3303    pair_string=list_pair{index};
3304    time=get(handles.ImaDoc,'UserData'); %get the set of times
3305    pxcm=get(handles.SearchRange,'UserData');
3306    mode_list=get(handles.ListPairMode,'String');
3307    mode_value=get(handles.ListPairMode,'Value');
3308    mode=mode_list{mode_value};     
3309    if isequal (mode, 'series(Di)' )
3310        ref_i=str2double(get(handles.ref_i,'String'));
3311        num1=ref_i-floor(index/2);%  first image numbers
3312        num2=ref_i+ceil(index/2);
3313        num_a=1;
3314        num_b=1;
3315    elseif isequal (mode, 'series(Dj)')
3316        num1=1;
3317        num2=1;
3318        ref_j=str2double(get(handles.ref_j,'String'));
3319        num_a=ref_j-floor(index/2);%  first image numbers
3320        num_b=ref_j+ceil(index/2);
3321    elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)     
3322        ref_i=str2double(get(handles.ref_i,'String'));
3323        num1=ref_i;
3324        num2=ref_i;
3325                r=regexp(pair_string,'(?<mode>(Di=)|(Dj=)) -*(?<num1>\d+)\|(?<num2>\d+)','names');
3326        if isempty(r)
3327            r=regexp(pair_string,'(?<num1>\d+)(?<mode>-)(?<num2>\d+)','names');
3328        end 
3329        num_a=str2num(r.num1);
3330        num_b=str2num(r.num2);
3331    end
3332    dt=time(num2+1,num_b+1)-time(num1+1,num_a+1);
3333    ibx=str2double(get(handles.num_CorrBoxSize_1,'String'));
3334    iby=str2double(get(handles.num_CorrBoxSize_2,'String'));
3335    umin=dt*pxcm*umin;
3336    umax=dt*pxcm*umax;
3337    vmin=dt*pxcm*vmin;
3338    vmax=dt*pxcm*vmax;
3339    shiftx=round((umin+umax)/2);
3340    shifty=round((vmin+vmax)/2);
3341    isx=(umax+2-shiftx)*2+param_civ1.Bx;
3342    isx=2*ceil(isx/2)+1;
3343    isy=(vmax+2-shifty)*2+param_civ1.Bx;
3344    isy=2*ceil(isy/2)+1;
3345    set(handles.num_SearchBoxShift_1,'String',num2str(shiftx));
3346    set(handles.num_SearchBoxShift_2,'String',num2str(shifty));
3347    set(handles.num_SearchBoxSize_1,'String',num2str(isx));
3348    set(handles.num_SearchBoxSize_2,'String',num2str(isy));
3349end
3350
3351%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3352% Callbacks in the uipanel Fix1
3353%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3354%------------------------------------------------------------------------
3355% --- Executes on button press in CheckMask.
3356function get_mask_fix1_Callback(hObject, eventdata, handles)
3357%------------------------------------------------------------------------
3358maskval=get(handles.CheckMask,'Value');
3359if isequal(maskval,0)
3360    set(handles.Mask,'String','')
3361else
3362    mask_displ='no mask'; %default
3363    filebase=get(handles.RootPath,'String');
3364    [nbslice, flag_mask]=get_mask(filebase,handles);
3365    if isequal(flag_mask,1)
3366        mask_displ=[num2str(nbslice) 'mask'];
3367    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3368        filebase_a=get(handles.RootFile_1,'String');
3369        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3370        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3371            mask_displ='no mask';
3372        end
3373    end
3374    if isequal(mask_displ,'no mask')
3375        [FileName, PathName, filterindex] = uigetfile( ...
3376            {'*.png', ' (*.png)';
3377            '*.png',  '.png files '; ...
3378            '*.*', 'All Files (*.*)'}, ...
3379            'Pick a mask file *.png',filebase);
3380        mask_displ=fullfile(PathName,FileName);
3381        if ~exist(mask_displ,'file')
3382            mask_displ='no mask';
3383        end
3384    end
3385    if isequal(mask_displ,'no mask')
3386        set(handles.CheckMask,'Value',0)
3387        set(handles.CheckMask,'Value',0)
3388        set(handles.CheckMask,'Value',0)
3389    else
3390        %set(handles.CheckMask,'Value',1)
3391        set(handles.CheckMask,'Value',1)
3392    end
3393    set(handles.Mask,'String',mask_displ)
3394    set(handles.Mask,'String',mask_displ)
3395    set(handles.Mask,'String',mask_displ)
3396end
3397
3398%------------------------------------------------------------------------
3399% --- Executes on button press in CheckMask: select box for mask option
3400function get_mask_civ2_Callback(hObject, eventdata, handles)
3401%------------------------------------------------------------------------
3402maskval=get(handles.CheckMask,'Value');
3403if isequal(maskval,0)
3404    set(handles.Mask,'String','')
3405else
3406    mask_displ='no mask'; %default
3407    filebase=get(handles.RootPath,'String');
3408    [nbslice, flag_mask]=get_mask(filebase,handles);
3409    if isequal(flag_mask,1)
3410        mask_displ=[num2str(nbslice) 'mask'];
3411    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3412        filebase_a=get(handles.RootFile_1,'String');
3413        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3414        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3415            mask_displ='no mask';
3416        end
3417    end
3418    if isequal(mask_displ,'no mask')
3419        [FileName, PathName, filterindex] = uigetfile( ...
3420            {'*.png', ' (*.png)';
3421            '*.png',  '.png files '; ...
3422            '*.*', 'All Files (*.*)'}, ...
3423            'Pick a mask file *.png',filebase);
3424        mask_displ=fullfile(PathName,FileName);
3425        if ~exist(mask_displ,'file')
3426            mask_displ='no mask';
3427        end
3428    end
3429    if isequal(mask_displ,'no mask')
3430        set(handles.CheckMask,'Value',0)
3431        set(handles.CheckMask,'Value',0)
3432    else
3433        set(handles.CheckMask,'Value',1)
3434    end
3435    set(handles.Mask,'String',mask_displ)
3436    set(handles.Mask,'String',mask_displ)
3437end
3438
3439%------------------------------------------------------------------------
3440% --- Executes on button press in CheckMask.
3441function get_mask_fix2_Callback(hObject, eventdata, handles)
3442%------------------------------------------------------------------------
3443maskval=get(handles.CheckMask,'Value');
3444if isequal(maskval,0)
3445    set(handles.Mask,'String','')
3446else
3447    mask_displ='no mask'; %default
3448    filebase=get(handles.RootPath,'String');
3449    [nbslice, flag_mask]=get_mask(filebase,handles);
3450    if isequal(flag_mask,1)
3451        mask_displ=[num2str(nbslice) 'mask'];
3452    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3453        filebase_a=get(handles.RootFile_1,'String');
3454        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3455        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3456            mask_displ='no mask';
3457        end
3458    end
3459    if isequal(mask_displ,'no mask')
3460        [FileName, PathName, filterindex] = uigetfile( ...
3461            {'*.png', ' (*.png)';
3462            '*.png',  '.png files '; ...
3463            '*.*', 'All Files (*.*)'}, ...
3464            'Pick a mask file *.png',filebase);
3465        mask_displ=fullfile(PathName,FileName);
3466        if ~exist(mask_displ,'file')
3467            mask_displ='no mask';
3468        end
3469    end
3470    if isequal(mask_displ,'no mask')
3471        set(handles.CheckMask,'Value',0)
3472    end
3473    set(handles.Mask,'String',mask_displ)
3474end
3475
3476%------------------------------------------------------------------------
3477% --- function called to look for mask files
3478function [nbslice, flag_mask]=get_mask(filebase,handles)
3479%------------------------------------------------------------------------
3480%detect mask files, images with appropriate file base
3481%[filebase '_' xx 'mask'], xx=nbslice
3482%flag_mask=1 indicates detection
3483
3484flag_mask=0;%default
3485nbslice=1;
3486
3487% subdir=get(handles.SubdirCiv1,'String');
3488[Path,Name]=fileparts(filebase);
3489if ~isdir(Path)
3490    msgbox_uvmat('ERROR','no path for input files')
3491    return
3492end
3493% currentdir=pwd;
3494% cd(Path);%move in the dir of the root name filebase
3495maskfiles=dir(fullfile(Path,[Name '_*mask_*.png']));%look for mask files
3496% cd(currentdir);%come back to the current working directory
3497if ~isempty(maskfiles)
3498    %     msgbox_uvmat('ERROR','no mask available, to create it use Tools/Make mask in the upper menu bar of uvmat')
3499    % else
3500    flag_mask=1;
3501    maskname=maskfiles(1).name;% take the first mask file in the list
3502    [Path2,Name,ext]=fileparts(maskname);
3503    Namedouble=double(Name);
3504    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3505    ind_mask=findstr('mask',Name);
3506    i=ind_mask-1;
3507    while val(i)==0 && i>0
3508        i=i-1;
3509    end
3510    nbslice=str2double(Name(i+1:ind_mask-1));
3511    if ~isnan(nbslice) && Name(i)=='_'
3512        flag_mask=1;
3513    else
3514        msgbox_uvmat('ERROR',['bad mask file ' Name ext ' found in ' Path2])
3515        return
3516        nbslice=1;
3517    end
3518end
3519
3520%------------------------------------------------------------------------
3521% --- function called to look for grid files
3522function [nbslice, flag_mask]=get_grid(filebase,handles)
3523%------------------------------------------------------------------------
3524flag_mask=0;%default
3525nbslice=1;
3526[Path,Name]=fileparts(filebase);
3527currentdir=pwd;
3528cd(Path);%move in the dir of the root name filebase
3529maskfiles=dir([Name '_*grid_*.grid']);%look for mask files
3530cd(currentdir);%come back to the current working directory
3531if ~isempty(maskfiles)
3532    flag_mask=1;
3533    maskname=maskfiles(1).name;% take the first mask file in the list
3534    [Path2,Name,ext]=fileparts(maskname);
3535    Namedouble=double(Name);
3536    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3537    ind_mask=findstr('grid',Name);
3538    i=ind_mask-1;
3539    while val(i)==0 && i>0
3540        i=i-1;
3541    end
3542    nbslice=str2double(Name(i+1:ind_mask-1));
3543    if ~isnan(nbslice) && Name(i)=='_'
3544        flag_mask=1;
3545    else
3546        msgbox_uvmat('ERROR',['bad grid file ' Name ext ' found in ' Path2])
3547        return
3548        nbslice=1;
3549    end
3550end
3551
3552%------------------------------------------------------------------------
3553% --- transform numbers to letters
3554function str=num2stra(num,nom_type)
3555%------------------------------------------------------------------------
3556if isempty(nom_type)
3557    str='';
3558elseif strcmp(nom_type(end),'a')
3559    str=char(96+num);
3560elseif strcmp(nom_type(end),'A')
3561    str=char(96+num);
3562elseif isempty(nom_type(2:end))%a single index
3563    str='';
3564else
3565    str=num2str(num);
3566end
3567
3568% %------------------------------------------------------------------------
3569% % --- Executes on button press in ListSubdirCiv1.
3570% function ListSubdirCiv1_Callback(hObject, eventdata, handles)
3571% %------------------------------------------------------------------------
3572% list_subdir_civ1=get(handles.ListSubdirCiv1,'String');
3573% val=get(handles.ListSubdirCiv1,'Value');
3574% SubDir=list_subdir_civ1{val};
3575% if strcmp(SubDir,'new...')
3576%     if get(handles.CheckCiv1,'Value')
3577%         SubDir='CIV'; %default subdirectory
3578%     else
3579%         msgbox_uvmat('ERROR','select CheckCiv1 to perform a new Civ operation')
3580%         return
3581%     end   
3582% end
3583% set(handles.SubdirCiv1,'String',SubDir);
3584% errormsg=find_netcpair_civ(handles,1);
3585% if ~isempty(errormsg)
3586%     msgbox_uvmat('ERROR',errormsg)
3587% end
3588%     
3589%------------------------------------------------------------------------
3590% % --- Executes on button press in ListSubdirCiv2.
3591% function ListSubdirCiv2_Callback(hObject, eventdata, handles)
3592% %------------------------------------------------------------------------
3593% list_subdir_civ2=get(handles.ListSubdirCiv2,'String');
3594% val=get(handles.ListSubdirCiv2,'Value');
3595% SubDir=list_subdir_civ2{val};
3596% if strcmp(SubDir,'new...')
3597%     if get(handles.CheckCiv2,'Value')
3598%         SubDir='CIV'; %default subdirectory
3599%     else
3600%         msgbox_uvmat('ERROR','select CheckCiv2 to perform a new Civ operation')
3601%         return
3602%     end
3603% end
3604% set(handles.SubdirCiv2,'String',SubDir);
3605
3606%------------------------------------------------------------------------
3607% --- Executes on button press in CheckGrid.
3608function CheckGrid_Callback(hObject, eventdata, handles)
3609%------------------------------------------------------------------------
3610value=get(hObject,'Value');
3611hparent=get(hObject,'parent');
3612hchildren=get(hparent,'children');
3613handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3614handle_dx=findobj(hchildren,'tag','num_Dx');
3615handle_dy=findobj(hchildren,'tag','num_Dy');
3616handle_title_dx=findobj(hchildren,'tag','title_Dx');
3617handle_title_dy=findobj(hchildren,'tag','title_Dy');
3618testgrid=0;
3619filegrid='';
3620if value
3621    filebase=get(handles.RootPath,'String');
3622    [nbslice, flag_grid]=get_grid(filebase,handles);% look for a grid with appropriate name
3623    if isequal(flag_grid,1)
3624        filegrid=[num2str(nbslice) 'grid'];
3625        testgrid=1;
3626    else % browse for a grid
3627        filegrid=get(hObject,'UserData');%look for previous grid name stored as UserData
3628        if exist(filegrid,'file')
3629            filebase=filegrid;
3630        end
3631        [FileName, PathName, filterindex] = uigetfile( ...
3632            {'*.grid', ' (*.grid)';
3633            '*.grid',  '.grid files '; ...
3634            '*.*', 'All Files (*.*)'}, ...
3635            'Pick a file',filebase);
3636        filegrid=fullfile(PathName,FileName);
3637        set(hObject,'UserData',filegrid);%store for future use
3638        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filegrid,'file'))
3639            testgrid=1;
3640        end
3641    end
3642end
3643if testgrid
3644    set(handle_dx,'Visible','off');
3645    set(handle_dy,'Visible','off');
3646    set(handle_title_dy,'Visible','off');
3647    set(handle_title_dx,'Visible','off');
3648    set(handle_txtbox,'Visible','on')
3649    set(handle_txtbox,'String',filegrid)
3650else
3651    set(hObject,'Value',0);
3652    set(handle_dx,'Visible','on');
3653    set(handle_dy,'Visible','on');
3654    set(handle_title_dy,'Visible','on');
3655    set(handle_title_dx,'Visible','on');
3656    set(handle_txtbox,'Visible','off')
3657end
3658
3659%% if hObject is on the checkciv1 frame, duplicate action for checkciv2 frame
3660PanelName=get(hparent,'tag');
3661if strcmp(PanelName,'Civ1')
3662    hchildren=get(handles.Civ2,'children');
3663    handle_checkbox=findobj(hchildren,'tag','CheckGrid');
3664    handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3665    handle_dx=findobj(hchildren,'tag','num_Dx');
3666    handle_dy=findobj(hchildren,'tag','num_Dy');
3667    handle_title_dx=findobj(hchildren,'tag','title_Dx');
3668    handle_title_dy=findobj(hchildren,'tag','title_Dy');
3669    set(handle_checkbox,'UserData',filegrid);%store for future use
3670    if testgrid
3671        set(handle_checkbox,'Value',1);
3672        set(handle_dx,'Visible','off');
3673        set(handle_dy,'Visible','off');
3674        set(handle_title_dx,'Visible','off');
3675        set(handle_title_dy,'Visible','off');
3676        set(handle_txtbox,'Visible','on')
3677        set(handle_txtbox,'String',filegrid)
3678%     else
3679%         set(handle_checkbox,'Value',0);
3680%         set(handles.CheckGrid,'Value',0);
3681%         set(handle_dx,'Visible','on');
3682%         set(handle_dy,'Visible','on');
3683%          set(handle_title_dx,'Visible','on');
3684%         set(handle_title_dy,'Visible','on');
3685%         set(handle_txtbox,'Visible','off')
3686    end
3687end
3688
3689%------------------------------------------------------------------------
3690% --- Executes on button press in CheckMask: common to all panels (civ1, Civ2..)
3691function CheckMask_Callback(hObject, eventdata, handles)
3692%------------------------------------------------------------------------
3693value=get(hObject,'Value');
3694hparent=get(hObject,'parent');
3695parent_tag=get(hparent,'Tag');
3696hchildren=get(hparent,'children');
3697handle_txtbox=findobj(hchildren,'tag','Mask');% look for the mask name box in the same panel
3698testmask=0;
3699if value
3700    filebase=get(handles.RootPath,'String');
3701    [nbslice, flag_mask]=get_mask(filebase,handles);% look for a mask with appropriate name
3702    if isequal(flag_mask,1)
3703        filemask=[num2str(nbslice) 'mask'];
3704        testmask=1;
3705    else % browse for a mask
3706        filemask=get(hObject,'UserData');%look for previous mask name stored as UserData
3707        if exist(filemask,'file')
3708            filebase=filemask;
3709        end
3710        [FileName, PathName] = uigetfile( ...
3711            {'*.png', ' (*.png)';
3712            '*.png',  '.png files '; ...
3713            '*.*', 'All Files (*.*)'}, ...
3714            'Pick a mask file *.png',filebase);
3715        filemask=fullfile(PathName,FileName);
3716        set(hObject,'UserData',filemask);%store for future use
3717        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filemask,'file'))
3718            testmask=1;
3719        end
3720    end
3721end
3722if testmask
3723    if strcmp(parent_tag,'Civ1')
3724        set(handles.Mask,'Visible','on')
3725        set(handles.Mask,'String',filemask)
3726    set(handles.CheckMask,'Value',1)
3727    end
3728%     switch parent_tag
3729% %         case 'Fix1'
3730% %             stage=2;
3731%         case 'Civ2'
3732%              stage=3;
3733% %         case 'Fix2'
3734% %             stage=4;
3735%     end
3736%     set(handles.Mask(stage:end),'Visible','on')
3737%     set(handles.Mask(stage:end),'String',filemask)
3738%     set(handles.CheckMask(stage:end),'Value',1)
3739else
3740    set(hObject,'Value',0);
3741    set(handle_txtbox,'Visible','off')
3742end
3743
3744
3745% --- Executes on button press in get_gridpatch1.
3746function get_gridpatch1_Callback(hObject, eventdata, handles)
3747filebase=get(handles.RootPath,'String');
3748[FileName, PathName, filterindex] = uigetfile( ...
3749    {'*.grid', ' (*.grid)';
3750    '*.grid',  '.grid files '; ...
3751    '*.*', 'All Files (*.*)'}, ...
3752    'Pick a file',filebase);
3753filegrid=fullfile(PathName,FileName);
3754set(handles.grid_patch1,'string',filegrid);
3755
3756
3757%------------------------------------------------------------------------
3758% --- Executes on button press in get_gridpatch2.
3759function get_gridpatch2_Callback(hObject, eventdata, handles)
3760%------------------------------------------------------------------------
3761
3762
3763%------------------------------------------------------------------------
3764% --- STEREO Interp
3765function cmd=RUN_STINTERP(stinterpBin,filename_A_nc,filename_B_nc,filename_nc,nx_patch,ny_patch,rho_patch,subdomain_patch,thresh_value,xmlA,xmlB)
3766%------------------------------------------------------------------------
3767namelog=[filename_nc(1:end-3) '_stinterp.log'];
3768cmd=[stinterpBin ' -f1 ' filename_A_nc  ' -f2 ' filename_B_nc ' -f  ' filename_nc ...
3769    ' -m ' nx_patch  ' -n ' ny_patch ' -ro ' rho_patch ' -nopt ' subdomain_patch ' -c1 ' xmlA ' -c2 ' xmlB '  -xy  x -Nfy 1024 > ' namelog ' 2>&1']; % redirect standard output to the log file
3770
3771%------------------------------------------------------------------------
3772%--read images and convert them to the uint16 format used for PIV
3773function A=read_image(filename,type_ima,num,movieobject)
3774%------------------------------------------------------------------------
3775%num is the view number needed for an avi movie
3776switch type_ima
3777    case 'movie'
3778        A=read(movieobject,num);
3779    case 'avi'
3780        mov=aviread(filename,num);
3781        A=frame2im(mov(1));
3782    case 'multimage'
3783        A=imread(filename,num);
3784    case 'image'
3785        A=imread(filename);
3786end
3787siz=size(A);
3788if length(siz)==3;%color images
3789    A=sum(double(A),3);
3790    A=uint16(A);
3791end
3792
3793
3794%------------------------------------------------------------------------
3795% --- Executes on button press in get_ref_fix1.
3796function get_ref_fix1_Callback(hObject, eventdata, handles)
3797%------------------------------------------------------------------------
3798filebase=get(handles.RootPath,'String');
3799[FileName, PathName, filterindex] = uigetfile( ...
3800    {'*.nc', ' (*.nc)';
3801    '*.nc',  'netcdf files '; ...
3802    '*.*', 'All Files (*.*)'}, ...
3803    'Pick a file',filebase);
3804
3805fileinput=[PathName FileName];
3806sizf=size(fileinput);
3807if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3808%[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3809[Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3810ref.filebase=fullfile(Path,File);
3811% ref.num_a=stra2num(str_a);
3812% ref.num_b=stra2num(str_b);
3813% ref.num1=str2double(field_count);
3814% ref.num2=str2double(str2);
3815browse=[];%initialisation
3816if ~isequal(ref.ext,'.nc')
3817    msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3818    return
3819end
3820set(handles.ref_fix1,'String',[fullfile(ref.subdir,File) '....nc']);
3821set(handles.ref_fix1,'UserData',ref)
3822menu_field{1}='civ1';
3823Data=nc2struct(fileinput,[]);
3824if isfield(Data,'patch') && isequal(Data.patch,1)
3825    menu_field{2}='filter1';
3826end
3827if isfield(Data,'civ2') && isequal(Data.civ2,1)
3828    menu_field{3}='civ2';
3829end
3830if isfield(Data,'patch2') && isequal(Data.patch2,1)
3831    menu_field{4}='filter2';
3832end
3833set(handles.field_ref1,'String',menu_field);
3834set(handles.field_ref1,'Value',length(menu_field));
3835set(handles.num_MinVel,'Value',2);
3836set(handles.num_MinVel,'String','1');%default threshold
3837set(handles.ref_fix1,'Enable','on')
3838
3839%------------------------------------------------------------------------
3840% --- Executes on button press in get_ref_fix2.
3841function get_ref_fix2_Callback(hObject, eventdata, handles)
3842%------------------------------------------------------------------------
3843if isequal(get(handles.get_ref_fix2,'Value'),1)
3844    filebase=get(handles.RootPath,'String');
3845    [FileName, PathName, filterindex] = uigetfile( ...
3846        {'*.nc', ' (*.nc)';
3847        '*.nc',  'netcdf files '; ...
3848        '*.*', 'All Files (*.*)'}, ...
3849        'Pick a file',filebase);
3850    fileinput=[PathName FileName];
3851    sizf=size(fileinput);
3852    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3853    %[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3854    [Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3855    ref.filebase=fullfile(Path,File);
3856%     ref.num_a=stra2num(str_a);
3857%     ref.num_b=stra2num(str_b);
3858%     ref.num1=str2num(field_count);
3859%     ref.num2=str2num(str2);
3860    browse=[];%initialisation
3861    if ~isequal(ref.ext,'.nc')
3862        msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3863        return
3864    end
3865    set(handles.ref_fix2,'String',[fullfile(ref.subdir,File) '....nc']);
3866    set(handles.ref_fix2,'UserData',ref)
3867    menu_field{1}='civ1';
3868    Data=nc2struct(fileinput,[]);
3869    if isfield(Data,'patch') && isequal(Data.patch,1)
3870        menu_field{2}='filter1';
3871    end
3872    if isfield(Data,'civ2') && isequal(Data.civ2,1)
3873        menu_field{3}='civ2';
3874    end
3875    if isfield(Data,'patch2') && isequal(Data.patch2,1)
3876        menu_field{4}='filter2';
3877    end
3878    set(handles.field_ref2,'String',menu_field);
3879    set(handles.field_ref2,'Value',length(menu_field));
3880    set(handles.num_MinVel,'Value',2);
3881    set(handles.num_MinVel,'String','1');%default threshold
3882    set(handles.ref_fix2,'Enable','on')
3883    set(handles.ref_fix2,'Visible','on')
3884    set(handles.field_ref2,'Visible','on')
3885else
3886    set(handles.ref_fix2,'Visible','off')
3887    set(handles.field_ref2,'Visible','off')
3888end
3889
3890%------------------------------------------------------------------------
3891function ref_fix1_Callback(hObject, eventdata, handles)
3892%------------------------------------------------------------------------
3893set(handles.num_MinVel,'Value',1);
3894set(handles.field_ref1,'Value',1)
3895set(handles.field_ref1,'String',{' '})
3896set(handles.ref_fix1,'UserData',[]);
3897set(handles.ref_fix1,'String','');
3898set(handles.thresh_vel1,'String','0');
3899
3900%------------------------------------------------------------------------
3901function ref_fix2_Callback(hObject, eventdata, handles)
3902%------------------------------------------------------------------------
3903set(handles.num_MinVel,'Value',1);
3904set(handles.field_ref2,'Value',1)
3905set(handles.field_ref2,'String',{' '})
3906set(handles.ref_fix2,'UserData',[]);
3907set(handles.ref_fix2,'String','');
3908set(handles.num_MinVel,'String','0');
3909
3910%------------------------------------------------------------------------
3911% --- TO ABANDON Executes on button press in test_stereo1.
3912function CheckStereo_Callback(hObject, eventdata, handles)
3913%------------------------------------------------------------------------
3914hparent=get(hObject,'parent');
3915parent_tag=get(hparent,'Tag');
3916hchildren=get(hparent,'children');
3917handle_txtbox=findobj(hchildren,'tag','txt_Mask');
3918if isequal(get(hObject,'Value'),0)
3919    set(handles.num_SubdomainSize,'Visible','on')
3920    set(handles.num_FieldSmooth,'Visible','on')
3921else
3922    set(handles.num_SubdomainSize,'Visible','off')
3923    set(handles.num_FieldSmooth,'Visible','off')
3924end
3925
3926% %------------------------------------------------------------------------
3927% % --- Executes on button press in CheckStereo.
3928% function StereoCheck_Callback(hObject, eventdata, handles)
3929% %------------------------------------------------------------------------
3930% if isequal(get(handles.CheckStereo,'Value'),0)
3931%     set(handles.num_SubdomainSize,'Visible','on')
3932%     set(handles.num_FieldSmooth,'Visible','on')
3933% else
3934%     set(handles.num_SubdomainSize,'Visible','off')
3935%     set(handles.num_FieldSmooth,'Visible','off')
3936% end
3937
3938%------------------------------------------------------------------------
3939% --- Executes on button press in TestCiv1: prepare the image correlation function
3940% activated by mouse motion
3941function TestCiv1_Callback(hObject, eventdata, handles)
3942%------------------------------------------------------------------------
3943drawnow
3944if get(handles.TestCiv1,'Value')
3945    set(handles.TestCiv1,'BackgroundColor',[0.7 0.7 0.7])% paint TestCiv1 button to grey to confirm civ launch
3946    ref_i=str2double(get(handles.ref_i,'String'));% read reference i index
3947    if strcmp(get(handles.ref_j,'Visible'),'on')
3948        ref_j=str2double(get(handles.ref_j,'String'));% read reference j index if relevant
3949    else
3950        ref_j=1;%default j index
3951    end
3952    [filecell,i1,i2]=set_civ_filenames(handles,ref_i,ref_j,[1 0 0 0 0 0]);% get the corresponding file name and indices
3953    Data.ListVarName={'ny','nx','A'};
3954    Data.VarDimName= {'ny','nx',{'ny','nx'}};
3955
3956    Data.A=imread(filecell.ima1.civ1{1}); % read the first image
3957    if ndims(Data.A)==3 %case of color image
3958        Data.VarDimName= {'ny','nx',{'ny','nx','rgb'}};
3959    end
3960    Data.ny=[size(Data.A,1) 1];
3961    Data.nx=[1 size(Data.A,2)];
3962    Data.CoordUnit='pixel';% used to set equal scaling for x and y in image dispaly
3963    par_civ1=read_GUI(handles.Civ1);
3964    par_civ1.FileTypeA=get_file_type(filecell.ima1.civ1{1});
3965    par_civ1.ImageWidth=size(Data.A,2);
3966    par_civ1.ImageHeight=size(Data.A,1);
3967    par_civ1.Mask='all';% will provide only the grid set for PIV, no image correlation
3968    par_civ1.FrameIndexA=num2str(i1);
3969    par_civ1.FrameIndexB=num2str(i2);
3970    Param.Civ1=par_civ1;
3971    Grid=civ_matlab(Param);% get the grid of x, y positions set for PIV
3972    hview_field=view_field(Data); %view the image in the GUI view_field
3973    set(0,'CurrentFigure',hview_field)
3974    hhview_field=guihandles(hview_field);
3975    set(hview_field,'CurrentAxes',hhview_field.axes3)
3976    ViewData=get(hview_field,'UserData');
3977    ViewData.CivHandle=handles.civ;% indicate the handle of the civ GUI in view_field
3978    ViewData.axes3.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
3979    ViewData.axes3.X=Grid.Civ1_X; %keep the set of points in memeory
3980    ViewData.axes3.Y=Grid.Civ1_Y;
3981    set(hview_field,'UserData',ViewData)
3982    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3983    if isempty(corrfig)
3984        corrfig=figure;
3985        set(corrfig,'tag','corrfig')
3986        set(corrfig,'name','image correlation')
3987        set(corrfig,'DeleteFcn',{@closeview_field})%
3988    end
3989    set(handles.TestCiv1,'BackgroundColor',[1 0 0])
3990else
3991    set(handles.TestCiv1,'BackgroundColor',[1 0 0])% paint button to red
3992    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3993    if ~isempty(corrfig)
3994        delete(corrfig)
3995    end
3996    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
3997    if ~isempty(hview_field)
3998        delete(hview_field)
3999    end
4000end
4001
4002%------------------------------------------------------------------------
4003%----function introduced for the correlation window figure, activated by deleting this window
4004function closeview_field(gcbo,eventdata)
4005%------------------------------------------------------------------------
4006hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
4007if ~isempty(hview_field)
4008    delete(hview_field)
4009end
4010
4011%------------------------------------------------------------------------
4012% --- Executes on button press in CheckThreshold.
4013function CheckThreshold_Callback(hObject, eventdata, handles)
4014%------------------------------------------------------------------------
4015huipanel=get(hObject,'parent');
4016obj(1)=findobj(huipanel,'Tag','num_MinIma');
4017obj(2)=findobj(huipanel,'Tag','num_MaxIma');
4018obj(3)=findobj(huipanel,'Tag','title_Threshold');
4019if get(hObject,'Value')
4020    set(obj,'Visible','on')
4021else
4022    set(obj,'Visible','off')
4023end
4024
4025%------------------------------------------------------------------------
4026function [cmd,errormsg]=cmd_civ1(filename,Param)
4027%------------------------------------------------------------------------
4028%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4029%changes : filename_cmx -> filename ( no extension )
4030cmd='';
4031filename=regexprep(filename,'.nc',''); %file name for the result
4032if isequal(Param.Civ1.Dt,0)
4033    Param.Civ1.Dt=1 ;%case of 'displacement' mode
4034end
4035Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'.png','');
4036Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'.png','');
4037[fid,errormsg]=fopen([filename '.civ1.cmx'],'w');
4038if isequal(fid,-1)
4039    errormsg=['cmd file ' filename ' cannot be created: ' errormsg];
4040    return
4041end
4042fprintf(fid,['##############   CMX file' '\n' ]);
4043fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4044fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4045fprintf(fid,  ['XX' '\n' ]);
4046if isfield(Param.Civ1,'Mask')
4047    fprintf(fid,  ['Mask ' 'y' '\n' ]);
4048    fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.Mask,'\\','\\\\') '\n' ]);
4049else
4050    fprintf(fid,  ['Mask ' 'n' '\n' ]);
4051    fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4052end
4053fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageWidth) ' ' num2str(Param.Civ1.ImageHeight) '\n' ]);   %VERIFIER CAS GENERAL ?
4054fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.CorrBoxSize(1)) ' ' num2str(Param.Civ1.CorrBoxSize(2)) '\n' ]);
4055fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.SearchBoxSize(1)) ' ' num2str(Param.Civ1.SearchBoxSize(2)) '\n' ]);
4056fprintf(fid,   ['RO ' num2str(Param.Civ1.CorrSmooth) '\n' ]);
4057if isfield(Param.Civ1,'Grid')
4058    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4059else
4060    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
4061end
4062fprintf(fid,   ['XX 1.0' '\n' ]);
4063fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.Time) '\n' ]);
4064fprintf(fid,  ['PixCmXY ' '1' ' ' '1' '\n' ]);
4065fprintf(fid,  ['XX 1' '\n' ]);
4066fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.SearchBoxShift(1)) ' '  num2str(Param.Civ1.SearchBoxShift(2)) '\n' ]);
4067if isfield(Param.Civ1,'Grid')
4068    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4069    fprintf(fid,   ['GridName ' regexprep(Param.Civ1.Grid,'\\','\\\\') '\n' ]);
4070else
4071    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4072    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4073end
4074fprintf(fid,   ['XX 85' '\n' ]);
4075fprintf(fid,   ['XX 1.0' '\n' ]);
4076fprintf(fid,   ['XX 1.0' '\n' ]);
4077fprintf(fid,   ['Hart 1' '\n' ]);
4078fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
4079fprintf(fid,   ['Deformation 0' '\n' ]);
4080fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4081fprintf(fid,   ['IntensityMin 0' '\n' ]);
4082if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
4083    fprintf(fid,  ['SeuilImage n' '\n' ]);
4084    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4085else% Image threshold  activated
4086    if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
4087        Param.Civ1.MaxIma=2^Param.Civ1.ImageBitDepth;%take the max image value as upper bound by default
4088    end
4089    fprintf(fid,  ['SeuilImage y' '\n' ]);
4090    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
4091end
4092fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
4093fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
4094fclose(fid);
4095
4096if(isunix) %unix (or Mac) system
4097    cmd=['cp -f ' filename '.civ1.cmx ' filename '.cmx \n '];% the cmx file gives the name to the nc file
4098    cmd=[cmd Param.xml.Civ1Bin ' -f ' filename '.cmx >' filename '.civ1.log \n ' ]; % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
4099    cmd=[cmd 'rm ' filename '.cmx'];
4100else %Windows system
4101    filename=regexprep(filename,'\\','\\\\');
4102    cmd=['copy /Y "' filename '.civ1.cmx" "' filename '.cmx" \n '];
4103    cmd=[cmd '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\')...
4104        '" -f "' filename '.cmx" >"' filename '.civ1.log" \n ' ]; % redirect standard output to the log file
4105    cmd=[cmd 'del "' filename '.cmx"'];
4106end
4107
4108
4109function cmd=cmd_fix(filename,Param,fixname)
4110%%
4111switch fixname
4112    case 'Fix1'
4113        fi2_value=num2str(Param.(fixname).CheckF2);
4114    case 'Fix2'
4115        fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
4116end
4117filename=regexprep(filename,'.nc','');
4118MaskName_string='';%default
4119MaxVel_string='';%default
4120if ~isempty(Param.(fixname).MinVel)
4121    MaxVel_string=[' -threshV ' num2str(Param.(fixname).MinVel)];
4122end
4123if isunix
4124    cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
4125        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4126        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4127        ' >' filename '.' lower(fixname) '.log 2>&1'];
4128else
4129    cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
4130        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4131        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4132        ' > "' filename '.' lower(fixname) '.log"'];
4133    cmd=regexprep(cmd,'\\','\\\\');
4134end
4135
4136
4137function cmd=cmd_patch(filename,Param,patchname)
4138%% ------------------------------------------------------------------------
4139filename=regexprep(filename,'.nc','');
4140if isunix
4141    cmd=[Param.xml.PatchBin...
4142        ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
4143        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
4144        ' -nopt ' num2str(Param.(patchname).SubdomainSize) ...
4145        '  > ' filename '.' lower(patchname) '.log 2>&1']; % redirect standard output to the log file
4146else
4147    cmd=['"' Param.xml.PatchBin...
4148        '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
4149        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
4150        ' -nopt ' num2str(Param.(patchname).SubdomainSize)...
4151        '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
4152    cmd=regexprep(cmd,'\\','\\\\');
4153end
4154
4155%------------------------------------------------------------------------
4156% --- CheckCiv2  CheckCiv2  CheckCiv2 CheckCiv2
4157function [cmd,errormsg]=cmd_civ2(filename,Param)
4158%------------------------------------------------------------------------
4159%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4160% global civ2Bin sge%name of the executable for checkciv1 calculation
4161 cmd='';
4162filename=regexprep(filename,'.nc','');
4163if isequal(Param.Civ2.Dt,'0')
4164    Param.Civ2.Dt='1' ;%case of 'displacement' mode
4165end
4166Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'.png','');
4167Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'.png','');% bug : .png appears two times ?
4168[fid,errormsg]=fopen([filename '.civ2.cmx'],'w');
4169if isequal(fid,-1)
4170    return
4171end
4172fprintf(fid,['##############   CMX file' '\n' ]);
4173fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4174fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4175fprintf(fid,  ['XX' '\n' ]);
4176if isfield(Param.Civ2,'Mask')
4177    fprintf(fid,  ['Mask ' 'y' '\n' ]);
4178    fprintf(fid,  ['MaskName ' regexprep(Param.Civ2.Mask,'\\','\\\\') '\n' ]);
4179else
4180    fprintf(fid,  ['Mask ' 'n' '\n' ]);
4181    fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4182end
4183% fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
4184% fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
4185fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageWidth) ' ' num2str(Param.Civ2.ImageHeight) '\n' ]); 
4186% fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
4187fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n' ]);
4188fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n']);
4189fprintf(fid, ['RO ' num2str(Param.Civ2.CorrSmooth) '\n']);
4190if isfield(Param.Civ2,'Grid')
4191    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4192else
4193    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
4194end
4195% fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
4196fprintf(fid, ['XX 1.0' '\n' ]);
4197fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.Time) '\n' ]);
4198fprintf(fid, ['PixCmXY ' '1' ' ' '1' '\n' ]);
4199fprintf(fid, ['XX 1' '\n' ]);
4200fprintf(fid, 'ShiftXY 0 0\n');
4201if isfield(Param.Civ2,'Grid')
4202    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4203    fprintf(fid,   ['GridName ' regexprep(Param.Civ2.Grid,'\\','\\\\') '\n' ]);
4204else
4205    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4206    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4207end
4208% fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
4209% fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
4210fprintf(fid, ['XX 85' '\n' ]);
4211fprintf(fid, ['XX 1.0' '\n' ]);
4212fprintf(fid, ['XX 1.0' '\n' ]);
4213fprintf(fid, ['Hart 1' '\n' ]);
4214fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
4215fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
4216fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4217fprintf(fid,   ['IntensityMin 0' '\n' ]);
4218
4219if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
4220    fprintf(fid,  ['SeuilImage n' '\n' ]);
4221    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4222else% Image threshold  activated
4223    if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
4224        Param.Civ2.MaxIma=2^Param.Civ2.ImageBitDepth;%take the max image value as upper bound by default
4225    end
4226    fprintf(fid,  ['SeuilImage y' '\n' ]);
4227    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
4228end
4229fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
4230fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
4231fclose(fid);
4232
4233if(isunix)
4234    cmd=['cp -f ' filename '.civ2.cmx ' filename '.cmx\n'...
4235        Param.xml.Civ2Bin ' -f ' filename  '.cmx >' filename '.civ2.log \n '... % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
4236        'rm ' filename '.cmx \n'];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
4237else
4238    filename=regexprep(filename,'\\','\\\\');
4239    cmd=['copy /Y "' filename '.civ2.cmx" "' filename '.cmx" \n'...
4240        '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f "' filename  '.cmx" >"' filename '.civ2.log" \n'...
4241        'del "' filename '.cmx" \n'];
4242end
4243
4244%------------------------------------------------------------------------
4245% --- CheckCiv1  Unified: TO ABADON
4246function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
4247%------------------------------------------------------------------------
4248%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4249%global CivBin%name of the executable for checkciv1 calculation
4250
4251civ1.image1=par.ImageA;
4252civ1.image2=par.ImageB;
4253civ1.imageSize_X=par.npx;
4254civ1.imageSize_Y=par.npy;
4255civ1.outputFileName=[filename '.nc'];
4256civ1.correlationBoxesSize_X=par.ibx;
4257civ1.correlationBoxesSize_Y=par.iby;
4258civ1.searchBoxesSize_X=par.isx;
4259civ1.searchBoxesSize_Y=par.isy;
4260civ1.globalShift_X=par.shiftx;
4261civ1.globalShift_Y=par.shifty;
4262civ1.ro=par.rho;
4263civ1.hart='y';
4264if isequal(par.gridflag,'y')
4265    civ1.grid=par.gridname;
4266else
4267    civ1.grid='n';
4268    civ1.gridSpacing_X=par.dx;
4269    civ1.gridSpacing_Y=par.dy;
4270end
4271if isequal(par.maskflag,'y')
4272    civ1.mask=par.maskname;
4273end
4274civ1.dt=par.Dt;
4275civ1.unit='pixel';
4276civ1.absolut_time_T0=par.Time;
4277civ1.pixcmx='1';
4278civ1.pixcmy='1';
4279civ1.convectFlow='n';
4280
4281xml_civ1_parameters=civ1;
4282
4283%------------------------------------------------------------------------
4284% --- CheckCiv2  Unified: TO ABADON
4285function civ2=CIV2_CMD_Unified(filename,namelog,par)
4286%------------------------------------------------------------------------
4287%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4288%global CivBin%name of the executable for checkciv1 calculation
4289
4290filename=regexprep(filename,'.nc','');
4291
4292civ2.image1=par.ImageA;
4293civ2.image2=par.ImageB;
4294civ2.imageSize_X=par.npx;
4295civ2.imageSize_Y=par.npy;
4296civ2.inputFileName=[par.filename_nc1 '.nc'];
4297civ2.outputFileName=[filename '.nc'];
4298civ2.correlationBoxesSize_X=par.ibx;
4299civ2.correlationBoxesSize_Y=par.iby;
4300civ2.ro=par.rho;
4301%checkciv2.decimalShift=par.CheckDecimal;
4302%checkciv2.CheckDeformation=par.CheckDeformation;
4303if isequal(par.decimal,'1')
4304    civ2.decimalShift='y';
4305else
4306    civ2.decimalShift='n';
4307end
4308if isequal(par.deformation,'1')
4309    civ2.deformation='y';
4310else
4311    civ2.deformation='n';
4312end
4313if isequal(par.gridflag,'y')
4314    civ2.grid=par.gridname;
4315else
4316    civ2.grid='n';
4317    civ2.gridSpacing_X=par.dx;
4318    civ2.gridSpacing_Y=par.dy;
4319end
4320civ2.gridSpacing_X='10';
4321civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
4322if isequal(par.maskflag,'y')
4323    civ2.mask=par.maskname;
4324else
4325    civ2.mask='n';
4326end
4327civ2.dt=par.Dt;
4328civ2.unit='pixel';
4329civ2.absolut_time_T0=par.Time;
4330civ2.pixcmx='1';
4331civ2.pixcmy='1';
4332civ2.convectFlow='n';
4333
4334
4335% --- Executes on button press in TestPatch1.
4336function TestPatch1_Callback(hObject, eventdata, handles)
4337set(handles.TestPatch1,'BackgroundColor',[1 1 0])
4338drawnow
4339if get(handles.TestPatch1,'Value')
4340    ref_i=str2double(get(handles.ref_i,'String'));
4341    if strcmp(get(handles.ref_j,'Visible'),'on')
4342        ref_j=str2double(get(handles.ref_j,'String'));
4343    else
4344        ref_j=1;%default
4345    end
4346    filecell=set_civ_filenames(handles,ref_i,ref_j,[0 0 1 0 0 0]);   
4347    Data.ListVarName={'ny','nx','A'};
4348    Data.VarDimName= {'ny','nx',{'ny','nx'}};   
4349    param_patch1=read_GUI(handles.Patch1);
4350    param_patch1.CivFile=filecell.nc.civ1{1};
4351    Param.Patch1=param_patch1;
4352    for irho=1:7
4353        [Data,errormsg]=civ_matlab(Param);% get the grid of x, y positions set for PIV
4354        if ~isempty(errormsg)
4355            msgbox_uvmat('ERROR',errormsg)
4356            return
4357        end
4358        SmoothingParam(irho)=Param.Patch1.FieldSmooth;
4359        Data.Civ1_U_Diff=Data.Civ1_U_Diff(Data.Civ1_FF==0);
4360        Data.Civ1_V_Diff=Data.Civ1_V_Diff(Data.Civ1_FF==0);
4361        DiffVel(irho)=sqrt(mean(Data.Civ1_U_Diff.*Data.Civ1_U_Diff+Data.Civ1_V_Diff.*Data.Civ1_V_Diff))
4362        NbSites(irho,:)=Data.Civ1_NbSites*numel(Data.Civ1_NbSites)/numel(Data.Civ1_U_Diff);
4363        Param.Patch1.SmoothingParam=2*Param.Patch1.FieldSmooth;
4364    end
4365    figure
4366    plot(SmoothingParam,DiffVel,'b',SmoothingParam,NbSites,'r')
4367    set(handles.TestPatch1,'BackgroundColor',[1 0 0])
4368else
4369    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4370    if ~isempty(corrfig)
4371        delete(corrfig)
4372    end
4373    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
4374    if ~isempty(hview_field)
4375        delete(hview_field)
4376    end
4377end
4378%'nomtype2pair': creates nomencalture for index pairs knowing the image nomenclature
4379%---------------------------------------------------------------------
4380% [nom_type_pair]=nomtype2pair(nom_type,Dti,Dtj);
4381%---------------------------------------------------------------------           
4382
4383% OUTPUT:
4384%nom_type_nc
4385
4386%---------------------------------------------------------------------
4387% INPUT:
4388% 'nom_type': string defining the kind of nomenclature used:
4389     %nom_type='': constant name [filebase ext] (default output if 'nom_type' is undefined)
4390     %nom_type='*': the same  file [filebase ext] contains successive fields (ex avi movies)
4391     %nom_type='_i': series of files with a single index i preceded by '_'(e.g. 'aa_45.png').
4392     %nom_type='#' series of indexed images wich is not series_i [filebase index ext], e.g. 'aa045.jpg' or 'aa45.tif'
4393     %nom_type='_i_j' matrix of files with two indices i and j separated by '_'(e.g. 'aa_45_2.png')
4394     %nom_type='_i1-i2' from pairs from a single index (e.g. 'aa_45-47.nc')
4395     %nom_type='_i_j1-j2'pairs of j indices (e.g. 'aa_45_2-3.nc')
4396     %nom_type='_i1-i2_j' pairs of i indices (e.g. 'aa_45-46_2.nc')
4397     %nom_type='#a','#A', with a numerical index and an index letter(e.g.'aa045b.png'), OBSOLETE (replaced by 'series_i_j')
4398     %nom_type='%03d' or '%04d', series of indexed images with numbers completed with zeros to 3 or 4 digits, e.g.'aa045.tif'
4399     %nom_type='_%03d', '_%04d', or '_%05d', series of indexed images with _ and numbers completed with zeros to 3, 4 or 5 digits, e.g.'aa_045.tif'
4400     %nom_type='raw_SMD', same as '#a' but with no extension ext='', OBSOLETE
4401     %nom_type='#_ab' from pairs of '#a' images (e.g. 'aa045bc.nc'), ext='.nc', OBSOLETE (replaced by 'netc_2D')
4402     %nom_type='%3dab' from pairs of '%3da' images (e.g. 'aa045bc.nc'), ext='.nc', OBSOLETE (replaced by 'netc_2D')
4403% Dti: ~=0 if i index pairs are used
4404% Dtj: ~=0 if i index pairs are used
4405
4406function NomTypeNc=nomtype2pair(NomTypeIma,mode)
4407
4408%determine nom_type_nc:
4409NomTypeNc=NomTypeIma;%default
4410switch mode
4411    case 'pair j1-j2'     
4412    if ~isempty(regexp(NomTypeIma,'a$'))
4413        NomTypeNc=[NomTypeIma 'b'];
4414    elseif ~isempty(regexp(NomTypeIma,'A$'))
4415        NomTypeNc=[NomTypeIma 'B'];
4416    else
4417        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4418        if ~isempty(r)
4419            NomTypeNc='_1_1-2';
4420        end
4421    end
4422    case 'series(Dj)' 
4423        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4424        if ~isempty(r)
4425            NomTypeNc='_1_1-2';
4426        end
4427   case 'series(Di)'
4428        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4429        if ~isempty(r)
4430            NomTypeNc='_1-2_1';
4431        else
4432            NomTypeNc='_1-2';
4433        end
4434end
4435
4436function NomType_Callback(hObject, eventdata, handles)
4437set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
4438RootPath=get(handles.RootPath,'String');
4439RootFile=get(handles.RootFile,'String');
4440ref_i=str2num(get(handles.ref_i,'String'));
4441ref_j=str2num(get(handles.ref_j,'String'));
4442NomType=get(handles.NomType,'String');
4443ImaExt=get(handles.ImaExt,'String');
4444fileinput=fullfile_uvmat(RootPath,'',RootFile,ImaExt,NomType,ref_i,[],ref_j);
4445errormsg=display_file_name(handles,fileinput);
4446if ~isempty(errormsg)
4447    msgbox_uvmat('ERROR',errormsg)
4448end
4449set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
4450
4451% --- Executes on selection change in ListProgram.
4452function ListProgram_Callback(hObject, eventdata, handles)
4453ListProgram=get(handles.ListProgram,'String');
4454Program=ListProgram{get(handles.ListProgram,'value')};
4455switch Program
4456    case 'CivX'
4457        set(handles.num_MaxDiff,'Visible','off')
4458        set(handles.num_MaxVel,'Visible','off')
4459        set(handles.title_MaxVel,'Visible','off')
4460        set(handles.num_Nx,'Visible','on')
4461        set(handles.num_Ny,'Visible','on')
4462        set(handles.title_Nx,'Visible','on')
4463        set(handles.title_Ny,'Visible','on')
4464        set(handles.title_MaxDiff,'Visible','off')
4465        set(handles.num_CorrSmooth,'Style','edit')
4466        set(handles.num_CorrSmooth,'String','1')
4467        set(handles.BATCH,'Enable','on')
4468        set(handles.CheckThreshold,'Visible','off')
4469        set(handles.CheckDeformation,'Value',1)
4470        set(handles.CheckDecimal,'Value',1)
4471    case 'Matlab'
4472        set(handles.num_MaxDiff,'Visible','on')
4473        set(handles.num_MaxVel,'Visible','on')
4474        set(handles.title_MaxVel,'Visible','on')
4475        set(handles.title_MaxDiff,'Visible','on')
4476        set(handles.num_Nx,'Visible','off')
4477        set(handles.num_Ny,'Visible','off')
4478        set(handles.title_Nx,'Visible','off')
4479        set(handles.title_Ny,'Visible','off')
4480        set(handles.num_CorrSmooth,'Style','popupmenu')
4481        set(handles.num_CorrSmooth,'Value',1)
4482        set(handles.num_CorrSmooth,'String',{'1';'2'})
4483        set(handles.CheckThreshold,'Visible','on')
4484        set(handles.CheckDeformation,'Value',0)% desactivate (work in progress)
4485        set(handles.CheckDecimal,'Value',0)% desactivate (work in progress)
4486end
4487
4488
4489% --- Executes on button press in TestCiv2.
4490function TestCiv2_Callback(hObject, eventdata, handles)
4491
4492
4493
4494function RootFile_Callback(hObject, eventdata, handles)
4495
4496
4497
4498function SubdirImages_Callback(hObject, eventdata, handles)
Note: See TracBrowser for help on using the repository browser.