source: trunk/src/civ.m @ 622

Last change on this file since 622 was 621, checked in by sommeria, 8 years ago

pb of time repaired in civ

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