source: trunk/src/civ.m @ 579

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

grid improved for civ: computation done closer to the edge. set_grid improved.

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