source: trunk/src/civ.m @ 500

Last change on this file since 500 was 500, checked in by sommeria, 9 years ago

various bug corrections

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