source: trunk/src/civ.m @ 487

Last change on this file since 487 was 487, checked in by sommeria, 12 years ago

Problems with the new launch_jobs resolved

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