source: trunk/src/civ.m @ 589

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

various minor corrections made

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