source: trunk/src/civ.m @ 975

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