source: trunk/src/civ.m @ 611

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

problem of time display repaired

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