source: trunk/src/civ.m @ 456

Last change on this file since 456 was 452, checked in by sommeria, 13 years ago

bugs repaired

File size: 192.8 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',['overwrite existing civ files in ' subdir_civ1_new]);
2103                    if strcmp(answer,'Yes')
2104                        detect=0;
2105                        filecell.nc.civ1(ifile,j)={filename};
2106                    else
2107                        r=regexp(subdir_civ1_new,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
2108                        if isempty(r)
2109                            r(1).root=[subdir_civ1_new '_'];
2110                            r(1).num1='0';
2111                        end
2112                        subdir_civ1_new=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
2113                        subdir_civ2=subdir_civ1_new;
2114                    end
2115                    break
2116                end
2117                filecell.nc.civ1(ifile,j)={filename};
2118            end
2119            if detect% if a netcdf file already exists
2120                break
2121            end
2122        end
2123 
2124        %create the new SubdirCiv1
2125        if ~exist(fullfile(RootPath,subdir_civ1_new),'dir')     
2126            [xx,msg1]=mkdir(fullfile(RootPath,subdir_civ1_new));
2127            if ~strcmp(msg1,'')
2128                errormsg=['cannot create ' subdir_civ1_new ': ' msg1];%error message for directory creation
2129                return
2130            elseif isunix         
2131                [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2132                if ~strcmp(msg2,'')
2133                    errormsg=['pb of permission for  ' fullfile(RootPath,subdir_civ1_new) ': ' msg2];%error message for directory creation
2134                    return
2135                end
2136            end
2137        end
2138        if strcmp(compare,'stereo PIV')&&(strcmp(mode,'pair j1-j2')||strcmp(mode,'series(Dj)')||strcmp(mode,'series(Di)'))%check second nc series
2139            for ifile=1:nbfield
2140                for j=1:nbslice
2141                     filename=fullfile_uvmat(RootPath,subdir_civ1_new,RootFile_A,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2142                   % filename=name_generator(filebase_A,i1_civ1(ifile),j1_civ1(j),'.nc',NomType_nc,1,i2_civ1(ifile),j2_civ1(j),subdir_civ1_new);%
2143                    detect=exist(filename,'file')==2;
2144                    if detect% if a netcdf file already exists
2145                       indstr=regexp(subdir_civ1_new,'\D');
2146                       if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
2147                           vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
2148                           subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
2149                       else
2150                           vers=vers+1;
2151                           subdir_civ1_new=[subdir_civ1_new '_' num2str(vers)];
2152                       end
2153                       subdir_civ2=subdir_civ1;
2154                       break
2155                    end
2156                    filecell.ncA.civ1(ifile,j)={filename};
2157                end
2158                if detect% if a netcdf file already exists
2159                    break
2160                end
2161            end
2162            %create the new SubdirCiv1
2163            if ~exist(fullfile(RootPath,subdir_civ1_new),'dir')       
2164                [xx,msg1]=mkdir(fullfile(RootPath,subdir_civ1_new));
2165                if ~strcmp(msg1,'')
2166                    errormsg=['cannot create ' subdir_civ1_new ': ' msg1];
2167                    return
2168                else
2169                    [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2170                    if ~strcmp(msg2,'')
2171                        errormsg=['pb of permission for ' subdir_civ1_new ': ' msg2];%error message for directory creation
2172                        return
2173                    end
2174                end
2175            end
2176        end
2177    end
2178    subdir_civ1=subdir_civ1_new;
2179    % get image names
2180    for ifile=1:nbfield
2181        for j=1:nbslice
2182             filename=fullfile_uvmat(RootPath,SubdirImages,RootFile_ima1,ext_ima,NomType_ima1,i1_civ1(ifile),[],j1_civ1(j));
2183            idetect(j)=exist(filename,'file')==2;
2184            filecell.ima1.civ1(ifile,j)={filename}; %first image
2185            filename=fullfile_uvmat(RootPath,SubdirImages,RootFile_ima2,ext_ima,NomType_ima2,i2_civ1(ifile),[],j2_civ1(j));
2186            idetect_1(j)=exist(filename,'file')==2;
2187            filecell.ima2.civ1(ifile,j)={filename};%second image
2188        end
2189        [idetectmin,indexj]=min(idetect);
2190        if idetectmin==0,
2191            errormsg=[filecell.ima1.civ1{ifile,indexj} ' not found'];
2192            return
2193        end
2194        [idetectmin,indexj]=min(idetect_1);
2195        if idetectmin==0,
2196            errormsg=[filecell.ima2.civ1{ifile,indexj} ' not found'];
2197            return
2198        end
2199    end
2200    if strcmp(compare,'stereo PIV') && (strcmp(mode,'pair j1-j2') || strcmp(mode,'series(Dj)') || strcmp(mode,'series(Di)'))
2201        for ifile=1:nbfield
2202            for j=1:nbslice
2203                filename=fullfile_uvmat(RootPath,'',RootFile_A,ext_ima,NomType_ima1,i1_civ1(ifile),[],j1_civ1(j));
2204                idetect(j)=exist(filename,'file')==2;
2205                filecell.imaA1.civ1(ifile,j)={filename} ;%first image
2206                filename=fullfile_uvmat(RootPath,'',RootFile_A,ext_ima,NomType_ima2,i2_civ1(ifile),[],j2_civ1(j));
2207                idetect_1(j)=exist(filename,'file')==2;
2208                filecell.imaA2.civ1(ifile,j)={filename};%second image
2209            end
2210            [idetectmin,indexj]=min(idetect);
2211            if idetectmin==0,
2212                errormsg=[filecell.imaA1.civ1{ifile,indexj} ' not found'];
2213                return
2214            end
2215            [idetectmin,indexj]=min(idetect_1);
2216            if idetectmin==0,
2217                errormsg=[filecell.imaA2.civ1{ifile,indexj} ' not found'];
2218                return
2219            end
2220        end
2221    end
2222   
2223    %%%%%%%%%%%%%  checkfix1 or checkpatch1 activated but no checkciv1   %%%%%%%%%%%%%
2224elseif (checkbox(2)==1 || checkbox(3)==1);
2225    for ifile=1:nbfield
2226        for j=1:nbslice
2227            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2228            detect=exist(filename,'file')==2;
2229            if detect==0
2230                errormsg=[filename ' not found'];
2231                return
2232            end
2233            filecell.nc.civ1(ifile,j)={filename};
2234        end
2235    end
2236    if strcmp(compare,'stereo PIV')
2237        for ifile=1:nbfield
2238            for j=1:nbslice
2239                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_A,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2240                filecell.ncA.civ1(ifile,j)={filename};
2241                if ~exist(filename,'file')
2242                    errormsg=['input file ' filename ' not found'];
2243                    return
2244                end
2245            end
2246        end
2247    end
2248end
2249
2250%%%%%%%%%%%%%  if checkciv2 performed with pairs different than checkciv1  %%%%%%%%%%%%%
2251testdiff=0;
2252if (checkbox(4)==1)&&...
2253        ((get(handles.ListPairCiv1,'Value')~=get(handles.ListPairCiv2,'Value'))||~strcmp(subdir_civ2,subdir_civ1))
2254    testdiff=1;
2255    detect=1;
2256    vers=0;
2257    subdir_civ2_new=subdir_civ2;
2258    while detect==1 %create a new subdir if the netcdf files already exist
2259        for ifile=1:nbfield
2260            for j=1:nbslice
2261                filename=fullfile_uvmat(RootPath,subdir_civ2_new,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2262                detect=exist(filename,'file')==2;
2263                if detect% if a netcdf file already exists
2264                    indstr=regexp(subdir_civ2,'\D');
2265                    if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2266                        vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2267                        subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2268                    else
2269                        vers=vers+1;
2270                        subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2271                    end
2272                    break
2273                end
2274                filecell.nc.civ2(ifile,j)={filename};
2275            end
2276            if detect% if a netcdf file already exists
2277                break
2278            end
2279        end
2280        %create the new subdir_civ2_new
2281        if ~exist(fullfile(RootPath,subdir_civ2_new),'dir')
2282            [xx,m2]=mkdir(fullfile(RootPath,subdir_civ2_new));
2283            [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2284            if ~isequal(m2,'')
2285                errormsg=['cannot create ' fullfile(RootPath,subdir_civ2_new) ': ' m2];
2286                return
2287            end
2288        end
2289        if strcmp(compare,'stereo PIV')%check second nc series
2290            for ifile=1:nbfield
2291                for j=1:nbslice
2292                    filename=fullfile_uvmat(RootPath,subdir_civ2_new,RootFile_A,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2293                    detect=exist(filename,'file')==2;
2294                    if detect% if a netcdf file already exists
2295                        indstr=regexp(subdir_civ2,'\D');
2296                        if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2297                           vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2298                           subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2299                        else
2300                           vers=vers+1;
2301                           subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2302                        end
2303                        break
2304                    end
2305                    filecell.ncA.civ2(ifile,j)={filename};
2306                end
2307                if detect% if a netcdf file already exists
2308                    break
2309                end
2310            end
2311            subdir_civ2=subdir_civ2_new;
2312            %create the new SubdirCiv1
2313            if ~exist(fullfile(RootPath,subdir_civ2_new),'dir')
2314                [xx,m2]=mkdir(subdir_civ2_new);
2315                 [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2316                if ~isequal(m2,'')
2317                    errormsg= ['cannot create ' fullfile(RootPath,subdir_civ2_new) ': ' m2];%error message for directory creation
2318                    return
2319                end
2320            end
2321        end
2322    end
2323    subdir_civ2=subdir_civ2_new;
2324end
2325
2326%%%%%%%%%%%%%  if checkciv2 results are obtained or used  %%%%%%%%%%%%%
2327if checkbox(4)==1 || checkbox(5)==1 || checkbox(6)==1 %civ2
2328    %check source netcdf file of checkciv1 estimates
2329    if checkbox(1)==0; %no civ1 performed
2330        for ifile=1:nbfield
2331            for j=1:nbslice
2332                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));%
2333                filecell.nc.civ1(ifile,j)={filename};% name of the civ1 file
2334                if ~exist(filename,'file')
2335                    errormsg=['input file ' filename ' not found'];
2336                    return
2337                end
2338                if ~testdiff % civ2 or patch2 are written in the same file as civ1
2339                    if checkbox(4)==0 ; %check the existence of civ2 if it is not calculated
2340                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2341                        if isfield(Data,'Txt')
2342                            errormsg=Data.Txt;
2343                            return
2344                        elseif ~isempty(Data.CivStage)% case of new civ files
2345                            if Data.CivStage<4 %test for civ files
2346                            errormsg=['no civ2 data in ' filename];
2347                            return
2348                            end
2349                        elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2350                            errormsg=['no civ2 data in ' filename];
2351                            return
2352                        end
2353                    elseif checkbox(3)==0; %check the existence of patch if it is not calculated
2354                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','patch');
2355                        if isfield(Data,'Txt')
2356                            errormsg=Data.Txt;
2357                            return
2358                        elseif ~isempty(Data.CivStage)
2359                            if Data.CivStage<3 %test for civ files
2360                                errormsg=['no patch data in ' filename];
2361                                return
2362                            end
2363                        elseif isempty(Data.patch)||isequal(Data.patch,0)
2364                            errormsg=['no patch data in ' filename];
2365                            return
2366                        end
2367                    end
2368                end
2369            end
2370        end
2371        if strcmp(compare,'stereo PIV')
2372            for ifile=1:nbfield
2373                for j=1:nbslice
2374                    filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_A,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2375                    filecell.ncA.civ2(ifile,j)={filename};
2376                    if ~exist(filename,'file')
2377                        errormsg=['input file ' filename ' not found'];
2378                        return
2379                    end
2380                end
2381            end
2382        end
2383    end
2384   
2385    detect=1;
2386    %     while detect==1%creates a new subdir if the netcdf files already contain checkciv2 data
2387    for ifile=1:nbfield
2388        for j=1:nbslice
2389            filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2390            detect=exist(filename,'file')==2;
2391            filecell.nc.civ2(ifile,j)={filename};
2392        end
2393    end
2394    %get first image names for checkciv2
2395    if checkbox(1)==1 && isequal(i1_civ1,i1_civ2) && isequal(j1_civ1,j1_civ2)
2396        filecell.ima1.civ2=filecell.ima1.civ1;
2397    elseif checkbox(4)==1
2398        for ifile=1:nbfield
2399            for j=1:nbslice
2400                filename=fullfile_uvmat(RootPath,[],RootFile_ima1,ext_ima,NomType_ima1,i1_civ2(ifile),[],j1_civ2(j));
2401                idetect_2(j)=exist(filename,'file')==2;
2402                filecell.ima1.civ2(ifile,j)={filename};%first image
2403            end
2404            [idetectmin,indexj]=min(idetect_2);
2405            if idetectmin==0,
2406               errormsg=['input image ' filecell.ima1.civ2{ifile,indexj} ' not found'];
2407                return
2408            end
2409        end
2410    end
2411   
2412    %get second image names for checkciv2
2413    if checkbox(1)==1 && isequal(i2_civ1,i2_civ2) && isequal(j2_civ1,j2_civ2)
2414        filecell.ima2.civ2=filecell.ima2.civ1;
2415    elseif checkbox(4)==1
2416        for ifile=1:nbfield
2417            for j=1:nbslice
2418                filename=fullfile_uvmat(RootPath,[],RootFile_ima2,ext_ima,NomType_ima2,i2_civ2(ifile),[],j2_civ2(j));
2419                idetect_3(j)=exist(filename,'file')==2;
2420                filecell.ima2.civ2(ifile,j)={filename};%first image
2421            end
2422            [idetectmin,indexj]=min(idetect_3);
2423            if idetectmin==0,
2424                errormsg=['input image ' filecell.ima2.civ2{ifile,indexj} ' not found'];
2425                return
2426            end
2427        end
2428    end
2429end
2430if (checkbox(5) || checkbox(6)) && ~checkbox(4)  % need to read an existing netcdf civ2 file
2431    if ~testdiff
2432        filecell.nc.civ2=filecell.nc.civ1;% file already checked
2433    else     % check the civ2 files
2434        for ifile=1:nbfield
2435            for j=1:nbslice
2436                 filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2437                filecell.nc.civ2(ifile,j)={filename};
2438                if ~exist(filename,'file')
2439                    errormsg=['input file ' filename ' not found'];
2440                    return
2441                else
2442                    Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2443                    if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2444                            errormsg=['no civ2 data in ' filename];
2445                            return
2446                    elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2447                        errormsg=['no civ2 data in ' filename];
2448                        return
2449                    end
2450                end
2451            end
2452        end
2453    end
2454end
2455
2456%%%%%%%%%%%%%  if stereo fields are calculated by PATCH %%%%%%%%%%%%%
2457if strcmp(compare,'stereo PIV')
2458    if  checkbox(3) && isequal(get(handles.test_stereo1,'Value'),1)
2459        for ifile=1:nbfield
2460            for j=1:nbslice
2461                 filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_AB,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2462                filecell.st(ifile,j)={filename};
2463            end
2464        end
2465    end
2466    if  checkbox(6) && isequal(get(handles.CheckStereo,'Value'),1)
2467        for ifile=1:nbfield
2468            for j=1:nbslice
2469                 filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_AB,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2470                filecell.st(ifile,j)={filename};
2471            end
2472        end
2473    end
2474end
2475set(handles.SubdirCiv1,'String',regexprep(subdir_civ1,['^' SubdirImages],''));%suppress the root  SuddirImages;);%update the edit box
2476set(handles.SubdirCiv2,'String',regexprep(subdir_civ2,['^' SubdirImages],''));%update the edit box
2477
2478% For CivX COPY IMAGES TO THE FORMAT .png IF NEEDED
2479if strcmp(CivMode,'CivX')
2480    if isequal(NomType_ima1,'*')%case of movie files
2481        NomType_imanew1='_i';
2482    else
2483        NomType_imanew1=NomType_ima1;
2484    end
2485    if isequal(NomType_ima2,'*')%case of movie files
2486        NomType_imanew2='_i';
2487    else
2488        NomType_imanew2=NomType_ima2;
2489    end
2490    if ~isequal(ext_ima,'.png')
2491        %%type of image file
2492        type_ima1='none';%default
2493        movieobject1=[];%default
2494        if strcmpi(ext_ima,'.avi')
2495            if ~isempty(which('mmreader'))% if the mmreader function is found (recent version of matlab)
2496                type_ima1='movie';
2497                movieobject1=mmreader([filecell.filebase ext_ima]);
2498            else
2499                type_ima1='avi';
2500            end
2501        elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2502            form=imformats(ext_ima(2:end));
2503            if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2504                if isequal(NomType_ima1,'*');
2505                    type_ima1='multimage';%image series in a single image file
2506                else
2507                    type_ima1='image';
2508                end
2509            end
2510        end
2511        type_ima2='none';%default
2512        movieobject2=[];
2513        if strcmpi(ext_ima,'.avi')
2514            if ~isempty(which('mmreader'))% if the mmreader function is found (recent version of matlab)
2515                type_ima2='movie';
2516                movieobject2=mmreader([filecell.filebase ext_ima]);
2517            else
2518                type_ima2='avi';
2519            end
2520        elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2521            form=imformats(ext_ima(2:end));
2522            if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2523                if isequal(NomType_ima1,'*');
2524                    type_ima2='multimage';%image series in a single image file
2525                else
2526                    type_ima2='image';
2527                end
2528            end
2529        end
2530        if checkbox(1) %if civ1 is performed
2531            h = waitbar(0,'copy images to the .png format for civ1');% display a wait bar
2532            for ifile=1:nbfield
2533                waitbar(ifile/nbfield);
2534                for j=1:nbslice
2535                    filename=fullfile_uvmat(RootPath,[],RootFile_ima1,'.png',NomType_imanew1,i1_civ1(ifile),[],j1_civ1(j));
2536                    if ~exist(filename,'file')
2537                        A=read_image(filecell.ima1.civ1{ifile,j},type_ima1,i1_civ1(ifile),movieobject1);
2538                        imwrite(A,filename,'BitDepth',16);
2539                    end
2540                    filecell.ima1.civ1(ifile,j)={filename};
2541                    filename=fullfile_uvmat(RootPath,[],RootFile_ima2,'.png',NomType_imanew2,i2_civ1(ifile),[],j2_civ1(j));
2542                    if ~exist(filename,'file')
2543                        A=read_image(filecell.ima2.civ1{ifile,j},type_ima2,i2_civ1(ifile),movieobject2);
2544                        imwrite(A,filename,'BitDepth',16);
2545                    end
2546                    filecell.ima2.civ1(ifile,j)={filename};
2547                end
2548            end
2549            close(h)
2550        end
2551        if checkbox(4) %if civ2 is performed
2552            h = waitbar(0,'copy images to the .png format for civ2');% display a wait bar
2553            for ifile=1:nbfield
2554                waitbar(ifile/nbfield);
2555                for j=1:nbslice
2556                    filename=fullfile_uvmat(RootPath,[],RootFile_ima1,'.png',NomType_imanew1,i1_civ2(ifile),[],j1_civ2(j));
2557                    if ~exist(filename,'file')
2558                        A=read_image(cell2mat(filecell.ima1.civ2(ifile,j)),type_ima2,i1_civ2(ifile));
2559                        imwrite(A,filename,'BitDepth',16);
2560                    end
2561                    filecell.ima1.civ2(ifile,j)={filename};
2562                    filename=fullfile_uvmat(RootPath,[],RootFile_ima2,'.png',NomType_imanew2,i2_civ2(ifile),[],j2_civ2(j));
2563                    if ~exist(filename,'file')
2564                        A=read_image(cell2mat(filecell.ima2.civ2(ifile,j)),type_ima2,i2_civ2(ifile));
2565                        imwrite(A,filename,'BitDepth',16);
2566                    end
2567                    filecell.ima2.civ2(ifile,j)={filename};
2568                end
2569            end
2570            close(h);
2571        end
2572    end
2573end
2574
2575%------------------------------------------------------------------------
2576% --- determine the list of index pairs of processing file
2577function [num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
2578    find_pair_indices(handles,ref_i,ref_j,mode)
2579%------------------------------------------------------------------------
2580
2581list_civ1=get(handles.ListPairCiv1,'String');
2582index_civ1=get(handles.ListPairCiv1,'Value');
2583str_civ1=list_civ1{index_civ1};%string defining the image pairs for civ1
2584if isempty(str_civ1)||isequal(str_civ1,'')
2585    msgbox_uvmat('ERROR','no image pair selected for civ1')
2586    return
2587end
2588list_civ2=get(handles.ListPairCiv2,'String');
2589index_civ2=get(handles.ListPairCiv2,'Value');
2590if index_civ2>length(list_civ2)
2591    list_civ2=list_civ1;
2592    index_civ2=index_civ1;
2593end
2594str_civ2=list_civ2{index_civ2};%string defining the image pairs for civ2
2595
2596if isequal (mode,'series(Di)')
2597    lastfield=str2double(get(handles.nb_field,'String'));
2598    num1_civ1=ref_i-floor(index_civ1/2)*ones(size(ref_i));% set of first image numbers
2599    num2_civ1=ref_i+ceil(index_civ1/2)*ones(size(ref_i));
2600    num_a_civ1=ref_j;
2601    num_b_civ1=ref_j;
2602    num1_civ2=ref_i-floor(index_civ2/2)*ones(size(ref_i));
2603    num2_civ2=ref_i+ceil(index_civ2/2)*ones(size(ref_i));
2604    num_a_civ2=ref_j;
2605    num_b_civ2=ref_j;   
2606   
2607    % adjust the first and last field number
2608    lastfield=str2double(get(handles.nb_field,'String'));
2609    if isnan(lastfield)
2610        indsel=find((num1_civ1 >= 1)&(num1_civ2 >= 1));
2611    else
2612        indsel=find((num2_civ1 <= lastfield)&(num2_civ2 <= lastfield)&(num1_civ1 >= 1)&(num1_civ2 >= 1));
2613    end
2614    if length(indsel)>=1
2615        firstind=indsel(1);
2616        lastind=indsel(end);
2617        set(handles.first_i,'String',num2str(ref_i(firstind)))%update the display of first and last fields
2618        set(handles.last_i,'String',num2str(ref_i(lastind)))
2619        ref_i=ref_i(indsel);
2620        num1_civ1=num1_civ1(indsel);
2621        num1_civ2=num1_civ2(indsel);
2622        num2_civ1=num2_civ1(indsel);
2623        num2_civ2=num2_civ2(indsel);
2624    end
2625elseif isequal (mode,'series(Dj)')
2626    lastfield_j=str2double(get(handles.nb_field2,'String'));
2627    num1_civ1=ref_i;% set of first image numbers
2628    num2_civ1=ref_i;
2629    num_a_civ1=ref_j-floor(index_civ1/2)*ones(size(ref_j));
2630    num_b_civ1=ref_j+ceil(index_civ1/2)*ones(size(ref_j));
2631    num1_civ2=ref_i;
2632    num2_civ2=ref_i;
2633    num_a_civ2=ref_j-floor(index_civ2/2)*ones(size(ref_j));
2634    num_b_civ2=ref_j+ceil(index_civ2/2)*ones(size(ref_j));
2635    % adjust the first and last field number
2636    if isnan(lastfield_j)
2637        indsel=find((num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2638    else
2639        indsel=find((num_b_civ1 <= lastfield_j)&(num_b_civ2 <= lastfield_j)&(num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2640    end
2641    if length(indsel)>=1
2642        firstind=indsel(1);
2643        lastind=indsel(end);
2644        set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
2645        set(handles.last_j,'String',num2str(ref_j(lastind)))
2646        ref_j=ref_j(indsel);
2647        num_a_civ1=num_a_civ1(indsel);
2648        num_b_civ1=num_b_civ1(indsel);
2649        num_a_civ2=num_a_civ2(indsel);
2650        num_b_civ2=num_b_civ2(indsel);
2651    end
2652elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
2653    displ_num=get(handles.ListPairCiv1,'UserData');
2654    num1_civ1=ref_i;
2655    num2_civ1=ref_i;
2656    num_a_civ1=displ_num(1,index_civ1);
2657    num_b_civ1=displ_num(2,index_civ1);
2658    num1_civ2=ref_i;
2659    num2_civ2=ref_i;
2660    num_a_civ2=displ_num(1,index_civ2);
2661    num_b_civ2=displ_num(2,index_civ2);
2662elseif isequal(mode,'displacement')
2663    num1_civ1=ref_i;
2664    num2_civ1=ref_i;
2665    num_a_civ1=ref_j;
2666    num_b_civ1=ref_j;
2667    num1_civ2=ref_i;
2668    num2_civ2=ref_i;
2669    num_a_civ2=ref_j;
2670    num_b_civ2=ref_j;
2671end
2672
2673%------------------------------------------------------------------------
2674% --- Executes on button press in ListCompareMode.
2675function ListCompareMode_Callback(hObject, eventdata, handles)
2676%------------------------------------------------------------------------
2677ListCompareMode=get(handles.ListCompareMode,'String');
2678option=ListCompareMode{get(handles.ListCompareMode,'Value')};
2679if ~strcmp(option,'PIV') % case 'displacement' or 'stereo PIV'
2680    filebase=get(handles.RootPath,'String');
2681    set(handles.sub_txt,'Visible','on')
2682    set(handles.RootFile_1,'Visible','On');%mkes the second file input window visible
2683    mode_store=get(handles.ListPairMode,'String');%get the present 'mode'
2684    set(handles.ListCompareMode,'UserData',mode_store);%store the mode display
2685    set(handles.ListPairMode,'Visible','off')
2686   
2687    %% open an image file with the browser
2688    ind_opening=1;%default
2689    browse.incr_pair=[0 0]; %default
2690    oldfile=get(handles.RootPath,'String');
2691    menu={'*.png;*.jpg;*.tif;*.avi;*.AVI;', ' (*.png,*.jpg ,.tif, *.avi,*.AVI)';
2692        '*.png','.png image files'; ...
2693        '*.jpg',' jpeg image files'; ...
2694        '*.tif','.tif image files'; ...
2695        '*.avi;*.AVI','.avi movie files'; ...
2696        '*.*',  'All Files (*.*)'};
2697    if strcmp(option,'displacement')
2698        comment='Pick the reference file for displacements';
2699    else
2700        comment='Pick a file of the second series';
2701    end
2702    [FileName, PathName] = uigetfile( menu, comment,oldfile);
2703    fileinput=[PathName FileName];%complete file name
2704    sizf=size(fileinput);
2705    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
2706    [path,name,ext]=fileparts(fileinput);
2707    [path1]=fileparts(filebase);
2708    if isunix
2709        [status,path]=system(['readlink ' path]);
2710        [status,path1]=system(['readlink ' path1]);% look for the true path in case of symbolic paths
2711    end
2712    if ~strcmp(path1,path)
2713        msgbox_uvmat('ERROR','The second image or series must be in the same directory as the first one')
2714        return
2715    end
2716    if strcmp(option,'displacement')
2717        [tild,RootFile_1]=fileparts(name);
2718    else
2719        [FilePath,FileName,Ext]=fileparts(fileinput);
2720% detect the file type, get the movie object if relevant, and look for the corresponding file series:
2721% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
2722[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]);
2723       
2724       % [tild,tild,RootFile_1,tild,tild,tild,tild,tild,nom_type_1]=fileparts_uvmat(fileinput);
2725        %[RootFile_1,i1_series,tild,j1_series,tild,nom_type_1,FileType,Object]=find_file_series(PathName,FileName);
2726        %check image nom type
2727        if ~strcmp(nom_type_1,get(handles.NomType,'String'))
2728        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')
2729        return
2730        end
2731    end   
2732    %check image  extension
2733    if ~strcmp(ext,get(handles.ImaExt,'String'))
2734        msgbox_uvmat('ERROR','The second image series must have the same extension name as the first one')
2735        return
2736    end
2737    set(handles.RootFile_1,'String',RootFile_1);
2738else
2739    set(handles.ListPairMode,'Visible','on')
2740    set(handles.RootFile_1,'Visible','Off');
2741    set(handles.sub_txt,'Visible','off')
2742    set(handles.RootFile_1,'String',[]);
2743    mode_store=get(handles.ListCompareMode,'UserData');
2744    set(handles.ListPairMode,'Value',1)
2745    set(handles.ListPairMode,'String',mode_store)
2746    set(handles.CheckStereo,'Value',0)
2747    set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2748end
2749% if strcmp(option,'stereo PIV') && get(handles.CheckPatch1,'Value')
2750%     set(handles.CheckStereo,'Visible','on')
2751% else
2752%     set(handles.CheckStereo,'Visible','off')
2753% end
2754% if strcmp(option,'stereo PIV') && get(handles.CheckPatch2,'Value')
2755%     set(handles.CheckStereo,'Visible','on')
2756% else
2757%     set(handles.CheckStereo,'Visible','off')
2758% end
2759ListPairMode_Callback(hObject, eventdata, handles)
2760
2761
2762%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2763% Callbacks in the uipanel Pair Indices
2764%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2765%------------------------------------------------------------------------
2766% --- Executes on button press in ListPairMode.
2767function ListPairMode_Callback(hObject, eventdata, handles)
2768%------------------------------------------------------------------------
2769compare_list=get(handles.ListCompareMode,'String');
2770val=get(handles.ListCompareMode,'Value');
2771compare=compare_list{val};
2772if strcmp(compare,'displacement')||strcmp(compare,'shift')
2773    mode='displacement';
2774else
2775    mode_list=get(handles.ListPairMode,'String');
2776    if ischar(mode_list)
2777        mode_list={mode_list};
2778    end
2779    mode_value=get(handles.ListPairMode,'Value');
2780    mode=mode_list{mode_value};
2781end
2782displ_num=[];%default
2783ref_i=str2double(get(handles.ref_i,'String'));
2784% last_i=str2num(get(handles.last_i,'String'));
2785time=get(handles.ImaDoc,'UserData'); %get the set of times
2786TimeUnit=get(handles.TimeUnit,'String');
2787checkframe=strcmp(TimeUnit,'frame');
2788siztime=size(time);
2789nbfield=siztime(1)-1;
2790nbfield2=siztime(2)-1;
2791indchosen=1;  %%first pair selected by default
2792%displ_num used to define the indices of the civ pairs
2793% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
2794% are relative to the reference indices ref_i and ref_j respectively.
2795if isequal(mode,'pair j1-j2')%| isequal(mode,'st_pair j1-j2')
2796    dt=1;
2797    displ='';
2798    index=0;
2799    numlist_a=[];
2800    numlist_B=[];
2801    %get all the time intervals in bursts
2802    displ_dt=1;%default
2803    nbfield2=min(nbfield2,10);%limitate the number of pairs to 10x10
2804    for numod_a=1:nbfield2-1 %nbfield2 always >=2 for 'pair j1-j2' mode
2805        for numod_b=(numod_a+1):nbfield2
2806            index=index+1;
2807            numlist_a(index)=numod_a;
2808            numlist_b(index)=numod_b;
2809            if size(time,2)>1 && ~checkframe
2810                dt(numod_a,numod_b)=time(ref_i+1,numod_b+1)-time(ref_i+1,numod_a+1);%first time interval dt
2811                displ_dt(index)=dt(numod_a,numod_b);
2812            else
2813                displ_dt(index)=1;
2814            end
2815        end
2816    end
2817    [dtsort,indsort]=sort(displ_dt);
2818    if ~isempty(numlist_a)
2819        displ_num(1,:)=numlist_a(indsort);
2820        displ_num(2,:)=numlist_b(indsort);
2821    end
2822    displ_num(3,:)=0;
2823    displ_num(4,:)=0;
2824    enable_j(handles, 'off')
2825elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)')
2826    index=1:200;
2827    displ_num(1,index)=-floor(index/2);
2828    displ_num(2,index)=ceil(index/2);
2829    displ_num(3:4,index)=zeros(2,200);
2830    enable_j(handles, 'on')
2831elseif isequal(mode,'series(Di)') %| isequal(mode,'st_series(Di)')
2832    index=1:200;
2833    displ_num(1:2,index)=zeros(2,200);
2834    displ_num(3,index)=-floor(index/2);
2835    displ_num(4,index)=ceil(index/2);
2836    enable_i(handles, 'on')
2837    if nbfield2 > 1
2838        enable_j(handles, 'on')
2839    else
2840        enable_j(handles, 'off')
2841    end
2842elseif isequal(mode,'displacement')%the pairs have the same indices
2843    displ_num(1,1)=0;
2844    displ_num(2,1)=0;
2845    displ_num(3,1)=0;
2846    displ_num(4,1)=0;
2847    if nbfield > 1 || nbfield==0
2848        enable_i(handles, 'on')
2849    else
2850        enable_j(handles, 'off')
2851    end
2852    if nbfield2 > 1
2853        enable_j(handles, 'on')
2854    else
2855        enable_j(handles, 'off')
2856    end
2857end
2858set(handles.ListPairCiv1,'UserData',displ_num);
2859errormsg=find_netcpair_civ( handles,1);
2860    if ~isempty(errormsg)
2861    msgbox_uvmat('ERROR',errormsg)
2862    end
2863% find_netcpair_civ2(handles)
2864
2865function enable_i(handles, state)
2866set(handles.itext,'Visible',state)
2867set(handles.first_i,'Visible',state)
2868set(handles.last_i,'Visible',state)
2869set(handles.incr_i,'Visible',state)
2870set(handles.nb_field,'Visible',state)
2871set(handles.ref_i,'Visible',state)
2872
2873function enable_j(handles, state)
2874set(handles.jtext,'Visible',state)
2875set(handles.first_j,'Visible',state)
2876set(handles.last_j,'Visible',state)
2877set(handles.incr_j,'Visible',state)
2878set(handles.nb_field2,'Visible',state)
2879set(handles.ref_j,'Visible',state)
2880
2881
2882%------------------------------------------------------------------------
2883% --- Executes on selection change in ListPairCiv1.
2884function ListPairCiv1_Callback(hObject, eventdata, handles)
2885%------------------------------------------------------------------------
2886%reproduce by default the chosen pair in the checkciv2 menu
2887list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
2888index_pair=get(handles.ListPairCiv1,'Value');
2889displ_num=get(handles.ListPairCiv1,'UserData');
2890% num_a=displ_num(1,index_pair);
2891% num_b=displ_num(2,index_pair);
2892list_pair2=get(handles.ListPairCiv2,'String');%get the menu of image pairs
2893if index_pair<=length(list_pair2)
2894    set(handles.ListPairCiv2,'Value',index_pair);
2895end
2896
2897%update first_i and last_i according to the chosen image pairs
2898mode_list=get(handles.ListPairMode,'String');
2899mode_value=get(handles.ListPairMode,'Value');
2900mode=mode_list{mode_value};
2901if isequal(mode,'series(Di)')
2902    first_i=str2double(get(handles.first_i,'String'));
2903    last_i=str2double(get(handles.last_i,'String'));
2904    incr_i=str2double(get(handles.incr_i,'String'));
2905    num1=first_i:incr_i:last_i;
2906    lastfield=str2double(get(handles.nb_field,'String'));
2907    if ~isnan(lastfield)
2908        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2909            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2910        num1=num1(test_find);
2911    end
2912    set(handles.first_i,'String',num2str(num1(1)));
2913    set(handles.last_i,'String',num2str(num1(end)));
2914elseif isequal(mode,'series(Dj)')
2915    first_j=str2double(get(handles.first_j,'String'));
2916    last_j=str2double(get(handles.last_j,'String'));
2917    incr_j=str2double(get(handles.incr_j,'String'));
2918    num_j=first_j:incr_j:last_j;
2919    lastfield2=str2double(get(handles.nb_field2,'String'));
2920    if ~isnan(lastfield2)
2921        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2922            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2923        num1=num_j(test_find);
2924    end
2925    set(handles.first_j,'String',num2str(num1(1)));
2926    set(handles.last_j,'String',num2str(num1(end)));
2927end
2928
2929%------------------------------------------------------------------------
2930% --- Executes on selection change in ListPairCiv2.
2931function ListPairCiv2_Callback(hObject, eventdata, handles)
2932%------------------------------------------------------------------------
2933index_pair=get(handles.ListPairCiv2,'Value');%get the selected position index in the menu
2934
2935%update first_i and last_i according to the chosen image pairs
2936mode_list=get(handles.ListPairMode,'String');
2937mode_value=get(handles.ListPairMode,'Value');
2938mode=mode_list{mode_value};
2939if isequal(mode,'series(Di)')
2940    first_i=str2double(get(handles.first_i,'String'));
2941    last_i=str2double(get(handles.last_i,'String'));
2942    incr_i=str2double(get(handles.incr_i,'String'));
2943    num1=first_i:incr_i:last_i;
2944    lastfield=str2double(get(handles.nb_field,'String'));
2945    if ~isnan(lastfield)
2946        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2947            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2948        num1=num1(test_find);
2949    end
2950    set(handles.first_i,'String',num2str(num1(1)));
2951    set(handles.last_i,'String',num2str(num1(end)));
2952elseif isequal(mode,'series(Dj)')
2953    first_j=str2double(get(handles.first_j,'String'));
2954    last_j=str2double(get(handles.last_j,'String'));
2955    incr_j=str2double(get(handles.incr_j,'String'));
2956    num_j=first_j:incr_j:last_j;
2957    lastfield2=str2double(get(handles.nb_field2,'String'));
2958    if ~isnan(lastfield2)
2959        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2960            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2961        num1=num_j(test_find);
2962    end
2963    set(handles.first_j,'String',num2str(num1(1)));
2964    set(handles.last_j,'String',num2str(num1(end)));
2965end
2966
2967%------------------------------------------------------------------------
2968function ref_i_Callback(hObject, eventdata, handles)
2969%------------------------------------------------------------------------
2970mode_list=get(handles.ListPairMode,'String');
2971mode_value=get(handles.ListPairMode,'Value');
2972mode=mode_list{mode_value};
2973errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2974if isequal(mode,'series(Di)') || ...% we do patch2 only
2975        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2976    errormsg=find_netcpair_civ( handles,2);
2977end
2978    if ~isempty(errormsg)
2979    msgbox_uvmat('ERROR',errormsg)
2980    end
2981
2982%------------------------------------------------------------------------
2983function ref_j_Callback(hObject, eventdata, handles)
2984%------------------------------------------------------------------------
2985mode_list=get(handles.ListPairMode,'String');
2986mode_value=get(handles.ListPairMode,'Value');
2987mode=mode_list{mode_value};
2988if isequal(get(handles.CheckCiv1,'Value'),0)|| isequal(mode,'series(Dj)')
2989    errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2990end
2991if isequal(mode,'series(Dj)') || ...
2992        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2993    errormsg=find_netcpair_civ(handles,2);
2994end
2995    if ~isempty(errormsg)
2996    msgbox_uvmat('ERROR',errormsg)
2997    end
2998
2999%------------------------------------------------------------------------
3000% determine the menu for checkciv1 pairs depending on existing netcdf file at the middle of
3001% the field series set by first_i, incr, last_i
3002% index=1: look for pairs for civ1
3003% index=2: look for pairs for civ2
3004function errormsg=find_netcpair_civ(handles,index)
3005%------------------------------------------------------------------------
3006set(gcf,'Pointer','watch')% set the mouse pointer to 'watch' (clock)
3007
3008%% initialisation
3009errormsg='';
3010browse=get(handles.RootPath,'UserData');
3011compare_list=get(handles.ListCompareMode,'String');
3012val=get(handles.ListCompareMode,'Value');
3013compare=compare_list{val};
3014if strcmp(compare,'displacement')||strcmp(compare,'shift')
3015    mode='displacement';
3016else
3017    mode_list=get(handles.ListPairMode,'String');
3018    mode_value=get(handles.ListPairMode,'Value');
3019    if isempty(mode_list)
3020        return
3021    end
3022    mode=mode_list{mode_value};
3023end
3024nom_type_ima=get(handles.NomType,'String');
3025
3026%% determine nom_type_nc, nomenclature type of the .nc files:
3027[nom_type_nc]=nomtype2pair(nom_type_ima,mode);
3028
3029%% reads .nc subdirectoy and image numbers from the interface
3030subdir_civ1=get(handles.SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
3031subdir_civ2=get(handles.SubdirCiv2,'String');%subdirectory subdir_civ2 for the netcdf data
3032ref_i=str2double(get(handles.ref_i,'String'));
3033if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
3034    ref_j=0;
3035else
3036    ref_j=str2double(get(handles.ref_j,'String'));
3037    if isnan(ref_j)
3038        ref_j=1;
3039    end
3040end
3041time=get(handles.ImaDoc,'UserData');%get the set of times
3042TimeUnit=get(handles.TimeUnit,'String');
3043checkframe=strcmp(TimeUnit,'frame');
3044displ_num=get(handles.ListPairCiv1,'UserData');
3045
3046%% eliminate the first pairs inconsistent with the position
3047if isempty(displ_num)
3048    nbpair=0;
3049else
3050    nbpair=length(displ_num(1,:));%nbre of displayed pairs
3051    if  isequal(mode,'series(Di)')  %| isequal(mode,'st_series(Di)')
3052        nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
3053    elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3054        nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
3055    end
3056end
3057nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
3058
3059%% case with no Civ1 operation, netcdf files need to exist for reading
3060displ_pair={''};
3061select=ones(size(1:nbpair));%flag for displayed pairs =1 for display
3062testpair=0;
3063RootPath=get(handles.RootPath,'String');
3064RootFile=get(handles.RootFile,'String');
3065if index==1 % case civ1
3066    if ~get(handles.CheckCiv1,'Value') %
3067        if ~exist(fullfile(RootPath,subdir_civ1),'dir')
3068            errormsg=['no civ1 file available: subdirectory ' subdir_civ1 ' does not exist'];
3069            set(handles.ListPairCiv1,'String',{});
3070            return
3071        end
3072        for ipair=1:nbpair
3073            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3074                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3075            select(ipair)=exist(filename,'file')==2;% put flag to 0 if the file does not exist
3076        end
3077        % case of no displayed pair
3078        if isequal(select,zeros(size(1:nbpair)))
3079            if isfield(browse,'incr_pair') && ~isequal(browse.incr_pair,[0 0])
3080                num_i1=ref_i-floor(browse.incr_pair(1)/2);
3081                num_i2=ref_i+ceil(browse.incr_pair(1)/2);
3082                num_j1=ref_j-floor(browse.incr_pair(2)/2);
3083                num_j2=ref_j+ceil(browse.incr_pair(2)/2);
3084                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3085                select(1)=exist(filename,'file')==2;
3086                testpair=1;
3087            else
3088                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3089                    errormsg=['no civ1 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ1];
3090                else
3091                    errormsg=['no civ1 file available for the selected reference indices (i,j)= ' num2str(ref_i) ', ' num2str(ref_j) ' and subdirectory ' subdir_civ1];
3092                end
3093                set(handles.ListPairCiv1,'String',{''});
3094                %COMPLETER CAS STEREO
3095                return
3096            end
3097        end
3098    end
3099else %case civ2 alone
3100    if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
3101        if ~exist(fullfile(RootPath,subdir_civ2),'dir')
3102            msgbox_uvmat('ERROR',['no civ2 file available: subdirectory ' subdir_civ2 ' does not exist'])
3103            set(handles.ListPairCiv2,'Value',1);
3104            set(handles.ListPairCiv2,'String',{''});
3105            return
3106        end
3107        for ipair=1:nbpair
3108            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3109                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3110            select(ipair)=exist(filename,'file')==2;
3111        end
3112        if  isequal(select,zeros(size(1:nbpair)))
3113            if isfield(browse,'incr_pair')
3114                num_i1=ref_i-floor(browse.incr_pair(1)/2);
3115                num_i2=ref_i+floor((browse.incr_pair(1)+1)/2);
3116                num_j1=ref_j-floor(browse.incr_pair(2)/2);
3117                num_j2=ref_j+floor((browse.incr_pair(2)+1)/2);
3118                filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3119                select(1)=exist(filename,'file')==2;
3120            else
3121                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3122                    errormsg=['no civ2 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ2];
3123                else
3124                    errormsg=['no civ2 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ2];
3125                end
3126                set(handles.ListPairCiv2,'Value',1);
3127                set(handles.ListPairCiv2,'String',{''});
3128                return
3129            end
3130        end
3131    end
3132end
3133
3134%% determine the menu display in .ListPairCiv1
3135% the menu depends on the mode defined in ListPairMode_callback through the array displ_num:
3136% displ_num(1,:)=indices j1
3137% displ_num(2,:)=indices j2
3138% displ_num(3,:)=indices i1
3139% displ_num(4,:)=indices i2
3140% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
3141% are relative to the reference indices ref_i and ref_j respectively.
3142if isequal(mode,'series(Di)')
3143    if testpair
3144        displ_pair{1}=['Di= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3145    else
3146        for ipair=1:nbpair
3147            if select(ipair)
3148                displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3149                %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
3150                 %   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
3151               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
3152                 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
3153                else
3154                    dt=1;
3155                end
3156                 displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3157            else
3158                displ_pair{ipair}='...'; %pair not displayed in the menu
3159            end
3160        end
3161    end
3162elseif isequal(mode,'series(Dj)')
3163    if testpair
3164        displ_pair{1}=['Dj= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3165    else
3166        for ipair=1:nbpair
3167            if select(ipair)
3168                displ_pair{ipair}=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3169                if ~checkframe && size(time,1)>=ref_i+1+displ_num(4,ipair) && size(time,2)>=ref_j+1+displ_num(2,ipair)
3170                    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
3171                    displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3172                end
3173            else
3174                displ_pair{ipair}='...'; %pair not displayed in the menu
3175            end
3176        end
3177    end
3178elseif isequal(mode,'pair j1-j2')%case of pairs
3179    for ipair=1:nbpair
3180        if select(ipair)
3181            if ~checkframe && size(time,2)>1
3182            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
3183            else % time set by default to i index
3184                dt=1;
3185            end
3186            displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair),nom_type_ima) '-' num2stra(displ_num(2,ipair),nom_type_ima) ...
3187                ' :dt= ' num2str(dt*1000)];
3188        else
3189            displ_pair{ipair}='...'; %pair not displayed in the menu
3190        end
3191    end
3192elseif isequal(mode,'displacement')
3193    displ_pair={'Di=Dj=0'};
3194end
3195if index==1
3196set(handles.ListPairCiv1,'String',displ_pair');
3197end
3198
3199%% determine the default selection in the pair menu
3200ichoice=find(select,1);% index of selected pair
3201if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3202initial=get(handles.ListPairCiv1,'Value');%initial choice of pair
3203if initial>nbpair || (numel(select)>=initial && ~isequal(select(initial),1))
3204    set(handles.ListPairCiv1,'Value',ichoice);% first valid pair proposed by default in the menu
3205end
3206initial=get(handles.ListPairCiv2,'Value');
3207if initial>length(displ_pair')%|~isequal(select(initial),1)
3208    if ichoice <= length(displ_pair')
3209        set(handles.ListPairCiv2,'Value',ichoice);% same pair proposed by default for civ2
3210    else
3211        set(handles.ListPairCiv2,'Value',1);% same pair proposed by default for civ2
3212    end
3213end
3214set(handles.ListPairCiv2,'String',displ_pair');
3215set(gcf,'Pointer','arrow')
3216
3217
3218   
3219% %------------------------------------------------------------------------   
3220% % call 'view_field.fig' to display the  field selected in the list of 'status'
3221% function open_view_field(hObject, eventdata)
3222% %------------------------------------------------------------------------
3223% list=get(hObject,'String');
3224% index=get(hObject,'Value');
3225% rootroot=get(hObject,'UserData');
3226% filename=list{index};
3227% ind_dot=strfind(filename,'...');
3228% filename=filename(1:ind_dot-1);
3229% filename=fullfile(rootroot,filename);
3230% delete(get(hObject,'parent'))%delete the display figure to stop the check process
3231% if exist(filename,'file')%visualise the vel field if it exists
3232%     uvmat(filename)
3233%     set(gcbo,'Value',1)
3234% end
3235
3236
3237%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3238% Callbacks in the uipanel Reference Indices
3239%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3240%------------------------------------------------------------------------
3241function first_i_Callback(hObject, eventdata, handles)
3242%------------------------------------------------------------------------
3243first_i=str2double(get(handles.first_i,'String'));
3244set(handles.ref_i,'String', num2str(first_i))% reference index for pair dt = first index
3245ref_i_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3246
3247%------------------------------------------------------------------------
3248function first_j_Callback(hObject, eventdata, handles)
3249%------------------------------------------------------------------------
3250first_j=str2num(get(handles.first_j,'String'));
3251set(handles.ref_j,'String', num2str(first_j))% reference index for pair dt = first index
3252ref_j_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3253
3254%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3255% Callbacks in the uipanel Civ1
3256%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3257%------------------------------------------------------------------------
3258% --- Executes on button press in SearchRange: determine the search range num_SearchBoxSize_1,num_SearchBoxSize_2
3259function SearchRange_Callback(hObject, eventdata, handles)
3260%------------------------------------------------------------------------
3261%determine pair numbers
3262if strcmp(get(handles.num_UMin,'Visible'),'off')
3263    set(handles.u_title,'Visible','on')
3264    set(handles.v_title,'Visible','on')
3265    set(handles.num_UMin,'Visible','on')
3266    set(handles.num_UMax,'Visible','on')
3267    set(handles.num_VMin,'Visible','on')
3268    set(handles.num_VMax,'Visible','on')
3269    set(handles.CoordUnit,'Visible','on')
3270    set(handles.TimeUnit,'Visible','on')
3271    set(handles.slash_title,'Visible','on')
3272    set(handles.min_title,'Visible','on')
3273    set(handles.max_title,'Visible','on')
3274    set(handles.unit_title,'Visible','on')
3275else
3276    get_search_range(hObject, eventdata, handles)
3277end
3278
3279%------------------------------------------------------------------------
3280% ---  determine the search range num_SearchBoxSize_1,num_SearchBoxSize_2 and shift
3281function get_search_range(hObject, eventdata, handles)
3282%------------------------------------------------------------------------
3283param_civ1=read_GUI(handles.Civ1);
3284umin=param_civ1.UMin;
3285umax=param_civ1.UMax;
3286vmin=param_civ1.VMin;
3287vmax=param_civ1.VMax;
3288%switch min_title and max_title in case of error
3289if umax<=umin
3290    umin_old=umin;
3291    umin=umax;
3292    umax=umin_old;
3293    set(handles.num_UMin,'String', num2str(umin))
3294    set(handles.num_UMax,'String', num2str(umax))
3295end
3296if vmax<=vmin
3297    vmin_old=vmin;
3298    vmin=vmax;
3299    vmax=vmin_old;
3300    set(handles.num_VMin,'String', num2str(vmin))
3301    set(handles.num_VMax,'String', num2str(vmax))
3302end   
3303if ~(isempty(umin)||isempty(umax)||isempty(vmin)||isempty(vmax))
3304    list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
3305    index=get(handles.ListPairCiv1,'Value');
3306    pair_string=list_pair{index};
3307    time=get(handles.ImaDoc,'UserData'); %get the set of times
3308    pxcm=get(handles.SearchRange,'UserData');
3309    mode_list=get(handles.ListPairMode,'String');
3310    mode_value=get(handles.ListPairMode,'Value');
3311    mode=mode_list{mode_value};     
3312    if isequal (mode, 'series(Di)' )
3313        ref_i=str2double(get(handles.ref_i,'String'));
3314        num1=ref_i-floor(index/2);%  first image numbers
3315        num2=ref_i+ceil(index/2);
3316        num_a=1;
3317        num_b=1;
3318    elseif isequal (mode, 'series(Dj)')
3319        num1=1;
3320        num2=1;
3321        ref_j=str2double(get(handles.ref_j,'String'));
3322        num_a=ref_j-floor(index/2);%  first image numbers
3323        num_b=ref_j+ceil(index/2);
3324    elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)     
3325        ref_i=str2double(get(handles.ref_i,'String'));
3326        num1=ref_i;
3327        num2=ref_i;
3328                r=regexp(pair_string,'(?<mode>(Di=)|(Dj=)) -*(?<num1>\d+)\|(?<num2>\d+)','names');
3329        if isempty(r)
3330            r=regexp(pair_string,'(?<num1>\d+)(?<mode>-)(?<num2>\d+)','names');
3331        end 
3332        num_a=str2num(r.num1);
3333        num_b=str2num(r.num2);
3334    end
3335    dt=time(num2+1,num_b+1)-time(num1+1,num_a+1);
3336    ibx=str2double(get(handles.num_CorrBoxSize_1,'String'));
3337    iby=str2double(get(handles.num_CorrBoxSize_2,'String'));
3338    umin=dt*pxcm*umin;
3339    umax=dt*pxcm*umax;
3340    vmin=dt*pxcm*vmin;
3341    vmax=dt*pxcm*vmax;
3342    shiftx=round((umin+umax)/2);
3343    shifty=round((vmin+vmax)/2);
3344    isx=(umax+2-shiftx)*2+param_civ1.Bx;
3345    isx=2*ceil(isx/2)+1;
3346    isy=(vmax+2-shifty)*2+param_civ1.Bx;
3347    isy=2*ceil(isy/2)+1;
3348    set(handles.num_SearchBoxShift_1,'String',num2str(shiftx));
3349    set(handles.num_SearchBoxShift_2,'String',num2str(shifty));
3350    set(handles.num_SearchBoxSize_1,'String',num2str(isx));
3351    set(handles.num_SearchBoxSize_2,'String',num2str(isy));
3352end
3353
3354%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3355% Callbacks in the uipanel Fix1
3356%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3357%------------------------------------------------------------------------
3358% --- Executes on button press in CheckMask.
3359function get_mask_fix1_Callback(hObject, eventdata, handles)
3360%------------------------------------------------------------------------
3361maskval=get(handles.CheckMask,'Value');
3362if isequal(maskval,0)
3363    set(handles.Mask,'String','')
3364else
3365    mask_displ='no mask'; %default
3366    filebase=get(handles.RootPath,'String');
3367    [nbslice, flag_mask]=get_mask(filebase,handles);
3368    if isequal(flag_mask,1)
3369        mask_displ=[num2str(nbslice) 'mask'];
3370    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3371        filebase_a=get(handles.RootFile_1,'String');
3372        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3373        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3374            mask_displ='no mask';
3375        end
3376    end
3377    if isequal(mask_displ,'no mask')
3378        [FileName, PathName, filterindex] = uigetfile( ...
3379            {'*.png', ' (*.png)';
3380            '*.png',  '.png files '; ...
3381            '*.*', 'All Files (*.*)'}, ...
3382            'Pick a mask file *.png',filebase);
3383        mask_displ=fullfile(PathName,FileName);
3384        if ~exist(mask_displ,'file')
3385            mask_displ='no mask';
3386        end
3387    end
3388    if isequal(mask_displ,'no mask')
3389        set(handles.CheckMask,'Value',0)
3390        set(handles.CheckMask,'Value',0)
3391        set(handles.CheckMask,'Value',0)
3392    else
3393        %set(handles.CheckMask,'Value',1)
3394        set(handles.CheckMask,'Value',1)
3395    end
3396    set(handles.Mask,'String',mask_displ)
3397    set(handles.Mask,'String',mask_displ)
3398    set(handles.Mask,'String',mask_displ)
3399end
3400
3401%------------------------------------------------------------------------
3402% --- Executes on button press in CheckMask: select box for mask option
3403function get_mask_civ2_Callback(hObject, eventdata, handles)
3404%------------------------------------------------------------------------
3405maskval=get(handles.CheckMask,'Value');
3406if isequal(maskval,0)
3407    set(handles.Mask,'String','')
3408else
3409    mask_displ='no mask'; %default
3410    filebase=get(handles.RootPath,'String');
3411    [nbslice, flag_mask]=get_mask(filebase,handles);
3412    if isequal(flag_mask,1)
3413        mask_displ=[num2str(nbslice) 'mask'];
3414    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3415        filebase_a=get(handles.RootFile_1,'String');
3416        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3417        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3418            mask_displ='no mask';
3419        end
3420    end
3421    if isequal(mask_displ,'no mask')
3422        [FileName, PathName, filterindex] = uigetfile( ...
3423            {'*.png', ' (*.png)';
3424            '*.png',  '.png files '; ...
3425            '*.*', 'All Files (*.*)'}, ...
3426            'Pick a mask file *.png',filebase);
3427        mask_displ=fullfile(PathName,FileName);
3428        if ~exist(mask_displ,'file')
3429            mask_displ='no mask';
3430        end
3431    end
3432    if isequal(mask_displ,'no mask')
3433        set(handles.CheckMask,'Value',0)
3434        set(handles.CheckMask,'Value',0)
3435    else
3436        set(handles.CheckMask,'Value',1)
3437    end
3438    set(handles.Mask,'String',mask_displ)
3439    set(handles.Mask,'String',mask_displ)
3440end
3441
3442%------------------------------------------------------------------------
3443% --- Executes on button press in CheckMask.
3444function get_mask_fix2_Callback(hObject, eventdata, handles)
3445%------------------------------------------------------------------------
3446maskval=get(handles.CheckMask,'Value');
3447if isequal(maskval,0)
3448    set(handles.Mask,'String','')
3449else
3450    mask_displ='no mask'; %default
3451    filebase=get(handles.RootPath,'String');
3452    [nbslice, flag_mask]=get_mask(filebase,handles);
3453    if isequal(flag_mask,1)
3454        mask_displ=[num2str(nbslice) 'mask'];
3455    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3456        filebase_a=get(handles.RootFile_1,'String');
3457        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3458        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3459            mask_displ='no mask';
3460        end
3461    end
3462    if isequal(mask_displ,'no mask')
3463        [FileName, PathName, filterindex] = uigetfile( ...
3464            {'*.png', ' (*.png)';
3465            '*.png',  '.png files '; ...
3466            '*.*', 'All Files (*.*)'}, ...
3467            'Pick a mask file *.png',filebase);
3468        mask_displ=fullfile(PathName,FileName);
3469        if ~exist(mask_displ,'file')
3470            mask_displ='no mask';
3471        end
3472    end
3473    if isequal(mask_displ,'no mask')
3474        set(handles.CheckMask,'Value',0)
3475    end
3476    set(handles.Mask,'String',mask_displ)
3477end
3478
3479%------------------------------------------------------------------------
3480% --- function called to look for mask files
3481function [nbslice, flag_mask]=get_mask(filebase,handles)
3482%------------------------------------------------------------------------
3483%detect mask files, images with appropriate file base
3484%[filebase '_' xx 'mask'], xx=nbslice
3485%flag_mask=1 indicates detection
3486
3487flag_mask=0;%default
3488nbslice=1;
3489
3490% subdir=get(handles.SubdirCiv1,'String');
3491[Path,Name]=fileparts(filebase);
3492if ~isdir(Path)
3493    msgbox_uvmat('ERROR','no path for input files')
3494    return
3495end
3496% currentdir=pwd;
3497% cd(Path);%move in the dir of the root name filebase
3498maskfiles=dir(fullfile(Path,[Name '_*mask_*.png']));%look for mask files
3499% cd(currentdir);%come back to the current working directory
3500if ~isempty(maskfiles)
3501    %     msgbox_uvmat('ERROR','no mask available, to create it use Tools/Make mask in the upper menu bar of uvmat')
3502    % else
3503    flag_mask=1;
3504    maskname=maskfiles(1).name;% take the first mask file in the list
3505    [Path2,Name,ext]=fileparts(maskname);
3506    Namedouble=double(Name);
3507    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3508    ind_mask=findstr('mask',Name);
3509    i=ind_mask-1;
3510    while val(i)==0 && i>0
3511        i=i-1;
3512    end
3513    nbslice=str2double(Name(i+1:ind_mask-1));
3514    if ~isnan(nbslice) && Name(i)=='_'
3515        flag_mask=1;
3516    else
3517        msgbox_uvmat('ERROR',['bad mask file ' Name ext ' found in ' Path2])
3518        return
3519        nbslice=1;
3520    end
3521end
3522
3523%------------------------------------------------------------------------
3524% --- function called to look for grid files
3525function [nbslice, flag_mask]=get_grid(filebase,handles)
3526%------------------------------------------------------------------------
3527flag_mask=0;%default
3528nbslice=1;
3529[Path,Name]=fileparts(filebase);
3530currentdir=pwd;
3531cd(Path);%move in the dir of the root name filebase
3532maskfiles=dir([Name '_*grid_*.grid']);%look for mask files
3533cd(currentdir);%come back to the current working directory
3534if ~isempty(maskfiles)
3535    flag_mask=1;
3536    maskname=maskfiles(1).name;% take the first mask file in the list
3537    [Path2,Name,ext]=fileparts(maskname);
3538    Namedouble=double(Name);
3539    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3540    ind_mask=findstr('grid',Name);
3541    i=ind_mask-1;
3542    while val(i)==0 && i>0
3543        i=i-1;
3544    end
3545    nbslice=str2double(Name(i+1:ind_mask-1));
3546    if ~isnan(nbslice) && Name(i)=='_'
3547        flag_mask=1;
3548    else
3549        msgbox_uvmat('ERROR',['bad grid file ' Name ext ' found in ' Path2])
3550        return
3551        nbslice=1;
3552    end
3553end
3554
3555%------------------------------------------------------------------------
3556% --- transform numbers to letters
3557function str=num2stra(num,nom_type)
3558%------------------------------------------------------------------------
3559if isempty(nom_type)
3560    str='';
3561elseif strcmp(nom_type(end),'a')
3562    str=char(96+num);
3563elseif strcmp(nom_type(end),'A')
3564    str=char(96+num);
3565elseif isempty(nom_type(2:end))%a single index
3566    str='';
3567else
3568    str=num2str(num);
3569end
3570
3571% %------------------------------------------------------------------------
3572% % --- Executes on button press in ListSubdirCiv1.
3573% function ListSubdirCiv1_Callback(hObject, eventdata, handles)
3574% %------------------------------------------------------------------------
3575% list_subdir_civ1=get(handles.ListSubdirCiv1,'String');
3576% val=get(handles.ListSubdirCiv1,'Value');
3577% SubDir=list_subdir_civ1{val};
3578% if strcmp(SubDir,'new...')
3579%     if get(handles.CheckCiv1,'Value')
3580%         SubDir='CIV'; %default subdirectory
3581%     else
3582%         msgbox_uvmat('ERROR','select CheckCiv1 to perform a new Civ operation')
3583%         return
3584%     end   
3585% end
3586% set(handles.SubdirCiv1,'String',SubDir);
3587% errormsg=find_netcpair_civ(handles,1);
3588% if ~isempty(errormsg)
3589%     msgbox_uvmat('ERROR',errormsg)
3590% end
3591%     
3592%------------------------------------------------------------------------
3593% % --- Executes on button press in ListSubdirCiv2.
3594% function ListSubdirCiv2_Callback(hObject, eventdata, handles)
3595% %------------------------------------------------------------------------
3596% list_subdir_civ2=get(handles.ListSubdirCiv2,'String');
3597% val=get(handles.ListSubdirCiv2,'Value');
3598% SubDir=list_subdir_civ2{val};
3599% if strcmp(SubDir,'new...')
3600%     if get(handles.CheckCiv2,'Value')
3601%         SubDir='CIV'; %default subdirectory
3602%     else
3603%         msgbox_uvmat('ERROR','select CheckCiv2 to perform a new Civ operation')
3604%         return
3605%     end
3606% end
3607% set(handles.SubdirCiv2,'String',SubDir);
3608
3609%------------------------------------------------------------------------
3610% --- Executes on button press in CheckGrid.
3611function CheckGrid_Callback(hObject, eventdata, handles)
3612%------------------------------------------------------------------------
3613value=get(hObject,'Value');
3614hparent=get(hObject,'parent');
3615hchildren=get(hparent,'children');
3616handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3617handle_dx=findobj(hchildren,'tag','num_Dx');
3618handle_dy=findobj(hchildren,'tag','num_Dy');
3619handle_title_dx=findobj(hchildren,'tag','title_Dx');
3620handle_title_dy=findobj(hchildren,'tag','title_Dy');
3621testgrid=0;
3622filegrid='';
3623if value
3624    filebase=get(handles.RootPath,'String');
3625    [nbslice, flag_grid]=get_grid(filebase,handles);% look for a grid with appropriate name
3626    if isequal(flag_grid,1)
3627        filegrid=[num2str(nbslice) 'grid'];
3628        testgrid=1;
3629    else % browse for a grid
3630        filegrid=get(hObject,'UserData');%look for previous grid name stored as UserData
3631        if exist(filegrid,'file')
3632            filebase=filegrid;
3633        end
3634        [FileName, PathName, filterindex] = uigetfile( ...
3635            {'*.grid', ' (*.grid)';
3636            '*.grid',  '.grid files '; ...
3637            '*.*', 'All Files (*.*)'}, ...
3638            'Pick a file',filebase);
3639        filegrid=fullfile(PathName,FileName);
3640        set(hObject,'UserData',filegrid);%store for future use
3641        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filegrid,'file'))
3642            testgrid=1;
3643        end
3644    end
3645end
3646if testgrid
3647    set(handle_dx,'Visible','off');
3648    set(handle_dy,'Visible','off');
3649    set(handle_title_dy,'Visible','off');
3650    set(handle_title_dx,'Visible','off');
3651    set(handle_txtbox,'Visible','on')
3652    set(handle_txtbox,'String',filegrid)
3653else
3654    set(hObject,'Value',0);
3655    set(handle_dx,'Visible','on');
3656    set(handle_dy,'Visible','on');
3657    set(handle_title_dy,'Visible','on');
3658    set(handle_title_dx,'Visible','on');
3659    set(handle_txtbox,'Visible','off')
3660end
3661
3662%% if hObject is on the checkciv1 frame, duplicate action for checkciv2 frame
3663PanelName=get(hparent,'tag');
3664if strcmp(PanelName,'Civ1')
3665    hchildren=get(handles.Civ2,'children');
3666    handle_checkbox=findobj(hchildren,'tag','CheckGrid');
3667    handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3668    handle_dx=findobj(hchildren,'tag','num_Dx');
3669    handle_dy=findobj(hchildren,'tag','num_Dy');
3670    handle_title_dx=findobj(hchildren,'tag','title_Dx');
3671    handle_title_dy=findobj(hchildren,'tag','title_Dy');
3672    set(handle_checkbox,'UserData',filegrid);%store for future use
3673    if testgrid
3674        set(handle_checkbox,'Value',1);
3675        set(handle_dx,'Visible','off');
3676        set(handle_dy,'Visible','off');
3677        set(handle_title_dx,'Visible','off');
3678        set(handle_title_dy,'Visible','off');
3679        set(handle_txtbox,'Visible','on')
3680        set(handle_txtbox,'String',filegrid)
3681%     else
3682%         set(handle_checkbox,'Value',0);
3683%         set(handles.CheckGrid,'Value',0);
3684%         set(handle_dx,'Visible','on');
3685%         set(handle_dy,'Visible','on');
3686%          set(handle_title_dx,'Visible','on');
3687%         set(handle_title_dy,'Visible','on');
3688%         set(handle_txtbox,'Visible','off')
3689    end
3690end
3691
3692%------------------------------------------------------------------------
3693% --- Executes on button press in CheckMask: common to all panels (civ1, Civ2..)
3694function CheckMask_Callback(hObject, eventdata, handles)
3695%------------------------------------------------------------------------
3696value=get(hObject,'Value');
3697hparent=get(hObject,'parent');
3698parent_tag=get(hparent,'Tag');
3699hchildren=get(hparent,'children');
3700handle_txtbox=findobj(hchildren,'tag','Mask');% look for the mask name box in the same panel
3701testmask=0;
3702if value
3703    filebase=get(handles.RootPath,'String');
3704    [nbslice, flag_mask]=get_mask(filebase,handles);% look for a mask with appropriate name
3705    if isequal(flag_mask,1)
3706        filemask=[num2str(nbslice) 'mask'];
3707        testmask=1;
3708    else % browse for a mask
3709        filemask=get(hObject,'UserData');%look for previous mask name stored as UserData
3710        if exist(filemask,'file')
3711            filebase=filemask;
3712        end
3713        [FileName, PathName] = uigetfile( ...
3714            {'*.png', ' (*.png)';
3715            '*.png',  '.png files '; ...
3716            '*.*', 'All Files (*.*)'}, ...
3717            'Pick a mask file *.png',filebase);
3718        filemask=fullfile(PathName,FileName);
3719        set(hObject,'UserData',filemask);%store for future use
3720        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filemask,'file'))
3721            testmask=1;
3722        end
3723    end
3724end
3725if testmask
3726    if strcmp(parent_tag,'Civ1')
3727        set(handles.Mask,'Visible','on')
3728        set(handles.Mask,'String',filemask)
3729    set(handles.CheckMask,'Value',1)
3730    end
3731%     switch parent_tag
3732% %         case 'Fix1'
3733% %             stage=2;
3734%         case 'Civ2'
3735%              stage=3;
3736% %         case 'Fix2'
3737% %             stage=4;
3738%     end
3739%     set(handles.Mask(stage:end),'Visible','on')
3740%     set(handles.Mask(stage:end),'String',filemask)
3741%     set(handles.CheckMask(stage:end),'Value',1)
3742else
3743    set(hObject,'Value',0);
3744    set(handle_txtbox,'Visible','off')
3745end
3746
3747
3748% --- Executes on button press in get_gridpatch1.
3749function get_gridpatch1_Callback(hObject, eventdata, handles)
3750filebase=get(handles.RootPath,'String');
3751[FileName, PathName, filterindex] = uigetfile( ...
3752    {'*.grid', ' (*.grid)';
3753    '*.grid',  '.grid files '; ...
3754    '*.*', 'All Files (*.*)'}, ...
3755    'Pick a file',filebase);
3756filegrid=fullfile(PathName,FileName);
3757set(handles.grid_patch1,'string',filegrid);
3758
3759
3760%------------------------------------------------------------------------
3761% --- Executes on button press in get_gridpatch2.
3762function get_gridpatch2_Callback(hObject, eventdata, handles)
3763%------------------------------------------------------------------------
3764
3765
3766%------------------------------------------------------------------------
3767% --- STEREO Interp
3768function cmd=RUN_STINTERP(stinterpBin,filename_A_nc,filename_B_nc,filename_nc,nx_patch,ny_patch,rho_patch,subdomain_patch,thresh_value,xmlA,xmlB)
3769%------------------------------------------------------------------------
3770namelog=[filename_nc(1:end-3) '_stinterp.log'];
3771cmd=[stinterpBin ' -f1 ' filename_A_nc  ' -f2 ' filename_B_nc ' -f  ' filename_nc ...
3772    ' -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
3773
3774%------------------------------------------------------------------------
3775%--read images and convert them to the uint16 format used for PIV
3776function A=read_image(filename,type_ima,num,movieobject)
3777%------------------------------------------------------------------------
3778%num is the view number needed for an avi movie
3779switch type_ima
3780    case 'movie'
3781        A=read(movieobject,num);
3782    case 'avi'
3783        mov=aviread(filename,num);
3784        A=frame2im(mov(1));
3785    case 'multimage'
3786        A=imread(filename,num);
3787    case 'image'
3788        A=imread(filename);
3789end
3790siz=size(A);
3791if length(siz)==3;%color images
3792    A=sum(double(A),3);
3793    A=uint16(A);
3794end
3795
3796
3797%------------------------------------------------------------------------
3798% --- Executes on button press in get_ref_fix1.
3799function get_ref_fix1_Callback(hObject, eventdata, handles)
3800%------------------------------------------------------------------------
3801filebase=get(handles.RootPath,'String');
3802[FileName, PathName, filterindex] = uigetfile( ...
3803    {'*.nc', ' (*.nc)';
3804    '*.nc',  'netcdf files '; ...
3805    '*.*', 'All Files (*.*)'}, ...
3806    'Pick a file',filebase);
3807
3808fileinput=[PathName FileName];
3809sizf=size(fileinput);
3810if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3811%[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3812[Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3813ref.filebase=fullfile(Path,File);
3814% ref.num_a=stra2num(str_a);
3815% ref.num_b=stra2num(str_b);
3816% ref.num1=str2double(field_count);
3817% ref.num2=str2double(str2);
3818browse=[];%initialisation
3819if ~isequal(ref.ext,'.nc')
3820    msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3821    return
3822end
3823set(handles.ref_fix1,'String',[fullfile(ref.subdir,File) '....nc']);
3824set(handles.ref_fix1,'UserData',ref)
3825menu_field{1}='civ1';
3826Data=nc2struct(fileinput,[]);
3827if isfield(Data,'patch') && isequal(Data.patch,1)
3828    menu_field{2}='filter1';
3829end
3830if isfield(Data,'civ2') && isequal(Data.civ2,1)
3831    menu_field{3}='civ2';
3832end
3833if isfield(Data,'patch2') && isequal(Data.patch2,1)
3834    menu_field{4}='filter2';
3835end
3836set(handles.field_ref1,'String',menu_field);
3837set(handles.field_ref1,'Value',length(menu_field));
3838set(handles.num_MinVel,'Value',2);
3839set(handles.num_MinVel,'String','1');%default threshold
3840set(handles.ref_fix1,'Enable','on')
3841
3842%------------------------------------------------------------------------
3843% --- Executes on button press in get_ref_fix2.
3844function get_ref_fix2_Callback(hObject, eventdata, handles)
3845%------------------------------------------------------------------------
3846if isequal(get(handles.get_ref_fix2,'Value'),1)
3847    filebase=get(handles.RootPath,'String');
3848    [FileName, PathName, filterindex] = uigetfile( ...
3849        {'*.nc', ' (*.nc)';
3850        '*.nc',  'netcdf files '; ...
3851        '*.*', 'All Files (*.*)'}, ...
3852        'Pick a file',filebase);
3853    fileinput=[PathName FileName];
3854    sizf=size(fileinput);
3855    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3856    %[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3857    [Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3858    ref.filebase=fullfile(Path,File);
3859%     ref.num_a=stra2num(str_a);
3860%     ref.num_b=stra2num(str_b);
3861%     ref.num1=str2num(field_count);
3862%     ref.num2=str2num(str2);
3863    browse=[];%initialisation
3864    if ~isequal(ref.ext,'.nc')
3865        msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3866        return
3867    end
3868    set(handles.ref_fix2,'String',[fullfile(ref.subdir,File) '....nc']);
3869    set(handles.ref_fix2,'UserData',ref)
3870    menu_field{1}='civ1';
3871    Data=nc2struct(fileinput,[]);
3872    if isfield(Data,'patch') && isequal(Data.patch,1)
3873        menu_field{2}='filter1';
3874    end
3875    if isfield(Data,'civ2') && isequal(Data.civ2,1)
3876        menu_field{3}='civ2';
3877    end
3878    if isfield(Data,'patch2') && isequal(Data.patch2,1)
3879        menu_field{4}='filter2';
3880    end
3881    set(handles.field_ref2,'String',menu_field);
3882    set(handles.field_ref2,'Value',length(menu_field));
3883    set(handles.num_MinVel,'Value',2);
3884    set(handles.num_MinVel,'String','1');%default threshold
3885    set(handles.ref_fix2,'Enable','on')
3886    set(handles.ref_fix2,'Visible','on')
3887    set(handles.field_ref2,'Visible','on')
3888else
3889    set(handles.ref_fix2,'Visible','off')
3890    set(handles.field_ref2,'Visible','off')
3891end
3892
3893%------------------------------------------------------------------------
3894function ref_fix1_Callback(hObject, eventdata, handles)
3895%------------------------------------------------------------------------
3896set(handles.num_MinVel,'Value',1);
3897set(handles.field_ref1,'Value',1)
3898set(handles.field_ref1,'String',{' '})
3899set(handles.ref_fix1,'UserData',[]);
3900set(handles.ref_fix1,'String','');
3901set(handles.thresh_vel1,'String','0');
3902
3903%------------------------------------------------------------------------
3904function ref_fix2_Callback(hObject, eventdata, handles)
3905%------------------------------------------------------------------------
3906set(handles.num_MinVel,'Value',1);
3907set(handles.field_ref2,'Value',1)
3908set(handles.field_ref2,'String',{' '})
3909set(handles.ref_fix2,'UserData',[]);
3910set(handles.ref_fix2,'String','');
3911set(handles.num_MinVel,'String','0');
3912
3913%------------------------------------------------------------------------
3914% --- TO ABANDON Executes on button press in test_stereo1.
3915function CheckStereo_Callback(hObject, eventdata, handles)
3916%------------------------------------------------------------------------
3917hparent=get(hObject,'parent');
3918parent_tag=get(hparent,'Tag');
3919hchildren=get(hparent,'children');
3920handle_txtbox=findobj(hchildren,'tag','txt_Mask');
3921if isequal(get(hObject,'Value'),0)
3922    set(handles.num_SubdomainSize,'Visible','on')
3923    set(handles.num_FieldSmooth,'Visible','on')
3924else
3925    set(handles.num_SubdomainSize,'Visible','off')
3926    set(handles.num_FieldSmooth,'Visible','off')
3927end
3928
3929% %------------------------------------------------------------------------
3930% % --- Executes on button press in CheckStereo.
3931% function StereoCheck_Callback(hObject, eventdata, handles)
3932% %------------------------------------------------------------------------
3933% if isequal(get(handles.CheckStereo,'Value'),0)
3934%     set(handles.num_SubdomainSize,'Visible','on')
3935%     set(handles.num_FieldSmooth,'Visible','on')
3936% else
3937%     set(handles.num_SubdomainSize,'Visible','off')
3938%     set(handles.num_FieldSmooth,'Visible','off')
3939% end
3940
3941%------------------------------------------------------------------------
3942% --- Executes on button press in TestCiv1: prepare the image correlation function
3943% activated by mouse motion
3944function TestCiv1_Callback(hObject, eventdata, handles)
3945%------------------------------------------------------------------------
3946drawnow
3947if get(handles.TestCiv1,'Value')
3948    set(handles.TestCiv1,'BackgroundColor',[0.7 0.7 0.7])% paint TestCiv1 button to grey to confirm civ launch
3949    ref_i=str2double(get(handles.ref_i,'String'));% read reference i index
3950    if strcmp(get(handles.ref_j,'Visible'),'on')
3951        ref_j=str2double(get(handles.ref_j,'String'));% read reference j index if relevant
3952    else
3953        ref_j=1;%default j index
3954    end
3955    [filecell,i1,i2]=set_civ_filenames(handles,ref_i,ref_j,[1 0 0 0 0 0]);% get the corresponding file name and indices
3956    Data.ListVarName={'ny','nx','A'};
3957    Data.VarDimName= {'ny','nx',{'ny','nx'}};
3958
3959    Data.A=imread(filecell.ima1.civ1{1}); % read the first image
3960    if ndims(Data.A)==3 %case of color image
3961        Data.VarDimName= {'ny','nx',{'ny','nx','rgb'}};
3962    end
3963    Data.ny=[size(Data.A,1) 1];
3964    Data.nx=[1 size(Data.A,2)];
3965    Data.CoordUnit='pixel';% used to set equal scaling for x and y in image dispaly
3966    par_civ1=read_GUI(handles.Civ1);
3967    par_civ1.FileTypeA=get_file_type(filecell.ima1.civ1{1});
3968    par_civ1.ImageWidth=size(Data.A,2);
3969    par_civ1.ImageHeight=size(Data.A,1);
3970    par_civ1.Mask='all';% will provide only the grid set for PIV, no image correlation
3971    par_civ1.FrameIndexA=num2str(i1);
3972    par_civ1.FrameIndexB=num2str(i2);
3973    Param.Civ1=par_civ1;
3974    Grid=civ_matlab(Param);% get the grid of x, y positions set for PIV
3975    hview_field=view_field(Data); %view the image in the GUI view_field
3976    set(0,'CurrentFigure',hview_field)
3977    hhview_field=guihandles(hview_field);
3978    set(hview_field,'CurrentAxes',hhview_field.axes3)
3979    ViewData=get(hview_field,'UserData');
3980    ViewData.CivHandle=handles.civ;% indicate the handle of the civ GUI in view_field
3981    ViewData.axes3.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
3982    ViewData.axes3.X=Grid.Civ1_X; %keep the set of points in memeory
3983    ViewData.axes3.Y=Grid.Civ1_Y;
3984    set(hview_field,'UserData',ViewData)
3985    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3986    if isempty(corrfig)
3987        corrfig=figure;
3988        set(corrfig,'tag','corrfig')
3989        set(corrfig,'name','image correlation')
3990        set(corrfig,'DeleteFcn',{@closeview_field})%
3991    end
3992    set(handles.TestCiv1,'BackgroundColor',[1 0 0])
3993else
3994    set(handles.TestCiv1,'BackgroundColor',[1 0 0])% paint button to red
3995    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3996    if ~isempty(corrfig)
3997        delete(corrfig)
3998    end
3999    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
4000    if ~isempty(hview_field)
4001        delete(hview_field)
4002    end
4003end
4004
4005%------------------------------------------------------------------------
4006%----function introduced for the correlation window figure, activated by deleting this window
4007function closeview_field(gcbo,eventdata)
4008%------------------------------------------------------------------------
4009hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
4010if ~isempty(hview_field)
4011    delete(hview_field)
4012end
4013
4014%------------------------------------------------------------------------
4015% --- Executes on button press in CheckThreshold.
4016function CheckThreshold_Callback(hObject, eventdata, handles)
4017%------------------------------------------------------------------------
4018huipanel=get(hObject,'parent');
4019obj(1)=findobj(huipanel,'Tag','num_MinIma');
4020obj(2)=findobj(huipanel,'Tag','num_MaxIma');
4021obj(3)=findobj(huipanel,'Tag','title_Threshold');
4022if get(hObject,'Value')
4023    set(obj,'Visible','on')
4024else
4025    set(obj,'Visible','off')
4026end
4027
4028%------------------------------------------------------------------------
4029function [cmd,errormsg]=cmd_civ1(filename,Param)
4030%------------------------------------------------------------------------
4031%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4032%changes : filename_cmx -> filename ( no extension )
4033cmd='';
4034filename=regexprep(filename,'.nc',''); %file name for the result
4035if isequal(Param.Civ1.Dt,0)
4036    Param.Civ1.Dt=1 ;%case of 'displacement' mode
4037end
4038Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'.png','');
4039Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'.png','');
4040[fid,errormsg]=fopen([filename '.civ1.cmx'],'w');
4041if isequal(fid,-1)
4042    errormsg=['cmd file ' filename ' cannot be created: ' errormsg];
4043    return
4044end
4045fprintf(fid,['##############   CMX file' '\n' ]);
4046fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4047fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4048fprintf(fid,  ['XX' '\n' ]);
4049if isfield(Param.Civ1,'Mask')
4050    fprintf(fid,  ['Mask ' 'y' '\n' ]);
4051    fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.Mask,'\\','\\\\') '\n' ]);
4052else
4053    fprintf(fid,  ['Mask ' 'n' '\n' ]);
4054    fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4055end
4056fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageWidth) ' ' num2str(Param.Civ1.ImageHeight) '\n' ]);   %VERIFIER CAS GENERAL ?
4057fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.CorrBoxSize(1)) ' ' num2str(Param.Civ1.CorrBoxSize(2)) '\n' ]);
4058fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.SearchBoxSize(1)) ' ' num2str(Param.Civ1.SearchBoxSize(2)) '\n' ]);
4059fprintf(fid,   ['RO ' num2str(Param.Civ1.CorrSmooth) '\n' ]);
4060if isfield(Param.Civ1,'Grid')
4061    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4062else
4063    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
4064end
4065fprintf(fid,   ['XX 1.0' '\n' ]);
4066fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.Time) '\n' ]);
4067fprintf(fid,  ['PixCmXY ' '1' ' ' '1' '\n' ]);
4068fprintf(fid,  ['XX 1' '\n' ]);
4069fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.SearchBoxShift(1)) ' '  num2str(Param.Civ1.SearchBoxShift(2)) '\n' ]);
4070if isfield(Param.Civ1,'Grid')
4071    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4072    fprintf(fid,   ['GridName ' regexprep(Param.Civ1.Grid,'\\','\\\\') '\n' ]);
4073else
4074    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4075    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4076end
4077fprintf(fid,   ['XX 85' '\n' ]);
4078fprintf(fid,   ['XX 1.0' '\n' ]);
4079fprintf(fid,   ['XX 1.0' '\n' ]);
4080fprintf(fid,   ['Hart 1' '\n' ]);
4081fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
4082fprintf(fid,   ['Deformation 0' '\n' ]);
4083fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4084fprintf(fid,   ['IntensityMin 0' '\n' ]);
4085if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
4086    fprintf(fid,  ['SeuilImage n' '\n' ]);
4087    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4088else% Image threshold  activated
4089    if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
4090        Param.Civ1.MaxIma=2^Param.Civ1.ImageBitDepth;%take the max image value as upper bound by default
4091    end
4092    fprintf(fid,  ['SeuilImage y' '\n' ]);
4093    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
4094end
4095fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
4096fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
4097fclose(fid);
4098
4099if(isunix) %unix (or Mac) system
4100    cmd=['cp -f ' filename '.civ1.cmx ' filename '.cmx \n '];% the cmx file gives the name to the nc file
4101    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
4102    cmd=[cmd 'rm ' filename '.cmx'];
4103else %Windows system
4104    filename=regexprep(filename,'\\','\\\\');
4105    cmd=['copy /Y "' filename '.civ1.cmx" "' filename '.cmx" \n '];
4106    cmd=[cmd '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\')...
4107        '" -f "' filename '.cmx" >"' filename '.civ1.log" \n ' ]; % redirect standard output to the log file
4108    cmd=[cmd 'del "' filename '.cmx"'];
4109end
4110
4111
4112function cmd=cmd_fix(filename,Param,fixname)
4113%%
4114switch fixname
4115    case 'Fix1'
4116        fi2_value=num2str(Param.(fixname).CheckF2);
4117    case 'Fix2'
4118        fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
4119end
4120filename=regexprep(filename,'.nc','');
4121MaskName_string='';%default
4122MaxVel_string='';%default
4123if ~isempty(Param.(fixname).MinVel)
4124    MaxVel_string=[' -threshV ' num2str(Param.(fixname).MinVel)];
4125end
4126if isunix
4127    cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
4128        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4129        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4130        ' >' filename '.' lower(fixname) '.log 2>&1'];
4131else
4132    cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
4133        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4134        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4135        ' > "' filename '.' lower(fixname) '.log"'];
4136    cmd=regexprep(cmd,'\\','\\\\');
4137end
4138
4139
4140function cmd=cmd_patch(filename,Param,patchname)
4141%% ------------------------------------------------------------------------
4142filename=regexprep(filename,'.nc','');
4143if isunix
4144    cmd=[Param.xml.PatchBin...
4145        ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
4146        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
4147        ' -nopt ' num2str(Param.(patchname).SubdomainSize) ...
4148        '  > ' filename '.' lower(patchname) '.log 2>&1']; % redirect standard output to the log file
4149else
4150    cmd=['"' Param.xml.PatchBin...
4151        '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
4152        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
4153        ' -nopt ' num2str(Param.(patchname).SubdomainSize)...
4154        '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
4155    cmd=regexprep(cmd,'\\','\\\\');
4156end
4157
4158%------------------------------------------------------------------------
4159% --- CheckCiv2  CheckCiv2  CheckCiv2 CheckCiv2
4160function [cmd,errormsg]=cmd_civ2(filename,Param)
4161%------------------------------------------------------------------------
4162%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4163% global civ2Bin sge%name of the executable for checkciv1 calculation
4164 cmd='';
4165filename=regexprep(filename,'.nc','');
4166if isequal(Param.Civ2.Dt,'0')
4167    Param.Civ2.Dt='1' ;%case of 'displacement' mode
4168end
4169Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'.png','');
4170Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'.png','');% bug : .png appears two times ?
4171[fid,errormsg]=fopen([filename '.civ2.cmx'],'w');
4172if isequal(fid,-1)
4173    return
4174end
4175fprintf(fid,['##############   CMX file' '\n' ]);
4176fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4177fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4178fprintf(fid,  ['XX' '\n' ]);
4179if isfield(Param.Civ2,'Mask')
4180    fprintf(fid,  ['Mask ' 'y' '\n' ]);
4181    fprintf(fid,  ['MaskName ' regexprep(Param.Civ2.Mask,'\\','\\\\') '\n' ]);
4182else
4183    fprintf(fid,  ['Mask ' 'n' '\n' ]);
4184    fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4185end
4186% fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
4187% fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
4188fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageWidth) ' ' num2str(Param.Civ2.ImageHeight) '\n' ]); 
4189% fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
4190fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n' ]);
4191fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n']);
4192fprintf(fid, ['RO ' num2str(Param.Civ2.CorrSmooth) '\n']);
4193if isfield(Param.Civ2,'Grid')
4194    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4195else
4196    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
4197end
4198% fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
4199fprintf(fid, ['XX 1.0' '\n' ]);
4200fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.Time) '\n' ]);
4201fprintf(fid, ['PixCmXY ' '1' ' ' '1' '\n' ]);
4202fprintf(fid, ['XX 1' '\n' ]);
4203fprintf(fid, 'ShiftXY 0 0\n');
4204if isfield(Param.Civ2,'Grid')
4205    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4206    fprintf(fid,   ['GridName ' regexprep(Param.Civ2.Grid,'\\','\\\\') '\n' ]);
4207else
4208    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4209    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4210end
4211% fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
4212% fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
4213fprintf(fid, ['XX 85' '\n' ]);
4214fprintf(fid, ['XX 1.0' '\n' ]);
4215fprintf(fid, ['XX 1.0' '\n' ]);
4216fprintf(fid, ['Hart 1' '\n' ]);
4217fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
4218fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
4219fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4220fprintf(fid,   ['IntensityMin 0' '\n' ]);
4221
4222if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
4223    fprintf(fid,  ['SeuilImage n' '\n' ]);
4224    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4225else% Image threshold  activated
4226    if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
4227        Param.Civ2.MaxIma=2^Param.Civ2.ImageBitDepth;%take the max image value as upper bound by default
4228    end
4229    fprintf(fid,  ['SeuilImage y' '\n' ]);
4230    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
4231end
4232fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
4233fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
4234fclose(fid);
4235
4236if(isunix)
4237    cmd=['cp -f ' filename '.civ2.cmx ' filename '.cmx\n'...
4238        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
4239        'rm ' filename '.cmx \n'];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
4240else
4241    filename=regexprep(filename,'\\','\\\\');
4242    cmd=['copy /Y "' filename '.civ2.cmx" "' filename '.cmx" \n'...
4243        '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f "' filename  '.cmx" >"' filename '.civ2.log" \n'...
4244        'del "' filename '.cmx" \n'];
4245end
4246
4247%------------------------------------------------------------------------
4248% --- CheckCiv1  Unified: TO ABADON
4249function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
4250%------------------------------------------------------------------------
4251%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4252%global CivBin%name of the executable for checkciv1 calculation
4253
4254civ1.image1=par.ImageA;
4255civ1.image2=par.ImageB;
4256civ1.imageSize_X=par.npx;
4257civ1.imageSize_Y=par.npy;
4258civ1.outputFileName=[filename '.nc'];
4259civ1.correlationBoxesSize_X=par.ibx;
4260civ1.correlationBoxesSize_Y=par.iby;
4261civ1.searchBoxesSize_X=par.isx;
4262civ1.searchBoxesSize_Y=par.isy;
4263civ1.globalShift_X=par.shiftx;
4264civ1.globalShift_Y=par.shifty;
4265civ1.ro=par.rho;
4266civ1.hart='y';
4267if isequal(par.gridflag,'y')
4268    civ1.grid=par.gridname;
4269else
4270    civ1.grid='n';
4271    civ1.gridSpacing_X=par.dx;
4272    civ1.gridSpacing_Y=par.dy;
4273end
4274if isequal(par.maskflag,'y')
4275    civ1.mask=par.maskname;
4276end
4277civ1.dt=par.Dt;
4278civ1.unit='pixel';
4279civ1.absolut_time_T0=par.Time;
4280civ1.pixcmx='1';
4281civ1.pixcmy='1';
4282civ1.convectFlow='n';
4283
4284xml_civ1_parameters=civ1;
4285
4286%------------------------------------------------------------------------
4287% --- CheckCiv2  Unified: TO ABADON
4288function civ2=CIV2_CMD_Unified(filename,namelog,par)
4289%------------------------------------------------------------------------
4290%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4291%global CivBin%name of the executable for checkciv1 calculation
4292
4293filename=regexprep(filename,'.nc','');
4294
4295civ2.image1=par.ImageA;
4296civ2.image2=par.ImageB;
4297civ2.imageSize_X=par.npx;
4298civ2.imageSize_Y=par.npy;
4299civ2.inputFileName=[par.filename_nc1 '.nc'];
4300civ2.outputFileName=[filename '.nc'];
4301civ2.correlationBoxesSize_X=par.ibx;
4302civ2.correlationBoxesSize_Y=par.iby;
4303civ2.ro=par.rho;
4304%checkciv2.decimalShift=par.CheckDecimal;
4305%checkciv2.CheckDeformation=par.CheckDeformation;
4306if isequal(par.decimal,'1')
4307    civ2.decimalShift='y';
4308else
4309    civ2.decimalShift='n';
4310end
4311if isequal(par.deformation,'1')
4312    civ2.deformation='y';
4313else
4314    civ2.deformation='n';
4315end
4316if isequal(par.gridflag,'y')
4317    civ2.grid=par.gridname;
4318else
4319    civ2.grid='n';
4320    civ2.gridSpacing_X=par.dx;
4321    civ2.gridSpacing_Y=par.dy;
4322end
4323civ2.gridSpacing_X='10';
4324civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
4325if isequal(par.maskflag,'y')
4326    civ2.mask=par.maskname;
4327else
4328    civ2.mask='n';
4329end
4330civ2.dt=par.Dt;
4331civ2.unit='pixel';
4332civ2.absolut_time_T0=par.Time;
4333civ2.pixcmx='1';
4334civ2.pixcmy='1';
4335civ2.convectFlow='n';
4336
4337
4338% --- Executes on button press in TestPatch1.
4339function TestPatch1_Callback(hObject, eventdata, handles)
4340set(handles.TestPatch1,'BackgroundColor',[1 1 0])
4341drawnow
4342if get(handles.TestPatch1,'Value')
4343    ref_i=str2double(get(handles.ref_i,'String'));
4344    if strcmp(get(handles.ref_j,'Visible'),'on')
4345        ref_j=str2double(get(handles.ref_j,'String'));
4346    else
4347        ref_j=1;%default
4348    end
4349    filecell=set_civ_filenames(handles,ref_i,ref_j,[0 0 1 0 0 0]);   
4350    Data.ListVarName={'ny','nx','A'};
4351    Data.VarDimName= {'ny','nx',{'ny','nx'}};   
4352    param_patch1=read_GUI(handles.Patch1);
4353    param_patch1.CivFile=filecell.nc.civ1{1};
4354    Param.Patch1=param_patch1;
4355    for irho=1:7
4356        [Data,errormsg]=civ_matlab(Param);% get the grid of x, y positions set for PIV
4357        if ~isempty(errormsg)
4358            msgbox_uvmat('ERROR',errormsg)
4359            return
4360        end
4361        SmoothingParam(irho)=Param.Patch1.FieldSmooth;
4362        Data.Civ1_U_Diff=Data.Civ1_U_Diff(Data.Civ1_FF==0);
4363        Data.Civ1_V_Diff=Data.Civ1_V_Diff(Data.Civ1_FF==0);
4364        DiffVel(irho)=sqrt(mean(Data.Civ1_U_Diff.*Data.Civ1_U_Diff+Data.Civ1_V_Diff.*Data.Civ1_V_Diff))
4365        NbSites(irho,:)=Data.Civ1_NbSites*numel(Data.Civ1_NbSites)/numel(Data.Civ1_U_Diff);
4366        Param.Patch1.SmoothingParam=2*Param.Patch1.FieldSmooth;
4367    end
4368    figure
4369    plot(SmoothingParam,DiffVel,'b',SmoothingParam,NbSites,'r')
4370    set(handles.TestPatch1,'BackgroundColor',[1 0 0])
4371else
4372    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4373    if ~isempty(corrfig)
4374        delete(corrfig)
4375    end
4376    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
4377    if ~isempty(hview_field)
4378        delete(hview_field)
4379    end
4380end
4381%'nomtype2pair': creates nomencalture for index pairs knowing the image nomenclature
4382%---------------------------------------------------------------------
4383% [nom_type_pair]=nomtype2pair(nom_type,Dti,Dtj);
4384%---------------------------------------------------------------------           
4385
4386% OUTPUT:
4387%nom_type_nc
4388
4389%---------------------------------------------------------------------
4390% INPUT:
4391% 'nom_type': string defining the kind of nomenclature used:
4392     %nom_type='': constant name [filebase ext] (default output if 'nom_type' is undefined)
4393     %nom_type='*': the same  file [filebase ext] contains successive fields (ex avi movies)
4394     %nom_type='_i': series of files with a single index i preceded by '_'(e.g. 'aa_45.png').
4395     %nom_type='#' series of indexed images wich is not series_i [filebase index ext], e.g. 'aa045.jpg' or 'aa45.tif'
4396     %nom_type='_i_j' matrix of files with two indices i and j separated by '_'(e.g. 'aa_45_2.png')
4397     %nom_type='_i1-i2' from pairs from a single index (e.g. 'aa_45-47.nc')
4398     %nom_type='_i_j1-j2'pairs of j indices (e.g. 'aa_45_2-3.nc')
4399     %nom_type='_i1-i2_j' pairs of i indices (e.g. 'aa_45-46_2.nc')
4400     %nom_type='#a','#A', with a numerical index and an index letter(e.g.'aa045b.png'), OBSOLETE (replaced by 'series_i_j')
4401     %nom_type='%03d' or '%04d', series of indexed images with numbers completed with zeros to 3 or 4 digits, e.g.'aa045.tif'
4402     %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'
4403     %nom_type='raw_SMD', same as '#a' but with no extension ext='', OBSOLETE
4404     %nom_type='#_ab' from pairs of '#a' images (e.g. 'aa045bc.nc'), ext='.nc', OBSOLETE (replaced by 'netc_2D')
4405     %nom_type='%3dab' from pairs of '%3da' images (e.g. 'aa045bc.nc'), ext='.nc', OBSOLETE (replaced by 'netc_2D')
4406% Dti: ~=0 if i index pairs are used
4407% Dtj: ~=0 if i index pairs are used
4408
4409function NomTypeNc=nomtype2pair(NomTypeIma,mode)
4410
4411%determine nom_type_nc:
4412NomTypeNc=NomTypeIma;%default
4413switch mode
4414    case 'pair j1-j2'     
4415    if ~isempty(regexp(NomTypeIma,'a$'))
4416        NomTypeNc=[NomTypeIma 'b'];
4417    elseif ~isempty(regexp(NomTypeIma,'A$'))
4418        NomTypeNc=[NomTypeIma 'B'];
4419    else
4420        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4421        if ~isempty(r)
4422            NomTypeNc='_1_1-2';
4423        end
4424    end
4425    case 'series(Dj)' 
4426        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4427        if ~isempty(r)
4428            NomTypeNc='_1_1-2';
4429        end
4430   case 'series(Di)'
4431        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4432        if ~isempty(r)
4433            NomTypeNc='_1-2_1';
4434        else
4435            NomTypeNc='_1-2';
4436        end
4437end
4438
4439function NomType_Callback(hObject, eventdata, handles)
4440set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
4441RootPath=get(handles.RootPath,'String');
4442RootFile=get(handles.RootFile,'String');
4443ref_i=str2num(get(handles.ref_i,'String'));
4444ref_j=str2num(get(handles.ref_j,'String'));
4445NomType=get(handles.NomType,'String');
4446ImaExt=get(handles.ImaExt,'String');
4447fileinput=fullfile_uvmat(RootPath,'',RootFile,ImaExt,NomType,ref_i,[],ref_j);
4448errormsg=display_file_name(handles,fileinput);
4449if ~isempty(errormsg)
4450    msgbox_uvmat('ERROR',errormsg)
4451end
4452set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
4453
4454% --- Executes on selection change in ListProgram.
4455function ListProgram_Callback(hObject, eventdata, handles)
4456ListProgram=get(handles.ListProgram,'String');
4457Program=ListProgram{get(handles.ListProgram,'value')};
4458switch Program
4459    case 'CivX'
4460        set(handles.num_MaxDiff,'Visible','off')
4461        set(handles.num_MaxVel,'Visible','off')
4462        set(handles.title_MaxVel,'Visible','off')
4463        set(handles.num_Nx,'Visible','on')
4464        set(handles.num_Ny,'Visible','on')
4465        set(handles.title_Nx,'Visible','on')
4466        set(handles.title_Ny,'Visible','on')
4467        set(handles.title_MaxDiff,'Visible','off')
4468        set(handles.num_CorrSmooth,'Style','edit')
4469        set(handles.num_CorrSmooth,'String','1')
4470        set(handles.BATCH,'Enable','on')
4471        set(handles.CheckThreshold,'Visible','off')
4472        set(handles.CheckDeformation,'Value',1)
4473        set(handles.CheckDecimal,'Value',1)
4474    case 'Matlab'
4475        set(handles.num_MaxDiff,'Visible','on')
4476        set(handles.num_MaxVel,'Visible','on')
4477        set(handles.title_MaxVel,'Visible','on')
4478        set(handles.title_MaxDiff,'Visible','on')
4479        set(handles.num_Nx,'Visible','off')
4480        set(handles.num_Ny,'Visible','off')
4481        set(handles.title_Nx,'Visible','off')
4482        set(handles.title_Ny,'Visible','off')
4483        set(handles.num_CorrSmooth,'Style','popupmenu')
4484        set(handles.num_CorrSmooth,'Value',1)
4485        set(handles.num_CorrSmooth,'String',{'1';'2'})
4486        set(handles.CheckThreshold,'Visible','on')
4487        set(handles.CheckDeformation,'Value',0)% desactivate (work in progress)
4488        set(handles.CheckDecimal,'Value',0)% desactivate (work in progress)
4489end
4490
4491
4492% --- Executes on button press in TestCiv2.
4493function TestCiv2_Callback(hObject, eventdata, handles)
4494
4495
4496
4497function RootFile_Callback(hObject, eventdata, handles)
4498
4499
4500
4501function SubdirImages_Callback(hObject, eventdata, handles)
Note: See TracBrowser for help on using the repository browser.