source: trunk/src/civ.m @ 728

Last change on this file since 728 was 662, checked in by sommeria, 11 years ago

bug corrected in xml2struct

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