source: trunk/src/civ.m @ 505

Last change on this file since 505 was 505, checked in by sommeria, 12 years ago

bugs correctied in civ. test for compilation need introduced in check_files

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