source: trunk/src/civ.m @ 1086

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