source: trunk/src/civ.m @ 501

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

various improvements: read input parameters for civ. Order of panels rationalised.
rationalisation in find_field_indices
simplification of default PARAM.xml, suppress unneeded information.

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