source: trunk/src/civ.m @ 784

Last change on this file since 784 was 784, checked in by sommeria, 10 years ago

adpat uvmat to reading data from rdvision

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