source: trunk/src/civ.m @ 486

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

cmd modified for Windows \ + record time

File size: 193.9 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,'(\w+)([/\\])(\w+$)','$1$20_BAT$2$3.m');
1311            case {'CivX','CivAll','civ_matlab.sh'}
1312                switch computer
1313                    case {'PCWIN','PCWIN64'}
1314                        filename_bat=regexprep(Param.OutputFile,'(\w+)([/\\])(\w+$)','$1$20_BAT$2$3.bat');
1315                    case {'GLNX86','GLNXA64','MACI64'}
1316                        filename_bat=regexprep(Param.OutputFile,'(\w+)([/\\])(\w+$)','$1$20_BAT$2$3.sh');
1317                end
1318        end
1319       
1320        % print the command in the bat file
1321        [fid,message]=fopen(filename_bat,'w');
1322        if isequal(fid,-1)
1323            errormsg=['creation of .bat file: ' message];
1324            return
1325        end
1326        fprintf(fid,cmd);
1327        fclose(fid);
1328       
1329        % special case for civ_matlab on cluster
1330        if strcmp(Param.Program,'civ_matlab') && strcmp(Param.RunMode,'cluster')
1331            filename_bat2=regexprep(Param.OutputFile,'(\w+)([/\\])(\w+$)','$1$20_BAT$2$3.sh');
1332            [fid,message]=fopen(filename_bat2,'w');
1333            if isequal(fid,-1)
1334                errormsg=['creation of .bat file: ' message];
1335                return
1336            end
1337            fprintf(fid,['#!/bin/bash \n' ...
1338                '/etc/sysprofile \n'...
1339                'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
1340                'addpath(''' path_civ ''');\n']);
1341            for p=1:length(batch_file_list)
1342                fprintf(fid,['run ' filename_bat '\n']);
1343            end
1344            fprintf(fid, 'exit \n END_MATLAB \n');
1345            fclose(fid);
1346            filename_bat=filename_bat2;
1347        end
1348       
1349        switch computer
1350            case {'GLNX86','GLNXA64','MACI64'}
1351                system(['chmod +x ' filename_bat]);
1352        end
1353        batch_file_list{length(batch_file_list)+1}=filename_bat;
1354    end
1355end
1356
1357%% start calculation
1358%computation on cluster
1359%if batch ==3
1360switch Param.RunMode,
1361    case 'cluster'
1362        switch batch_mode
1363            case 'sge' %at the moment only psmn ENS Lyon uses it
1364                for p=1:length(batch_file_list)
1365                    %cmd=['!qsub -p ' pvalue ' -q civ.q -e ' flname '.errors -o ' flname '.log' ' ' batch_file_list{p}];
1366                    cmd=['!qsub -q piv1,piv2,piv3 '...
1367                        '-e ' regexprep(batch_file_list{p},'.bat','.errors') ' -o ' regexprep(batch_file_list{p},'.bat','.log ')...
1368                        ' -v ' 'LD_LIBRARY_PATH=/home/sjoubaud/matlab_sylvain/civx/lib ' batch_file_list{p}];
1369                    display(cmd);eval(cmd);
1370                end
1371            case 'oar_old' % to remove
1372                for p=1:length(batch_file_list)
1373                    oar_command=['!oarsub -n CIVX -q nicejob '...
1374                        '-E ' regexprep(batch_file_list{p},'.bat','.errors') ' -O ' regexprep(batch_file_list{p},'.bat','.log ')...
1375                        '-l "/core=1+{type = ''smalljob''}/licence=1,walltime=00:60:00"   ' batch_file_list{p}];
1376                    display(oar_command);eval(oar_command);
1377                end
1378            case 'oar'
1379                max_walltime=3600*12; % 12h max
1380                oar_modes={'oar-parexec','oar-dispatch','mpilauncher'};
1381                text={'Batch processing on servcalcul3 LEGI';...
1382                    'Please choose one of the followint modes';...
1383                    '* oar-parexec : default and best choice';...
1384                    '* oar-dispatch : jobs in a container of several cores';...
1385                    '* mpilauncher : one single parallel mpi job using several cores';...
1386                    '**********************************'...
1387                    };
1388                [S,v]=listdlg('PromptString',text,'ListString',oar_modes,...
1389                    'SelectionMode','single','ListSize',[400 100],'Name','LEGI job mode');
1390                switch oar_modes{S}
1391                    case 'oar-parexec' %oar-dispatch.pl
1392                        answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
1393                        ncores=str2double(answer{1});
1394                        if strcmp(Param.Program,'civ_matlab')
1395                            ncores=1;
1396                        end
1397                        extra_oar=answer{2};
1398                        walltime_onejob=600;%seconds
1399                        filename_joblist=fullfile(RootBat,'job_list.txt');
1400                        fid=fopen(filename_joblist,'w');
1401                        for p=1:length(batch_file_list)
1402                            fprintf(fid,[batch_file_list{p} '\n']);
1403                        end
1404                        fclose(fid);
1405                        oar_command=['oarsub -n CIVX '...
1406                            '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
1407                            '-l /core=' num2str(ncores) ','...
1408                            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,max_walltime/86400),13) ' '...
1409                            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1410                            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1411                            extra_oar ' '...
1412                            '"oar-parexec -s -f ' filename_joblist ' '...
1413                            '-l ' filename_joblist '.log"\n'];
1414                        filename_oarcommand=fullfile(RootBat,'oar_command');
1415                        fid=fopen(filename_oarcommand,'w');
1416                        fprintf(fid,oar_command);
1417                        fclose(fid);
1418                        fprintf(oar_command);% display in command line
1419                        system(oar_command);
1420%                         eval(['! . ' filename
1421%                             _oarcommand])
1422                    case 'oar-dispatch' %oar-dispatch.pl
1423                        ncores=str2double(...
1424                            inputdlg('Number of cores (max 36)','oarsub parameter',1,{'6'})...
1425                            );
1426                        walltime_onejob=600;%seconds
1427                        filename_joblist=fullfile(RootBat,'job_list.txt');
1428                        fid=fopen(filename_joblist,'w');
1429                        for p=1:length(batch_file_list)
1430                            oar_command=['oarsub -n CIVX '...
1431                                '-E ' regexprep(batch_file_list{p},'\.bat\>','.stderr') ' -O ' regexprep(batch_file_list{p},'\.bat\>','.stdout ')...
1432                                '-l "/core=1,walltime=' datestr(walltime_onejob/86400,13) '"   ' batch_file_list{p}];
1433                            fprintf(fid,[oar_command '\n']);
1434                        end
1435                        fclose(fid);
1436                        oar_command=['oarsub -t container -n civx-container '...
1437                            '-l /core=' num2str(ncores)...
1438                            ',walltime=' datestr(1.05*walltime_onejob/86400*max(length(batch_file_list),ncores)/ncores,13) ' '...
1439                            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1440                            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1441                            '"oar-dispatch -f ' filename_joblist '"'];
1442                        filename_oarcommand=fullfile(RootBat,'oar_command');
1443                        fid=fopen(filename_oarcommand,'w');
1444                        fprintf(fid,[oar_command '\n']);
1445                        fclose(fid);
1446                        display(oar_command);
1447                        eval(['! . ' filename_oarcommand])
1448                    case 'mpilauncher'
1449                        filename_joblist=fullfile(RootBat,'job_list.txt');
1450                        fid=fopen(filename_joblist,'w');
1451                       
1452                        for p=1:length(batch_file_list)
1453                            fprintf(fid,[batch_file_list{p} '\n']);
1454                        end
1455                        fclose(fid)
1456                        text_oarscript=[...
1457                            '#!/bin/bash \n'...
1458                            '#OAR -n Mylauncher \n'...
1459                            '#OAR -l node=4/core=5,walltime=0:15:00 \n'...
1460                            '#OAR -E ' fullfile(RootBat,'stderrfile.log') ' \n'...
1461                            '#OAR -O ' fullfile(RootBat,'stdoutfile.log') ' \n'...
1462                            '# ========================================================= \n'...
1463                            '# This simple program launch a multinode parallel OpenMPI mpilauncher \n'...
1464                            '# application for coriolis PIV post-processing. \n'...
1465                            '# OAR uses oarshmost wrapper to propagate the user environement. \n'...
1466                            '# This wrapper assert that the user has the same environment on all the \n'...
1467                            '# allocated nodes (basic behavior needed by most MPI applications).  \n'...
1468                            '# \n'...
1469                            '# REQUIREMENT: \n'...
1470                            '# the oarshmost wrapper should be installed in $HOME/bin directory. \n'...
1471                            '# If a different location is used, change the line following the comment "Bidouille" \n'...
1472                            '# ========================================================= \n'...
1473                            '#   USER should only modify these 2 lines  \n'...
1474                            'WORKDIR=' pwd ' \n'...
1475                            'COMMANDE="mpilauncher  -f ' filename_joblist '" \n'...
1476                            '# ========================================================= \n'...
1477                            '# DO NOT MODIFY the FOLOWING LINES. (or be carefull) \n'...
1478                            'echo "job starting on: "`hostname` \n'...
1479                            'MPINODES="-host `tr [\\\\\\n] [,] <$OAR_NODEFILE |sed -e "s/,$/ /"`" \n'...
1480                            'NCPUS=`cat $OAR_NODEFILE |wc -l` \n'...
1481                            '#========== Bidouille ============== \n'...
1482                            'export OMPI_MCA_plm_rsh_agent=oar-envsh \n'...%                     'cd $WORKDIR \n'...
1483                            'CMD="mpirun -np $NCPUS -wdir $WORKDIR $MPINODES $COMMANDE" \n'...
1484                            'echo "I run: $CMD"  \n'...
1485                            '$CMD \n'...
1486                            'echo "job ending" \n'...
1487                            ];
1488                        %                 oarsub -S ./oar.sub
1489                        filename_oarscript=fullfile(RootBat,'oar_command');
1490                        fid=fopen(filename_oarscript,'w');
1491                        fprintf(fid,[text_oarscript]);
1492                        fclose(fid);
1493                        eval(['!chmod +x  ' filename_oarscript]);
1494                        eval(['!oarsub -S ' filename_oarscript]);
1495                end
1496        end
1497    case {'background','local'}
1498        switch Param.Program
1499            case {'civ_matlab'}
1500                switch Param.RunMode
1501                    case 'background'
1502                        switch computer
1503                            case {'PCWIN','PCWIN64'}
1504                                filename_superbat=fullfile(RootBat,'job_list.bat');
1505                                fid=fopen(filename_superbat,'w');
1506                                if fid==-1
1507                                    msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1508                                    return
1509                                end
1510                                    %%% TODO FOR WINDOWS : TRANSLATE
1511                                    %%% COMMANDS BELOW
1512%                                 fprintf(fid,['#!/bin/bash \n' ...
1513%                                     '/etc/sysprofile \n'...
1514%                                     'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
1515%                                     'addpath(''' path_civ ''');\n']);
1516%                                 for p=1:length(batch_file_list)
1517%                                     fprintf(fid,['run ' batch_file_list{p} '\n']);
1518%                                 end
1519%                                 fprintf(fid, 'exit \n END_MATLAB \n');
1520                                fclose(fid);
1521%                                 system(['chmod +x ' filename_superbat]);
1522%                                 system([filename_superbat ' &']);
1523                            case {'GLNX86','GLNXA64','MACI64'}
1524                                filename_superbat=fullfile(RootBat,'job_list.sh');
1525                                fid=fopen(filename_superbat,'w');
1526                                if fid==-1
1527                                    msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1528                                    return
1529                                end
1530                                fprintf(fid,['#!/bin/bash \n' ...
1531                                    '/etc/sysprofile \n'...
1532                                    'matlab -nodisplay -nosplash -nojvm <<END_MATLAB \n'...
1533                                    'addpath(''' path_civ ''');\n']);
1534                                for p=1:length(batch_file_list)
1535                                    fprintf(fid,['run ' batch_file_list{p} '\n']);
1536                                end
1537                                fprintf(fid, 'exit \n END_MATLAB \n');
1538                                fclose(fid);
1539                                system(['chmod +x ' filename_superbat]);
1540                                system([filename_superbat ' &']);
1541                        end
1542                    case 'local'
1543                        for p=1:length(batch_file_list)
1544                            fid=fopen(batch_file_list{p});
1545                            eval(fscanf(fid,'%s'));
1546                            fclose(fid);
1547                        end
1548                end
1549            case {'CivX','CivAll','civ_matlab.sh'}
1550                    switch computer
1551                        case {'PCWIN','PCWIN64'}
1552                            filename_superbat=fullfile(RootBat,'job_list.bat');
1553                            fid=fopen(filename_superbat,'w');
1554                            if fid==-1
1555                                msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1556                                return
1557                            end
1558                            for p=1:length(batch_file_list)
1559                                fprintf(fid,['@call "' regexprep(batch_file_list{p},'\\','\\\\') '"' '\n']);
1560                            end
1561                            fclose(fid);
1562                            system(['chmod +x ' filename_superbat]);
1563                        case {'GLNX86','GLNXA64','MACI64'}
1564                            filename_superbat=fullfile(RootBat,'job_list.bat');
1565                            fid=fopen(filename_superbat,'w');
1566                            if fid==-1
1567                                msgbox_uvmat('ERROR',['cannot create the command file ' filename_superbat])
1568                                return
1569                            end
1570                            for p=1:length(batch_file_list)
1571                                fprintf(fid,['sh ' batch_file_list{p} '\n']);
1572                            end
1573                            fclose(fid);
1574                            system(['chmod +x ' filename_superbat]);
1575                    end
1576                switch Param.RunMode
1577                    case 'background'
1578                        system([filename_superbat ' &']);% execute main commmand see what it does in dos ?
1579                    case 'local'
1580                        system(filename_superbat);
1581                end
1582        end
1583end
1584
1585
1586%% save interface state
1587if isfield(filecell,'nc')
1588    if isfield(filecell.nc,'civ2')
1589        fileresu=filecell.nc.civ2{1,1};
1590    else
1591        fileresu=filecell.nc.civ1{1,1};
1592    end
1593end
1594[RootPath,SubDir,RootFile]=fileparts_uvmat(fileresu);
1595namedoc=fullfile(RootPath,SubDir,RootFile);
1596detect=1;
1597while detect==1
1598    namefigfull=[namedoc '.fig'];
1599    hh=dir(namefigfull);
1600    if ~isempty(hh)
1601        detect=1;
1602        namedoc=[namedoc '.0'];
1603    else
1604        detect=0;
1605    end
1606end
1607Param=rmfield(Param,'status');
1608Param=rmfield(Param,'xml');
1609t=struct2xml(Param);
1610t=set(t,1,'name','Civ');% set the head label
1611save(t,[namedoc '.civ.xml']); %save GUI  parameters as xml file
1612% saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
1613
1614%Save info in personal profile (initiate browser next time) TODO
1615MenuFile={};
1616dir_perso=prefdir;
1617profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1618if exist(profil_perso,'file')
1619    hh=load (profil_perso);
1620      if isfield(hh,'MenuFile')
1621          MenuFile=hh.MenuFile;
1622      end
1623      if isfield(filecell.nc,'civ2')
1624          MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
1625      else
1626           MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
1627      end
1628      save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
1629else
1630    MenuFile=filecell.ima1.civ1(1,1);
1631    save (profil_perso,'MenuFile')
1632end
1633
1634%------------------------------------------------------------------------
1635% --- determine the list of reference indices of processing file
1636function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
1637%------------------------------------------------------------------------
1638errormsg=''; %default error message
1639first_i=str2double(get(handles.first_i,'String'));%first index i
1640last_i=str2double(get(handles.last_i,'String'));%last index i
1641incr_i=str2double(get(handles.incr_i,'String'));% increment
1642if isequal(get(handles.first_j,'Visible'),'on')
1643    first_j=str2double(get(handles.first_j,'String'));%first index j
1644    last_j=str2double(get(handles.last_j,'String'));%last index j
1645    incr_j=str2double(get(handles.incr_j,'String'));% increment
1646else
1647    first_j=1;
1648    last_j=1;
1649    incr_j=1;
1650end
1651ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
1652ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
1653if isnan(first_i)||isnan(first_j)
1654    errormsg='first field number not defined';
1655elseif isnan(last_i)||isnan(last_j)
1656    errormsg='last field number not defined';
1657elseif isnan(incr_i)||isnan(incr_j)
1658    errormsg='increment in field number not defined';
1659elseif last_i < first_i || last_j < first_j
1660    errormsg='last field number must be larger than the first one';
1661end
1662
1663%------------------------------------------------------------------------
1664% --- determine the list of filenames and indices needed for launch_job
1665%------------------------------------------------------------------------
1666% OUTPUT:
1667% filecell: structure of cell arrays {ref_i,ref_j} containing all the filenames involved in the civ process
1668%    the indices ref_i and ref_j correspond to the list of reference indices
1669%       .filebase=fullfile(RootPath,RootFile) used to construct mask names, grid names, CivDoc xml file
1670%       .ima1.civ1,.ima1.civ2: first image for civ1 and civ2 respectively (possibly different)
1671%       .ima2.civ1,.ima2.civ2: second image for civ1 and civ2 respectively (possibly different)
1672%       .nc.civ1,.nc.civ2: netcdf files containing civ1 and civ2 data respectively (possibly different)
1673% i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2: arrays of files indices, needed for timing records
1674function [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]=...
1675    set_civ_filenames(handles,ref_i,ref_j,checkbox)
1676%------------------------------------------------------------------------
1677filecell=[];%default
1678errormsg='';
1679ListProgram=get(handles.Program,'String');
1680CivMode=ListProgram{get(handles.Program,'Value')};%Program to use , CivX or Matlab
1681
1682%% get the root name and check dir
1683RootPath=get(handles.RootPath,'String');
1684SubdirImages=get(handles.SubdirImages,'String');
1685RootFile=get(handles.RootFile,'String');
1686filecell.filebase=fullfile(RootPath,SubdirImages,RootFile);
1687if isempty(filecell.filebase)
1688    errormsg='please open an image with the upper menu option Open/Browse...';
1689    return
1690end
1691if ~exist(RootPath,'dir')
1692    errormsg=['path to images ' RootPath ' not found'];
1693    return
1694end
1695[tild,message]=fileattrib(RootPath);
1696if ~isempty(message) && ~isequal(message.UserWrite,1)
1697    errormsg=['No writting access to ' RootPath];
1698    return
1699end
1700%check result directory
1701subdir_civ1=regexprep(get(handles.SubdirCiv1,'String'),'^.','');%subdirectory subdir_civ1 for the netcdf output data
1702subdir_civ2=regexprep(get(handles.SubdirCiv2,'String'),'^.','');
1703if isequal(subdir_civ1,''),subdir_civ1='civ'; end% put default subdir
1704% subdir_civ1=[ '.' subdir_civ1];
1705% subdir_civ2=[ '.' subdir_civ2];
1706if isequal(subdir_civ2,''),subdir_civ2=subdir_civ1; end% put default subdir
1707subdir_civ1=[SubdirImages '.' subdir_civ1];
1708subdir_civ2=[SubdirImages '.' subdir_civ2];
1709
1710%% choose root names depending on ListCompareMode =displacement, shift, PIV or stereo PIV
1711ListCompareMode=get(handles.ListCompareMode,'String');
1712compare=ListCompareMode{get(handles.ListCompareMode,'Value')};
1713
1714% set the nomenclature type of the nc files depending on the pair mode
1715if strcmp(compare,'displacement')||strcmp(compare,'shift')
1716    mode='displacement';
1717else
1718    mode_list=get(handles.ListPairMode,'String');
1719    mode_value=get(handles.ListPairMode,'Value');
1720    mode=mode_list{mode_value};
1721end
1722NomType_ima2=get(handles.NomType,'String');
1723NomType_nc=nomtype2pair(NomType_ima2,mode);
1724
1725% set the rootfile and image indexing
1726RootFile_ima2=get(handles.RootFile,'String');%root file for the second image series
1727ext_ima=get(handles.ImaExt,'String'); % image extension (the same for all images)
1728switch compare
1729    case 'PIV'
1730       RootFile_ima1=RootFile_ima2;% root name of the two image series is the same
1731       NomType_ima1=NomType_ima2;% the index of the first image follows the index of the second one
1732       RootFile_nc=RootFile_ima2;
1733    case 'displacement'
1734       RootFile_ima1=get(handles.RootFile_1,'String');% root name of the first image series set by handles.RootFile_1
1735       NomType_ima1='';% no indexing of the first image, a fixed reference for the whole series
1736       RootFile_nc=RootFile_ima2;
1737    case 'shift'
1738       RootFile_ima1=get(handles.RootFile_1,'String');% root name of the first image series set by handles.RootFile_1
1739       NomType_ima1=NomType_ima2;% the index of the first image follows the index of the second one
1740       RootFile_nc=[RootFile_ima1 '-' RootFile_ima2];
1741end
1742
1743%determine the list of file indices involved
1744[i1_civ1,i2_civ1,j1_civ1,j2_civ1,i1_civ2,i2_civ2,j1_civ2,j2_civ2]=...
1745    find_pair_indices(handles,ref_i,ref_j,mode);
1746
1747%determine the new filebase for 'displacement' ListPairMode (comparison of two series)
1748%filebase_B=filebase;% root name of the second field series for stereo
1749% filebase_A=filebase;%default
1750% if strcmp(compare,'PIV')
1751%     filebase_AB=filebase;
1752% else
1753%     [Path2,Name2]=fileparts(filebase_B);
1754%     Name1=RootFile_ima1;
1755%     filebase_AB=fullfile(Path2,[Name2 '-' Name1]);   
1756% end
1757% [RootPath_AB,RootFile_AB]=fileparts(filebase_AB);
1758% % [RootPath_ima1,RootFile_ima1]=fileparts(filebase_B);
1759% [RootPath_ima2,RootFile_ima2]=fileparts(filebase_B);
1760% [RootPath_nc,RootFile_nc]=fileparts(filebase_B);%default
1761% if strcmp(compare,'displacement')
1762% %     [RootPath_ima1,RootFile_ima1]=fileparts(filebase_B);
1763% %     [RootPath_ima2,RootFile_ima2]=fileparts(filebase_B);
1764%     [RootPath_nc,RootFile_nc]=fileparts(filebase_B);
1765% elseif strcmp(compare,'shift')
1766%     RootPath_nc=RootPath_AB;
1767%     RootFile_nc=RootFile_AB;
1768% end
1769% else
1770%     filebase_ima1=filebase_B;
1771%     filebase_ima2=filebase_B;
1772%     filebase_nc=filebase_B;
1773% [RootPath_ima1,RootFile_ima1]=fileparts(filebase_ima1);
1774% [RootPath_ima2,RootFile_ima2]=fileparts(filebase_ima2);
1775% [RootPath_nc,RootFile_nc]=fileparts(filebase_nc);
1776% [RootPath_A,RootFile_A]=fileparts(filebase_A);
1777
1778   
1779%% determine reference files for fix:
1780file_ref_fix1={};%default
1781file_ref_fix2={};
1782nbfield=length(i1_civ1);
1783nbslice=length(j1_civ1);
1784if checkbox(2)==1% fix1 performed
1785    ref=get(handles.ref_fix1,'UserData');%read data on the ref file stored by get_ref_fix1_Callback
1786    if ~isempty(ref)
1787        first_i=str2double(get(handles.first_i,'String'));
1788        last_i=str2double(get(handles.last_i,'String'));
1789        incr_i=str2double(get(handles.incr_i,'String'));
1790        first_j=str2double(get(handles.first_j,'String'));
1791        last_j=str2double(get(handles.last_j,'String'));
1792        incr_j=str2double(get(handles.incr_j,'String'));
1793        num_i_ref=first_i:incr_i:last_i;
1794        num_j_ref=first_j:incr_j:last_j;
1795        if isequal(mode,'displacement')
1796            num_i1=num_i_ref;
1797            num_i2=num_i_ref;
1798            num_j1=num_j_ref;
1799            num_j2=num_j_ref;
1800        elseif isequal(mode,'pair j1-j2')% isequal(mode,'st_pair j1-j2')
1801            num_i1=num_i_ref;
1802            num_i2=num_i1;
1803            num_j1=ref.num_a*ones(size(num_i_ref));
1804            num_j2=ref.num_b*ones(size(num_i_ref));
1805        elseif isequal(mode,'series(Di)') % isequal(mode,'st_series(Di)')
1806            delta1=floor((ref.num2-ref.num1)/2);
1807            delta2=ceil((ref.num2-ref.num1)/2);
1808            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
1809            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
1810            if isempty(ref.num_a)
1811                ref.num_a=1;
1812            end
1813            num_j1=ref.num_a*ones(size(num_i1));
1814            num_j2=num_j1;
1815        elseif isequal(mode,'series(Dj)')%| isequal(mode,'st_series(Dj)')
1816            delta1=floor((ref.num_b-ref.num_a)/2);
1817            delta2=ceil((ref.num_b-ref.num_a)/2);
1818            num_i1=ref.num1*ones(size(num_i_ref));
1819            num_i2=num_i1;
1820            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
1821            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
1822        end
1823        for ifile=1:nbfield
1824            for j=1:nbslice
1825                [RootPathRef,RootFile]=fileparts(ref.filebase);
1826                file_ref=fullfile_uvmat(RootPathRef,ref.subdir,RootFile,'.nc',ref.NomType,num_i1(ifile),num_i2(ifile),num_j1(j),num_j2(j));
1827                file_ref_fix1(ifile,j)={file_ref};
1828                if ~exist(file_ref,'file')
1829                    errormsg=['reference file ' file_ref ' not found for fix1'];
1830                    return
1831                end
1832            end
1833        end
1834    end
1835end
1836
1837%% determine reference files for fix2:
1838if checkbox(5)==1% fix2 performed
1839    ref=get(handles.ref_fix2,'UserData');
1840    if ~isempty(ref)
1841        first_i=str2double(get(handles.first_i,'String'));
1842        last_i=str2double(get(handles.last_i,'String'));
1843        incr_i=str2double(get(handles.incr_i,'String'));
1844        first_j=str2double(get(handles.first_j,'String'));
1845        last_j=str2double(get(handles.last_j,'String'));
1846        incr_j=str2double(get(handles.incr_j,'String'));
1847        num_i_ref=first_i:incr_i:last_i;
1848        num_j_ref=first_j:incr_j:last_j;
1849        if isequal(mode,'displacement')
1850            num_i1=num_i_ref;
1851            num_i2=num_i_ref;
1852            num_j1=num_j_ref;
1853            num_j2=num_j_ref;
1854        elseif isequal(mode,'pair j1-j2')
1855            num_i1=num_i_ref;
1856            num_i2=num_i1;
1857            num_j1=ref.num_a;
1858            num_j2=ref.num_b;
1859        elseif isequal(mode,'series(Di)')
1860            delta1=floor((ref.num2-ref.num1)/2);
1861            delta2=ceil((ref.num2-ref.num1)/2);
1862            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
1863            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
1864            num_j1=ref.num_a*ones(size(num_i1));
1865            num_j2=num_j1;
1866        elseif isequal(mode,'series(Dj)')
1867            delta1=floor((ref.num_b-ref.num_a)/2);
1868            delta2=ceil((ref.num_b-ref.num_a)/2);
1869            num_i1=ref.num1*ones(size(num_i_ref));
1870            num_i2=num_i1;
1871            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
1872            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
1873        end
1874        for ifile=1:nbfield
1875            for j=1:nbslice
1876                [RootPathRef,RootFile]=fileparts(ref.filebase);
1877                file_ref=fullfile_uvmat(RootPathRef,ref.subdir,RootFile,'.nc',ref.NomType,num_i1(ifile),num_i2(ifile),num_j1(j),num_j2(j));
1878                file_ref_fix2(ifile,j)={file_ref};
1879                if ~exist(file_ref,'file')
1880                    errormsg=['reference file ' file_ref ' not found for fix2'];
1881                    return
1882                end
1883            end
1884        end
1885    end
1886end
1887
1888%% check the existence of the netcdf and image files involved
1889% %%%%%%%%%%%%  case CheckCiv1 activated   %%%%%%%%%%%%%
1890if checkbox(1)==1;
1891    detect=1;
1892    vers=0;
1893    subdir_civ1_new=subdir_civ1;
1894    answer='No';
1895    while detect==1 %create a new subdir if the netcdf files already exist
1896        for ifile=1:nbfield
1897            for j=1:nbslice
1898                filename=fullfile_uvmat(RootPath,subdir_civ1_new,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
1899                detect=exist(filename,'file')==2;
1900                if detect% if a netcdf file already exists
1901                    if strcmp(answer,'No')
1902                        answer=msgbox_uvmat('INPUT_Y-N',['overwrite existing civ files in ' subdir_civ1_new]);
1903                    end
1904                    if strcmp(answer,'Yes')
1905                        detect=0;
1906                        filecell.nc.civ1(ifile,j)={filename};
1907                    else
1908                        r=regexp(subdir_civ1_new,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
1909                        if isempty(r)
1910                            r(1).root=[subdir_civ1_new '_'];
1911                            r(1).num1='0';
1912                        end
1913                        subdir_civ1_new=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
1914                        subdir_civ2=subdir_civ1_new;
1915                    end
1916                    break
1917                end
1918                filecell.nc.civ1(ifile,j)={filename};
1919            end
1920            if detect% if a netcdf file already exists
1921                break
1922            end
1923        end
1924 
1925        %create the new SubdirCiv1
1926        if ~exist(fullfile(RootPath,subdir_civ1_new),'dir')     
1927            [xx,msg1]=mkdir(fullfile(RootPath,subdir_civ1_new));
1928            if ~strcmp(msg1,'')
1929                errormsg=['cannot create ' subdir_civ1_new ': ' msg1];%error message for directory creation
1930                return
1931            elseif isunix         
1932                [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
1933                if ~strcmp(msg2,'')
1934                    errormsg=['pb of permission for  ' fullfile(RootPath,subdir_civ1_new) ': ' msg2];%error message for directory creation
1935                    return
1936                end
1937            end
1938        end
1939        if strcmp(compare,'stereo PIV')&&(strcmp(mode,'pair j1-j2')||strcmp(mode,'series(Dj)')||strcmp(mode,'series(Di)'))%check second nc series
1940            for ifile=1:nbfield
1941                for j=1:nbslice
1942                     filename=fullfile_uvmat(RootPath,subdir_civ1_new,RootFile_A,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
1943                   % filename=name_generator(filebase_A,i1_civ1(ifile),j1_civ1(j),'.nc',NomType_nc,1,i2_civ1(ifile),j2_civ1(j),subdir_civ1_new);%
1944                    detect=exist(filename,'file')==2;
1945                    if detect% if a netcdf file already exists
1946                       indstr=regexp(subdir_civ1_new,'\D');
1947                       if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
1948                           vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
1949                           subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
1950                       else
1951                           vers=vers+1;
1952                           subdir_civ1_new=[subdir_civ1_new '_' num2str(vers)];
1953                       end
1954                       subdir_civ2=subdir_civ1;
1955                       break
1956                    end
1957                    filecell.ncA.civ1(ifile,j)={filename};
1958                end
1959                if detect% if a netcdf file already exists
1960                    break
1961                end
1962            end
1963            %create the new SubdirCiv1
1964            if ~exist(fullfile(RootPath,subdir_civ1_new),'dir')       
1965                [xx,msg1]=mkdir(fullfile(RootPath,subdir_civ1_new));
1966                if ~strcmp(msg1,'')
1967                    errormsg=['cannot create ' subdir_civ1_new ': ' msg1];
1968                    return
1969                else
1970                    [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
1971                    if ~strcmp(msg2,'')
1972                        errormsg=['pb of permission for ' subdir_civ1_new ': ' msg2];%error message for directory creation
1973                        return
1974                    end
1975                end
1976            end
1977        end
1978    end
1979    subdir_civ1=subdir_civ1_new;
1980    % get image names
1981    for ifile=1:nbfield
1982        for j=1:nbslice
1983             filename=fullfile_uvmat(RootPath,SubdirImages,RootFile_ima1,ext_ima,NomType_ima1,i1_civ1(ifile),[],j1_civ1(j));
1984            idetect(j)=exist(filename,'file')==2;
1985            filecell.ima1.civ1(ifile,j)={filename}; %first image
1986            filename=fullfile_uvmat(RootPath,SubdirImages,RootFile_ima2,ext_ima,NomType_ima2,i2_civ1(ifile),[],j2_civ1(j));
1987            idetect_1(j)=exist(filename,'file')==2;
1988            filecell.ima2.civ1(ifile,j)={filename};%second image
1989        end
1990        [idetectmin,indexj]=min(idetect);
1991        if idetectmin==0,
1992            errormsg=[filecell.ima1.civ1{ifile,indexj} ' not found'];
1993            return
1994        end
1995        [idetectmin,indexj]=min(idetect_1);
1996        if idetectmin==0,
1997            errormsg=[filecell.ima2.civ1{ifile,indexj} ' not found'];
1998            return
1999        end
2000    end
2001    if strcmp(compare,'stereo PIV') && (strcmp(mode,'pair j1-j2') || strcmp(mode,'series(Dj)') || strcmp(mode,'series(Di)'))
2002        for ifile=1:nbfield
2003            for j=1:nbslice
2004                filename=fullfile_uvmat(RootPath,'',RootFile_A,ext_ima,NomType_ima1,i1_civ1(ifile),[],j1_civ1(j));
2005                idetect(j)=exist(filename,'file')==2;
2006                filecell.imaA1.civ1(ifile,j)={filename} ;%first image
2007                filename=fullfile_uvmat(RootPath,'',RootFile_A,ext_ima,NomType_ima2,i2_civ1(ifile),[],j2_civ1(j));
2008                idetect_1(j)=exist(filename,'file')==2;
2009                filecell.imaA2.civ1(ifile,j)={filename};%second image
2010            end
2011            [idetectmin,indexj]=min(idetect);
2012            if idetectmin==0,
2013                errormsg=[filecell.imaA1.civ1{ifile,indexj} ' not found'];
2014                return
2015            end
2016            [idetectmin,indexj]=min(idetect_1);
2017            if idetectmin==0,
2018                errormsg=[filecell.imaA2.civ1{ifile,indexj} ' not found'];
2019                return
2020            end
2021        end
2022    end
2023   
2024    %%%%%%%%%%%%%  checkfix1 or checkpatch1 activated but no checkciv1   %%%%%%%%%%%%%
2025elseif (checkbox(2)==1 || checkbox(3)==1);
2026    for ifile=1:nbfield
2027        for j=1:nbslice
2028            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2029            detect=exist(filename,'file')==2;
2030            if detect==0
2031                errormsg=[filename ' not found'];
2032                return
2033            end
2034            filecell.nc.civ1(ifile,j)={filename};
2035        end
2036    end
2037    if strcmp(compare,'stereo PIV')
2038        for ifile=1:nbfield
2039            for j=1:nbslice
2040                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_A,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2041                filecell.ncA.civ1(ifile,j)={filename};
2042                if ~exist(filename,'file')
2043                    errormsg=['input file ' filename ' not found'];
2044                    return
2045                end
2046            end
2047        end
2048    end
2049end
2050
2051%%%%%%%%%%%%%  if checkciv2 performed with pairs different than checkciv1  %%%%%%%%%%%%%
2052testdiff=0;
2053if (checkbox(4)==1)&&...
2054        ((get(handles.ListPairCiv1,'Value')~=get(handles.ListPairCiv2,'Value'))||~strcmp(subdir_civ2,subdir_civ1))
2055    testdiff=1;
2056    detect=1;
2057    vers=0;
2058    subdir_civ2_new=subdir_civ2;
2059    while detect==1 %create a new subdir if the netcdf files already exist
2060        for ifile=1:nbfield
2061            for j=1:nbslice
2062                filename=fullfile_uvmat(RootPath,subdir_civ2_new,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2063                detect=exist(filename,'file')==2;
2064                if detect% if a netcdf file already exists
2065                    indstr=regexp(subdir_civ2,'\D');
2066                    if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2067                        vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2068                        subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2069                    else
2070                        vers=vers+1;
2071                        subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2072                    end
2073                    break
2074                end
2075                filecell.nc.civ2(ifile,j)={filename};
2076            end
2077            if detect% if a netcdf file already exists
2078                break
2079            end
2080        end
2081        %create the new subdir_civ2_new
2082        if ~exist(fullfile(RootPath,subdir_civ2_new),'dir')
2083            [xx,m2]=mkdir(fullfile(RootPath,subdir_civ2_new));
2084            [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2085            if ~isequal(m2,'')
2086                errormsg=['cannot create ' fullfile(RootPath,subdir_civ2_new) ': ' m2];
2087                return
2088            end
2089        end
2090        if strcmp(compare,'stereo PIV')%check second nc series
2091            for ifile=1:nbfield
2092                for j=1:nbslice
2093                    filename=fullfile_uvmat(RootPath,subdir_civ2_new,RootFile_A,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2094                    detect=exist(filename,'file')==2;
2095                    if detect% if a netcdf file already exists
2096                        indstr=regexp(subdir_civ2,'\D');
2097                        if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2098                           vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2099                           subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2100                        else
2101                           vers=vers+1;
2102                           subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2103                        end
2104                        break
2105                    end
2106                    filecell.ncA.civ2(ifile,j)={filename};
2107                end
2108                if detect% if a netcdf file already exists
2109                    break
2110                end
2111            end
2112            subdir_civ2=subdir_civ2_new;
2113            %create the new SubdirCiv1
2114            if ~exist(fullfile(RootPath,subdir_civ2_new),'dir')
2115                [xx,m2]=mkdir(subdir_civ2_new);
2116                 [xx,msg2] = fileattrib(fullfile(RootPath,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2117                if ~isequal(m2,'')
2118                    errormsg= ['cannot create ' fullfile(RootPath,subdir_civ2_new) ': ' m2];%error message for directory creation
2119                    return
2120                end
2121            end
2122        end
2123    end
2124    subdir_civ2=subdir_civ2_new;
2125end
2126
2127%%%%%%%%%%%%%  if checkciv2 results are obtained or used  %%%%%%%%%%%%%
2128if checkbox(4)==1 || checkbox(5)==1 || checkbox(6)==1 %civ2
2129    %check source netcdf file of checkciv1 estimates
2130    if checkbox(1)==0; %no civ1 performed
2131        for ifile=1:nbfield
2132            for j=1:nbslice
2133                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_nc,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));%
2134                filecell.nc.civ1(ifile,j)={filename};% name of the civ1 file
2135                if ~exist(filename,'file')
2136                    errormsg=['input file ' filename ' not found'];
2137                    return
2138                end
2139                if ~testdiff % civ2 or patch2 are written in the same file as civ1
2140                    if checkbox(4)==0 ; %check the existence of civ2 if it is not calculated
2141                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2142                        if isfield(Data,'Txt')
2143                            errormsg=Data.Txt;
2144                            return
2145                        elseif ~isempty(Data.CivStage)% case of new civ files
2146                            if Data.CivStage<4 %test for civ files
2147                            errormsg=['no civ2 data in ' filename];
2148                            return
2149                            end
2150                        elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2151                            errormsg=['no civ2 data in ' filename];
2152                            return
2153                        end
2154                    elseif checkbox(3)==0; %check the existence of patch if it is not calculated
2155                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','patch');
2156                        if isfield(Data,'Txt')
2157                            errormsg=Data.Txt;
2158                            return
2159                        elseif ~isempty(Data.CivStage)
2160                            if Data.CivStage<3 %test for civ files
2161                                errormsg=['no patch data in ' filename];
2162                                return
2163                            end
2164                        elseif isempty(Data.patch)||isequal(Data.patch,0)
2165                            errormsg=['no patch data in ' filename];
2166                            return
2167                        end
2168                    end
2169                end
2170            end
2171        end
2172        if strcmp(compare,'stereo PIV')
2173            for ifile=1:nbfield
2174                for j=1:nbslice
2175                    filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_A,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2176                    filecell.ncA.civ2(ifile,j)={filename};
2177                    if ~exist(filename,'file')
2178                        errormsg=['input file ' filename ' not found'];
2179                        return
2180                    end
2181                end
2182            end
2183        end
2184    end
2185   
2186    detect=1;
2187    %     while detect==1%creates a new subdir if the netcdf files already contain checkciv2 data
2188    for ifile=1:nbfield
2189        for j=1:nbslice
2190            filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2191            detect=exist(filename,'file')==2;
2192            filecell.nc.civ2(ifile,j)={filename};
2193        end
2194    end
2195    %get first image names for checkciv2
2196    if checkbox(1)==1 && isequal(i1_civ1,i1_civ2) && isequal(j1_civ1,j1_civ2)
2197        filecell.ima1.civ2=filecell.ima1.civ1;
2198    elseif checkbox(4)==1
2199        for ifile=1:nbfield
2200            for j=1:nbslice
2201                filename=fullfile_uvmat(RootPath,[],RootFile_ima1,ext_ima,NomType_ima1,i1_civ2(ifile),[],j1_civ2(j));
2202                idetect_2(j)=exist(filename,'file')==2;
2203                filecell.ima1.civ2(ifile,j)={filename};%first image
2204            end
2205            [idetectmin,indexj]=min(idetect_2);
2206            if idetectmin==0,
2207               errormsg=['input image ' filecell.ima1.civ2{ifile,indexj} ' not found'];
2208                return
2209            end
2210        end
2211    end
2212   
2213    %get second image names for checkciv2
2214    if checkbox(1)==1 && isequal(i2_civ1,i2_civ2) && isequal(j2_civ1,j2_civ2)
2215        filecell.ima2.civ2=filecell.ima2.civ1;
2216    elseif checkbox(4)==1
2217        for ifile=1:nbfield
2218            for j=1:nbslice
2219                filename=fullfile_uvmat(RootPath,[],RootFile_ima2,ext_ima,NomType_ima2,i2_civ2(ifile),[],j2_civ2(j));
2220                idetect_3(j)=exist(filename,'file')==2;
2221                filecell.ima2.civ2(ifile,j)={filename};%first image
2222            end
2223            [idetectmin,indexj]=min(idetect_3);
2224            if idetectmin==0,
2225                errormsg=['input image ' filecell.ima2.civ2{ifile,indexj} ' not found'];
2226                return
2227            end
2228        end
2229    end
2230end
2231if (checkbox(5) || checkbox(6)) && ~checkbox(4)  % need to read an existing netcdf civ2 file
2232    if ~testdiff
2233        filecell.nc.civ2=filecell.nc.civ1;% file already checked
2234    else     % check the civ2 files
2235        for ifile=1:nbfield
2236            for j=1:nbslice
2237                 filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_nc,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2238                filecell.nc.civ2(ifile,j)={filename};
2239                if ~exist(filename,'file')
2240                    errormsg=['input file ' filename ' not found'];
2241                    return
2242                else
2243                    Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2244                    if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2245                            errormsg=['no civ2 data in ' filename];
2246                            return
2247                    elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2248                        errormsg=['no civ2 data in ' filename];
2249                        return
2250                    end
2251                end
2252            end
2253        end
2254    end
2255end
2256
2257%%%%%%%%%%%%%  if stereo fields are calculated by PATCH %%%%%%%%%%%%%
2258if strcmp(compare,'stereo PIV')
2259    if  checkbox(3) && isequal(get(handles.test_stereo1,'Value'),1)
2260        for ifile=1:nbfield
2261            for j=1:nbslice
2262                 filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile_AB,'.nc',NomType_nc,i1_civ1(ifile),i2_civ1(ifile),j1_civ1(j),j2_civ1(j));
2263                filecell.st(ifile,j)={filename};
2264            end
2265        end
2266    end
2267    if  checkbox(6) && isequal(get(handles.CheckStereo,'Value'),1)
2268        for ifile=1:nbfield
2269            for j=1:nbslice
2270                 filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile_AB,'.nc',NomType_nc,i1_civ2(ifile),i2_civ2(ifile),j1_civ2(j),j2_civ2(j));
2271                filecell.st(ifile,j)={filename};
2272            end
2273        end
2274    end
2275end
2276set(handles.SubdirCiv1,'String',regexprep(subdir_civ1,['^' SubdirImages],''));%suppress the root  SuddirImages;);%update the edit box
2277set(handles.SubdirCiv2,'String',regexprep(subdir_civ2,['^' SubdirImages],''));%update the edit box
2278
2279% For CivX COPY IMAGES TO THE FORMAT .png IF NEEDED
2280if strcmp(CivMode,'CivX')
2281    if isequal(NomType_ima1,'*')%case of movie files
2282        NomType_imanew1='_i';
2283    else
2284        NomType_imanew1=NomType_ima1;
2285    end
2286    if isequal(NomType_ima2,'*')%case of movie files
2287        NomType_imanew2='_i';
2288    else
2289        NomType_imanew2=NomType_ima2;
2290    end
2291    if ~isequal(ext_ima,'.png')
2292        %%type of image file
2293        type_ima1='none';%default
2294        movieobject1=[];%default
2295        if strcmpi(ext_ima,'.avi')
2296            if ~isempty(which('mmreader'))% if the mmreader function is found (recent version of matlab)
2297                type_ima1='movie';
2298                movieobject1=mmreader([filecell.filebase ext_ima]);
2299            else
2300                type_ima1='avi';
2301            end
2302        elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2303            form=imformats(ext_ima(2:end));
2304            if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2305                if isequal(NomType_ima1,'*');
2306                    type_ima1='multimage';%image series in a single image file
2307                else
2308                    type_ima1='image';
2309                end
2310            end
2311        end
2312        type_ima2='none';%default
2313        movieobject2=[];
2314        if strcmpi(ext_ima,'.avi')
2315            if ~isempty(which('mmreader'))% if the mmreader function is found (recent version of matlab)
2316                type_ima2='movie';
2317                movieobject2=mmreader([filecell.filebase ext_ima]);
2318            else
2319                type_ima2='avi';
2320            end
2321        elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2322            form=imformats(ext_ima(2:end));
2323            if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2324                if isequal(NomType_ima1,'*');
2325                    type_ima2='multimage';%image series in a single image file
2326                else
2327                    type_ima2='image';
2328                end
2329            end
2330        end
2331        if checkbox(1) %if civ1 is performed
2332            h = waitbar(0,'copy images to the .png format for civ1');% display a wait bar
2333            for ifile=1:nbfield
2334                waitbar(ifile/nbfield);
2335                for j=1:nbslice
2336                    filename=fullfile_uvmat(RootPath,[],RootFile_ima1,'.png',NomType_imanew1,i1_civ1(ifile),[],j1_civ1(j));
2337                    if ~exist(filename,'file')
2338                        A=read_image(filecell.ima1.civ1{ifile,j},type_ima1,i1_civ1(ifile),movieobject1);
2339                        imwrite(A,filename,'BitDepth',16);
2340                    end
2341                    filecell.ima1.civ1(ifile,j)={filename};
2342                    filename=fullfile_uvmat(RootPath,[],RootFile_ima2,'.png',NomType_imanew2,i2_civ1(ifile),[],j2_civ1(j));
2343                    if ~exist(filename,'file')
2344                        A=read_image(filecell.ima2.civ1{ifile,j},type_ima2,i2_civ1(ifile),movieobject2);
2345                        imwrite(A,filename,'BitDepth',16);
2346                    end
2347                    filecell.ima2.civ1(ifile,j)={filename};
2348                end
2349            end
2350            close(h)
2351        end
2352        if checkbox(4) %if civ2 is performed
2353            h = waitbar(0,'copy images to the .png format for civ2');% display a wait bar
2354            for ifile=1:nbfield
2355                waitbar(ifile/nbfield);
2356                for j=1:nbslice
2357                    filename=fullfile_uvmat(RootPath,[],RootFile_ima1,'.png',NomType_imanew1,i1_civ2(ifile),[],j1_civ2(j));
2358                    if ~exist(filename,'file')
2359                        A=read_image(cell2mat(filecell.ima1.civ2(ifile,j)),type_ima2,i1_civ2(ifile));
2360                        imwrite(A,filename,'BitDepth',16);
2361                    end
2362                    filecell.ima1.civ2(ifile,j)={filename};
2363                    filename=fullfile_uvmat(RootPath,[],RootFile_ima2,'.png',NomType_imanew2,i2_civ2(ifile),[],j2_civ2(j));
2364                    if ~exist(filename,'file')
2365                        A=read_image(cell2mat(filecell.ima2.civ2(ifile,j)),type_ima2,i2_civ2(ifile));
2366                        imwrite(A,filename,'BitDepth',16);
2367                    end
2368                    filecell.ima2.civ2(ifile,j)={filename};
2369                end
2370            end
2371            close(h);
2372        end
2373    end
2374end
2375
2376%------------------------------------------------------------------------
2377% --- determine the list of index pairs of processing file
2378function [num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
2379    find_pair_indices(handles,ref_i,ref_j,mode)
2380%------------------------------------------------------------------------
2381
2382list_civ1=get(handles.ListPairCiv1,'String');
2383index_civ1=get(handles.ListPairCiv1,'Value');
2384str_civ1=list_civ1{index_civ1};%string defining the image pairs for civ1
2385if isempty(str_civ1)||isequal(str_civ1,'')
2386    msgbox_uvmat('ERROR','no image pair selected for civ1')
2387    return
2388end
2389list_civ2=get(handles.ListPairCiv2,'String');
2390index_civ2=get(handles.ListPairCiv2,'Value');
2391if index_civ2>length(list_civ2)
2392    list_civ2=list_civ1;
2393    index_civ2=index_civ1;
2394end
2395str_civ2=list_civ2{index_civ2};%string defining the image pairs for civ2
2396
2397if isequal (mode,'series(Di)')
2398    lastfield=str2double(get(handles.nb_field,'String'));
2399    num1_civ1=ref_i-floor(index_civ1/2)*ones(size(ref_i));% set of first image numbers
2400    num2_civ1=ref_i+ceil(index_civ1/2)*ones(size(ref_i));
2401    num_a_civ1=ref_j;
2402    num_b_civ1=ref_j;
2403    num1_civ2=ref_i-floor(index_civ2/2)*ones(size(ref_i));
2404    num2_civ2=ref_i+ceil(index_civ2/2)*ones(size(ref_i));
2405    num_a_civ2=ref_j;
2406    num_b_civ2=ref_j;   
2407   
2408    % adjust the first and last field number
2409    lastfield=str2double(get(handles.nb_field,'String'));
2410    if isnan(lastfield)
2411        indsel=find((num1_civ1 >= 1)&(num1_civ2 >= 1));
2412    else
2413        indsel=find((num2_civ1 <= lastfield)&(num2_civ2 <= lastfield)&(num1_civ1 >= 1)&(num1_civ2 >= 1));
2414    end
2415    if length(indsel)>=1
2416        firstind=indsel(1);
2417        lastind=indsel(end);
2418        set(handles.first_i,'String',num2str(ref_i(firstind)))%update the display of first and last fields
2419        set(handles.last_i,'String',num2str(ref_i(lastind)))
2420        ref_i=ref_i(indsel);
2421        num1_civ1=num1_civ1(indsel);
2422        num1_civ2=num1_civ2(indsel);
2423        num2_civ1=num2_civ1(indsel);
2424        num2_civ2=num2_civ2(indsel);
2425    end
2426elseif isequal (mode,'series(Dj)')
2427    lastfield_j=str2double(get(handles.nb_field2,'String'));
2428    num1_civ1=ref_i;% set of first image numbers
2429    num2_civ1=ref_i;
2430    num_a_civ1=ref_j-floor(index_civ1/2)*ones(size(ref_j));
2431    num_b_civ1=ref_j+ceil(index_civ1/2)*ones(size(ref_j));
2432    num1_civ2=ref_i;
2433    num2_civ2=ref_i;
2434    num_a_civ2=ref_j-floor(index_civ2/2)*ones(size(ref_j));
2435    num_b_civ2=ref_j+ceil(index_civ2/2)*ones(size(ref_j));
2436    % adjust the first and last field number
2437    if isnan(lastfield_j)
2438        indsel=find((num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2439    else
2440        indsel=find((num_b_civ1 <= lastfield_j)&(num_b_civ2 <= lastfield_j)&(num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2441    end
2442    if length(indsel)>=1
2443        firstind=indsel(1);
2444        lastind=indsel(end);
2445        set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
2446        set(handles.last_j,'String',num2str(ref_j(lastind)))
2447        ref_j=ref_j(indsel);
2448        num_a_civ1=num_a_civ1(indsel);
2449        num_b_civ1=num_b_civ1(indsel);
2450        num_a_civ2=num_a_civ2(indsel);
2451        num_b_civ2=num_b_civ2(indsel);
2452    end
2453elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
2454    displ_num=get(handles.ListPairCiv1,'UserData');
2455    num1_civ1=ref_i;
2456    num2_civ1=ref_i;
2457    num_a_civ1=displ_num(1,index_civ1);
2458    num_b_civ1=displ_num(2,index_civ1);
2459    num1_civ2=ref_i;
2460    num2_civ2=ref_i;
2461    num_a_civ2=displ_num(1,index_civ2);
2462    num_b_civ2=displ_num(2,index_civ2);
2463elseif isequal(mode,'displacement')
2464    num1_civ1=ref_i;
2465    num2_civ1=ref_i;
2466    num_a_civ1=ref_j;
2467    num_b_civ1=ref_j;
2468    num1_civ2=ref_i;
2469    num2_civ2=ref_i;
2470    num_a_civ2=ref_j;
2471    num_b_civ2=ref_j;
2472end
2473
2474%------------------------------------------------------------------------
2475% --- Executes on button press in ListCompareMode.
2476function ListCompareMode_Callback(hObject, eventdata, handles)
2477%------------------------------------------------------------------------
2478ListCompareMode=get(handles.ListCompareMode,'String');
2479option=ListCompareMode{get(handles.ListCompareMode,'Value')};
2480if ~strcmp(option,'PIV') % case 'displacement' or 'stereo PIV'
2481    filebase=get(handles.RootPath,'String');
2482    set(handles.sub_txt,'Visible','on')
2483    set(handles.RootFile_1,'Visible','On');%mkes the second file input window visible
2484    mode_store=get(handles.ListPairMode,'String');%get the present 'mode'
2485    set(handles.ListCompareMode,'UserData',mode_store);%store the mode display
2486    set(handles.ListPairMode,'Visible','off')
2487   
2488    %% open an image file with the browser
2489    ind_opening=1;%default
2490    browse.incr_pair=[0 0]; %default
2491    oldfile=get(handles.RootPath,'String');
2492    menu={'*.png;*.jpg;*.tif;*.avi;*.AVI;', ' (*.png,*.jpg ,.tif, *.avi,*.AVI)';
2493        '*.png','.png image files'; ...
2494        '*.jpg',' jpeg image files'; ...
2495        '*.tif','.tif image files'; ...
2496        '*.avi;*.AVI','.avi movie files'; ...
2497        '*.*',  'All Files (*.*)'};
2498    if strcmp(option,'displacement')
2499        comment='Pick the reference file for displacements';
2500    else
2501        comment='Pick a file of the second series';
2502    end
2503    [FileName, PathName] = uigetfile( menu, comment,oldfile);
2504    fileinput=[PathName FileName];%complete file name
2505    sizf=size(fileinput);
2506    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
2507    [path,name,ext]=fileparts(fileinput);
2508    [path1]=fileparts(filebase);
2509    if isunix
2510        [status,path]=system(['readlink ' path]);
2511        [status,path1]=system(['readlink ' path1]);% look for the true path in case of symbolic paths
2512    end
2513    if ~strcmp(path1,path)
2514        msgbox_uvmat('ERROR','The second image or series must be in the same directory as the first one')
2515        return
2516    end
2517    if strcmp(option,'displacement')
2518        [tild,RootFile_1]=fileparts(name);
2519    else
2520        [FilePath,FileName,Ext]=fileparts(fileinput);
2521% detect the file type, get the movie object if relevant, and look for the corresponding file series:
2522% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
2523[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]);
2524       
2525       % [tild,tild,RootFile_1,tild,tild,tild,tild,tild,nom_type_1]=fileparts_uvmat(fileinput);
2526        %[RootFile_1,i1_series,tild,j1_series,tild,nom_type_1,FileType,Object]=find_file_series(PathName,FileName);
2527        %check image nom type
2528        if ~strcmp(nom_type_1,get(handles.NomType,'String'))
2529        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')
2530        return
2531        end
2532    end   
2533    %check image  extension
2534    if ~strcmp(ext,get(handles.ImaExt,'String'))
2535        msgbox_uvmat('ERROR','The second image series must have the same extension name as the first one')
2536        return
2537    end
2538    set(handles.RootFile_1,'String',RootFile_1);
2539else
2540    set(handles.ListPairMode,'Visible','on')
2541    set(handles.RootFile_1,'Visible','Off');
2542    set(handles.sub_txt,'Visible','off')
2543    set(handles.RootFile_1,'String',[]);
2544    mode_store=get(handles.ListCompareMode,'UserData');
2545    set(handles.ListPairMode,'Value',1)
2546    set(handles.ListPairMode,'String',mode_store)
2547    set(handles.CheckStereo,'Value',0)
2548    set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2549end
2550% if strcmp(option,'stereo PIV') && get(handles.CheckPatch1,'Value')
2551%     set(handles.CheckStereo,'Visible','on')
2552% else
2553%     set(handles.CheckStereo,'Visible','off')
2554% end
2555% if strcmp(option,'stereo PIV') && get(handles.CheckPatch2,'Value')
2556%     set(handles.CheckStereo,'Visible','on')
2557% else
2558%     set(handles.CheckStereo,'Visible','off')
2559% end
2560ListPairMode_Callback(hObject, eventdata, handles)
2561
2562
2563%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2564% Callbacks in the uipanel Pair Indices
2565%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2566%------------------------------------------------------------------------
2567% --- Executes on button press in ListPairMode.
2568function ListPairMode_Callback(hObject, eventdata, handles)
2569%------------------------------------------------------------------------
2570compare_list=get(handles.ListCompareMode,'String');
2571val=get(handles.ListCompareMode,'Value');
2572compare=compare_list{val};
2573if strcmp(compare,'displacement')||strcmp(compare,'shift')
2574    mode='displacement';
2575else
2576    mode_list=get(handles.ListPairMode,'String');
2577    if ischar(mode_list)
2578        mode_list={mode_list};
2579    end
2580    mode_value=get(handles.ListPairMode,'Value');
2581    mode=mode_list{mode_value};
2582end
2583displ_num=[];%default
2584ref_i=str2double(get(handles.ref_i,'String'));
2585% last_i=str2num(get(handles.last_i,'String'));
2586time=get(handles.ImaDoc,'UserData'); %get the set of times
2587TimeUnit=get(handles.TimeUnit,'String');
2588checkframe=strcmp(TimeUnit,'frame');
2589siztime=size(time);
2590nbfield=siztime(1)-1;
2591nbfield2=siztime(2)-1;
2592indchosen=1;  %%first pair selected by default
2593%displ_num used to define the indices of the civ pairs
2594% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
2595% are relative to the reference indices ref_i and ref_j respectively.
2596if isequal(mode,'pair j1-j2')%| isequal(mode,'st_pair j1-j2')
2597    dt=1;
2598    displ='';
2599    index=0;
2600    numlist_a=[];
2601    numlist_B=[];
2602    %get all the time intervals in bursts
2603    displ_dt=1;%default
2604    nbfield2=min(nbfield2,10);%limitate the number of pairs to 10x10
2605    for numod_a=1:nbfield2-1 %nbfield2 always >=2 for 'pair j1-j2' mode
2606        for numod_b=(numod_a+1):nbfield2
2607            index=index+1;
2608            numlist_a(index)=numod_a;
2609            numlist_b(index)=numod_b;
2610            if size(time,2)>1 && ~checkframe
2611                dt(numod_a,numod_b)=time(ref_i+1,numod_b+1)-time(ref_i+1,numod_a+1);%first time interval dt
2612                displ_dt(index)=dt(numod_a,numod_b);
2613            else
2614                displ_dt(index)=1;
2615            end
2616        end
2617    end
2618    [dtsort,indsort]=sort(displ_dt);
2619    if ~isempty(numlist_a)
2620        displ_num(1,:)=numlist_a(indsort);
2621        displ_num(2,:)=numlist_b(indsort);
2622    end
2623    displ_num(3,:)=0;
2624    displ_num(4,:)=0;
2625    enable_j(handles, 'off')
2626elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)')
2627    index=1:200;
2628    displ_num(1,index)=-floor(index/2);
2629    displ_num(2,index)=ceil(index/2);
2630    displ_num(3:4,index)=zeros(2,200);
2631    enable_j(handles, 'on')
2632elseif isequal(mode,'series(Di)') %| isequal(mode,'st_series(Di)')
2633    index=1:200;
2634    displ_num(1:2,index)=zeros(2,200);
2635    displ_num(3,index)=-floor(index/2);
2636    displ_num(4,index)=ceil(index/2);
2637    enable_i(handles, 'on')
2638    if nbfield2 > 1
2639        enable_j(handles, 'on')
2640    else
2641        enable_j(handles, 'off')
2642    end
2643elseif isequal(mode,'displacement')%the pairs have the same indices
2644    displ_num(1,1)=0;
2645    displ_num(2,1)=0;
2646    displ_num(3,1)=0;
2647    displ_num(4,1)=0;
2648    if nbfield > 1 || nbfield==0
2649        enable_i(handles, 'on')
2650    else
2651        enable_j(handles, 'off')
2652    end
2653    if nbfield2 > 1
2654        enable_j(handles, 'on')
2655    else
2656        enable_j(handles, 'off')
2657    end
2658end
2659set(handles.ListPairCiv1,'UserData',displ_num);
2660errormsg=find_netcpair_civ( handles,1);
2661    if ~isempty(errormsg)
2662    msgbox_uvmat('ERROR',errormsg)
2663    end
2664% find_netcpair_civ2(handles)
2665
2666function enable_i(handles, state)
2667set(handles.itext,'Visible',state)
2668set(handles.first_i,'Visible',state)
2669set(handles.last_i,'Visible',state)
2670set(handles.incr_i,'Visible',state)
2671set(handles.nb_field,'Visible',state)
2672set(handles.ref_i,'Visible',state)
2673
2674function enable_j(handles, state)
2675set(handles.jtext,'Visible',state)
2676set(handles.first_j,'Visible',state)
2677set(handles.last_j,'Visible',state)
2678set(handles.incr_j,'Visible',state)
2679set(handles.nb_field2,'Visible',state)
2680set(handles.ref_j,'Visible',state)
2681
2682
2683%------------------------------------------------------------------------
2684% --- Executes on selection change in ListPairCiv1.
2685function ListPairCiv1_Callback(hObject, eventdata, handles)
2686%------------------------------------------------------------------------
2687%reproduce by default the chosen pair in the checkciv2 menu
2688list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
2689index_pair=get(handles.ListPairCiv1,'Value');
2690displ_num=get(handles.ListPairCiv1,'UserData');
2691% num_a=displ_num(1,index_pair);
2692% num_b=displ_num(2,index_pair);
2693list_pair2=get(handles.ListPairCiv2,'String');%get the menu of image pairs
2694if index_pair<=length(list_pair2)
2695    set(handles.ListPairCiv2,'Value',index_pair);
2696end
2697
2698%update first_i and last_i according to the chosen image pairs
2699mode_list=get(handles.ListPairMode,'String');
2700mode_value=get(handles.ListPairMode,'Value');
2701mode=mode_list{mode_value};
2702if isequal(mode,'series(Di)')
2703    first_i=str2double(get(handles.first_i,'String'));
2704    last_i=str2double(get(handles.last_i,'String'));
2705    incr_i=str2double(get(handles.incr_i,'String'));
2706    num1=first_i:incr_i:last_i;
2707    lastfield=str2double(get(handles.nb_field,'String'));
2708    if ~isnan(lastfield)
2709        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2710            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2711        num1=num1(test_find);
2712    end
2713    set(handles.first_i,'String',num2str(num1(1)));
2714    set(handles.last_i,'String',num2str(num1(end)));
2715elseif isequal(mode,'series(Dj)')
2716    first_j=str2double(get(handles.first_j,'String'));
2717    last_j=str2double(get(handles.last_j,'String'));
2718    incr_j=str2double(get(handles.incr_j,'String'));
2719    num_j=first_j:incr_j:last_j;
2720    lastfield2=str2double(get(handles.nb_field2,'String'));
2721    if ~isnan(lastfield2)
2722        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2723            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2724        num1=num_j(test_find);
2725    end
2726    set(handles.first_j,'String',num2str(num1(1)));
2727    set(handles.last_j,'String',num2str(num1(end)));
2728end
2729
2730%------------------------------------------------------------------------
2731% --- Executes on selection change in ListPairCiv2.
2732function ListPairCiv2_Callback(hObject, eventdata, handles)
2733%------------------------------------------------------------------------
2734index_pair=get(handles.ListPairCiv2,'Value');%get the selected position index in the menu
2735
2736%update first_i and last_i according to the chosen image pairs
2737mode_list=get(handles.ListPairMode,'String');
2738mode_value=get(handles.ListPairMode,'Value');
2739mode=mode_list{mode_value};
2740if isequal(mode,'series(Di)')
2741    first_i=str2double(get(handles.first_i,'String'));
2742    last_i=str2double(get(handles.last_i,'String'));
2743    incr_i=str2double(get(handles.incr_i,'String'));
2744    num1=first_i:incr_i:last_i;
2745    lastfield=str2double(get(handles.nb_field,'String'));
2746    if ~isnan(lastfield)
2747        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2748            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2749        num1=num1(test_find);
2750    end
2751    set(handles.first_i,'String',num2str(num1(1)));
2752    set(handles.last_i,'String',num2str(num1(end)));
2753elseif isequal(mode,'series(Dj)')
2754    first_j=str2double(get(handles.first_j,'String'));
2755    last_j=str2double(get(handles.last_j,'String'));
2756    incr_j=str2double(get(handles.incr_j,'String'));
2757    num_j=first_j:incr_j:last_j;
2758    lastfield2=str2double(get(handles.nb_field2,'String'));
2759    if ~isnan(lastfield2)
2760        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2761            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2762        num1=num_j(test_find);
2763    end
2764    set(handles.first_j,'String',num2str(num1(1)));
2765    set(handles.last_j,'String',num2str(num1(end)));
2766end
2767
2768%------------------------------------------------------------------------
2769function ref_i_Callback(hObject, eventdata, handles)
2770%------------------------------------------------------------------------
2771mode_list=get(handles.ListPairMode,'String');
2772mode_value=get(handles.ListPairMode,'Value');
2773mode=mode_list{mode_value};
2774errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2775if isequal(mode,'series(Di)') || ...% we do patch2 only
2776        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2777    errormsg=find_netcpair_civ( handles,2);
2778end
2779    if ~isempty(errormsg)
2780    msgbox_uvmat('ERROR',errormsg)
2781    end
2782
2783%------------------------------------------------------------------------
2784function ref_j_Callback(hObject, eventdata, handles)
2785%------------------------------------------------------------------------
2786mode_list=get(handles.ListPairMode,'String');
2787mode_value=get(handles.ListPairMode,'Value');
2788mode=mode_list{mode_value};
2789if isequal(get(handles.CheckCiv1,'Value'),0)|| isequal(mode,'series(Dj)')
2790    errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2791end
2792if isequal(mode,'series(Dj)') || ...
2793        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2794    errormsg=find_netcpair_civ(handles,2);
2795end
2796    if ~isempty(errormsg)
2797    msgbox_uvmat('ERROR',errormsg)
2798    end
2799
2800%------------------------------------------------------------------------
2801% determine the menu for checkciv1 pairs depending on existing netcdf file at the middle of
2802% the field series set by first_i, incr, last_i
2803% index=1: look for pairs for civ1
2804% index=2: look for pairs for civ2
2805function errormsg=find_netcpair_civ(handles,index)
2806%------------------------------------------------------------------------
2807set(gcf,'Pointer','watch')% set the mouse pointer to 'watch' (clock)
2808
2809%% initialisation
2810errormsg='';
2811browse=get(handles.RootPath,'UserData');
2812compare_list=get(handles.ListCompareMode,'String');
2813val=get(handles.ListCompareMode,'Value');
2814compare=compare_list{val};
2815if strcmp(compare,'displacement')||strcmp(compare,'shift')
2816    mode='displacement';
2817else
2818    mode_list=get(handles.ListPairMode,'String');
2819    mode_value=get(handles.ListPairMode,'Value');
2820    if isempty(mode_list)
2821        return
2822    end
2823    mode=mode_list{mode_value};
2824end
2825nom_type_ima=get(handles.NomType,'String');
2826
2827%% determine nom_type_nc, nomenclature type of the .nc files:
2828[nom_type_nc]=nomtype2pair(nom_type_ima,mode);
2829
2830%% reads .nc subdirectoy and image numbers from the interface
2831subdir_civ1=get(handles.SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
2832subdir_civ2=get(handles.SubdirCiv2,'String');%subdirectory subdir_civ2 for the netcdf data
2833ref_i=str2double(get(handles.ref_i,'String'));
2834if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
2835    ref_j=0;
2836else
2837    ref_j=str2double(get(handles.ref_j,'String'));
2838    if isnan(ref_j)
2839        ref_j=1;
2840    end
2841end
2842time=get(handles.ImaDoc,'UserData');%get the set of times
2843TimeUnit=get(handles.TimeUnit,'String');
2844checkframe=strcmp(TimeUnit,'frame');
2845displ_num=get(handles.ListPairCiv1,'UserData');
2846
2847%% eliminate the first pairs inconsistent with the position
2848if isempty(displ_num)
2849    nbpair=0;
2850else
2851    nbpair=length(displ_num(1,:));%nbre of displayed pairs
2852    if  isequal(mode,'series(Di)')  %| isequal(mode,'st_series(Di)')
2853        nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
2854    elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
2855        nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
2856    end
2857end
2858nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
2859
2860%% case with no Civ1 operation, netcdf files need to exist for reading
2861displ_pair={''};
2862select=ones(size(1:nbpair));%flag for displayed pairs =1 for display
2863testpair=0;
2864RootPath=get(handles.RootPath,'String');
2865RootFile=get(handles.RootFile,'String');
2866if index==1 % case civ1
2867    if ~get(handles.CheckCiv1,'Value') %
2868        if ~exist(fullfile(RootPath,subdir_civ1),'dir')
2869            errormsg=['no civ1 file available: subdirectory ' subdir_civ1 ' does not exist'];
2870            set(handles.ListPairCiv1,'String',{});
2871            return
2872        end
2873        for ipair=1:nbpair
2874            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
2875                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
2876            select(ipair)=exist(filename,'file')==2;% put flag to 0 if the file does not exist
2877        end
2878        % case of no displayed pair
2879        if isequal(select,zeros(size(1:nbpair)))
2880            if isfield(browse,'incr_pair') && ~isequal(browse.incr_pair,[0 0])
2881                num_i1=ref_i-floor(browse.incr_pair(1)/2);
2882                num_i2=ref_i+ceil(browse.incr_pair(1)/2);
2883                num_j1=ref_j-floor(browse.incr_pair(2)/2);
2884                num_j2=ref_j+ceil(browse.incr_pair(2)/2);
2885                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
2886                select(1)=exist(filename,'file')==2;
2887                testpair=1;
2888            else
2889                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
2890                    errormsg=['no civ1 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ1];
2891                else
2892                    errormsg=['no civ1 file available for the selected reference indices (i,j)= ' num2str(ref_i) ', ' num2str(ref_j) ' and subdirectory ' subdir_civ1];
2893                end
2894                set(handles.ListPairCiv1,'String',{''});
2895                %COMPLETER CAS STEREO
2896                return
2897            end
2898        end
2899    end
2900else %case civ2 alone
2901    if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
2902        if ~exist(fullfile(RootPath,subdir_civ2),'dir')
2903            msgbox_uvmat('ERROR',['no civ2 file available: subdirectory ' subdir_civ2 ' does not exist'])
2904            set(handles.ListPairCiv2,'Value',1);
2905            set(handles.ListPairCiv2,'String',{''});
2906            return
2907        end
2908        for ipair=1:nbpair
2909            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
2910                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
2911            select(ipair)=exist(filename,'file')==2;
2912        end
2913        if  isequal(select,zeros(size(1:nbpair)))
2914            if isfield(browse,'incr_pair')
2915                num_i1=ref_i-floor(browse.incr_pair(1)/2);
2916                num_i2=ref_i+floor((browse.incr_pair(1)+1)/2);
2917                num_j1=ref_j-floor(browse.incr_pair(2)/2);
2918                num_j2=ref_j+floor((browse.incr_pair(2)+1)/2);
2919                filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
2920                select(1)=exist(filename,'file')==2;
2921            else
2922                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
2923                    errormsg=['no civ2 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ2];
2924                else
2925                    errormsg=['no civ2 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ2];
2926                end
2927                set(handles.ListPairCiv2,'Value',1);
2928                set(handles.ListPairCiv2,'String',{''});
2929                return
2930            end
2931        end
2932    end
2933end
2934
2935%% determine the menu display in .ListPairCiv1
2936% the menu depends on the mode defined in ListPairMode_callback through the array displ_num:
2937% displ_num(1,:)=indices j1
2938% displ_num(2,:)=indices j2
2939% displ_num(3,:)=indices i1
2940% displ_num(4,:)=indices i2
2941% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
2942% are relative to the reference indices ref_i and ref_j respectively.
2943if isequal(mode,'series(Di)')
2944    if testpair
2945        displ_pair{1}=['Di= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
2946    else
2947        for ipair=1:nbpair
2948            if select(ipair)
2949                displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
2950                %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
2951                 %   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
2952               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
2953                 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
2954                else
2955                    dt=1;
2956                end
2957                 displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
2958            else
2959                displ_pair{ipair}='...'; %pair not displayed in the menu
2960            end
2961        end
2962    end
2963elseif isequal(mode,'series(Dj)')
2964    if testpair
2965        displ_pair{1}=['Dj= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
2966    else
2967        for ipair=1:nbpair
2968            if select(ipair)
2969                displ_pair{ipair}=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
2970                if ~checkframe && size(time,1)>=ref_i+1+displ_num(4,ipair) && size(time,2)>=ref_j+1+displ_num(2,ipair)
2971                    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
2972                    displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
2973                end
2974            else
2975                displ_pair{ipair}='...'; %pair not displayed in the menu
2976            end
2977        end
2978    end
2979elseif isequal(mode,'pair j1-j2')%case of pairs
2980    for ipair=1:nbpair
2981        if select(ipair)
2982            if ~checkframe && size(time,2)>1
2983            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
2984            else % time set by default to i index
2985                dt=1;
2986            end
2987            displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair),nom_type_ima) '-' num2stra(displ_num(2,ipair),nom_type_ima) ...
2988                ' :dt= ' num2str(dt*1000)];
2989        else
2990            displ_pair{ipair}='...'; %pair not displayed in the menu
2991        end
2992    end
2993elseif isequal(mode,'displacement')
2994    displ_pair={'Di=Dj=0'};
2995end
2996if index==1
2997set(handles.ListPairCiv1,'String',displ_pair');
2998end
2999
3000%% determine the default selection in the pair menu
3001ichoice=find(select,1);% index of selected pair
3002if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3003initial=get(handles.ListPairCiv1,'Value');%initial choice of pair
3004if initial>nbpair || (numel(select)>=initial && ~isequal(select(initial),1))
3005    set(handles.ListPairCiv1,'Value',ichoice);% first valid pair proposed by default in the menu
3006end
3007initial=get(handles.ListPairCiv2,'Value');
3008if initial>length(displ_pair')%|~isequal(select(initial),1)
3009    if ichoice <= length(displ_pair')
3010        set(handles.ListPairCiv2,'Value',ichoice);% same pair proposed by default for civ2
3011    else
3012        set(handles.ListPairCiv2,'Value',1);% same pair proposed by default for civ2
3013    end
3014end
3015set(handles.ListPairCiv2,'String',displ_pair');
3016set(gcf,'Pointer','arrow')
3017
3018
3019   
3020% %------------------------------------------------------------------------   
3021% % call 'view_field.fig' to display the  field selected in the list of 'status'
3022% function open_view_field(hObject, eventdata)
3023% %------------------------------------------------------------------------
3024% list=get(hObject,'String');
3025% index=get(hObject,'Value');
3026% rootroot=get(hObject,'UserData');
3027% filename=list{index};
3028% ind_dot=strfind(filename,'...');
3029% filename=filename(1:ind_dot-1);
3030% filename=fullfile(rootroot,filename);
3031% delete(get(hObject,'parent'))%delete the display figure to stop the check process
3032% if exist(filename,'file')%visualise the vel field if it exists
3033%     uvmat(filename)
3034%     set(gcbo,'Value',1)
3035% end
3036
3037
3038%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3039% Callbacks in the uipanel Reference Indices
3040%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3041%------------------------------------------------------------------------
3042function first_i_Callback(hObject, eventdata, handles)
3043%------------------------------------------------------------------------
3044first_i=str2double(get(handles.first_i,'String'));
3045set(handles.ref_i,'String', num2str(first_i))% reference index for pair dt = first index
3046ref_i_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3047
3048%------------------------------------------------------------------------
3049function first_j_Callback(hObject, eventdata, handles)
3050%------------------------------------------------------------------------
3051first_j=str2num(get(handles.first_j,'String'));
3052set(handles.ref_j,'String', num2str(first_j))% reference index for pair dt = first index
3053ref_j_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3054
3055%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3056% Callbacks in the uipanel Civ1
3057%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3058%------------------------------------------------------------------------
3059% --- Executes on button press in SearchRange: determine the search range num_SearchBoxSize_1,num_SearchBoxSize_2
3060function SearchRange_Callback(hObject, eventdata, handles)
3061%------------------------------------------------------------------------
3062%determine pair numbers
3063if strcmp(get(handles.num_UMin,'Visible'),'off')
3064    set(handles.u_title,'Visible','on')
3065    set(handles.v_title,'Visible','on')
3066    set(handles.num_UMin,'Visible','on')
3067    set(handles.num_UMax,'Visible','on')
3068    set(handles.num_VMin,'Visible','on')
3069    set(handles.num_VMax,'Visible','on')
3070    set(handles.CoordUnit,'Visible','on')
3071    set(handles.TimeUnit,'Visible','on')
3072    set(handles.slash_title,'Visible','on')
3073    set(handles.min_title,'Visible','on')
3074    set(handles.max_title,'Visible','on')
3075    set(handles.unit_title,'Visible','on')
3076else
3077    get_search_range(hObject, eventdata, handles)
3078end
3079
3080%------------------------------------------------------------------------
3081% ---  determine the search range num_SearchBoxSize_1,num_SearchBoxSize_2 and shift
3082function get_search_range(hObject, eventdata, handles)
3083%------------------------------------------------------------------------
3084param_civ1=read_GUI(handles.Civ1);
3085umin=param_civ1.UMin;
3086umax=param_civ1.UMax;
3087vmin=param_civ1.VMin;
3088vmax=param_civ1.VMax;
3089%switch min_title and max_title in case of error
3090if umax<=umin
3091    umin_old=umin;
3092    umin=umax;
3093    umax=umin_old;
3094    set(handles.num_UMin,'String', num2str(umin))
3095    set(handles.num_UMax,'String', num2str(umax))
3096end
3097if vmax<=vmin
3098    vmin_old=vmin;
3099    vmin=vmax;
3100    vmax=vmin_old;
3101    set(handles.num_VMin,'String', num2str(vmin))
3102    set(handles.num_VMax,'String', num2str(vmax))
3103end   
3104if ~(isempty(umin)||isempty(umax)||isempty(vmin)||isempty(vmax))
3105    list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
3106    index=get(handles.ListPairCiv1,'Value');
3107    pair_string=list_pair{index};
3108    time=get(handles.ImaDoc,'UserData'); %get the set of times
3109    pxcm=get(handles.SearchRange,'UserData');
3110    mode_list=get(handles.ListPairMode,'String');
3111    mode_value=get(handles.ListPairMode,'Value');
3112    mode=mode_list{mode_value};     
3113    if isequal (mode, 'series(Di)' )
3114        ref_i=str2double(get(handles.ref_i,'String'));
3115        num1=ref_i-floor(index/2);%  first image numbers
3116        num2=ref_i+ceil(index/2);
3117        num_a=1;
3118        num_b=1;
3119    elseif isequal (mode, 'series(Dj)')
3120        num1=1;
3121        num2=1;
3122        ref_j=str2double(get(handles.ref_j,'String'));
3123        num_a=ref_j-floor(index/2);%  first image numbers
3124        num_b=ref_j+ceil(index/2);
3125    elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)     
3126        ref_i=str2double(get(handles.ref_i,'String'));
3127        num1=ref_i;
3128        num2=ref_i;
3129                r=regexp(pair_string,'(?<mode>(Di=)|(Dj=)) -*(?<num1>\d+)\|(?<num2>\d+)','names');
3130        if isempty(r)
3131            r=regexp(pair_string,'(?<num1>\d+)(?<mode>-)(?<num2>\d+)','names');
3132        end 
3133        num_a=str2num(r.num1);
3134        num_b=str2num(r.num2);
3135    end
3136    dt=time(num2+1,num_b+1)-time(num1+1,num_a+1);
3137    ibx=str2double(get(handles.num_CorrBoxSize_1,'String'));
3138    iby=str2double(get(handles.num_CorrBoxSize_2,'String'));
3139    umin=dt*pxcm*umin;
3140    umax=dt*pxcm*umax;
3141    vmin=dt*pxcm*vmin;
3142    vmax=dt*pxcm*vmax;
3143    shiftx=round((umin+umax)/2);
3144    shifty=round((vmin+vmax)/2);
3145    isx=(umax+2-shiftx)*2+param_civ1.Bx;
3146    isx=2*ceil(isx/2)+1;
3147    isy=(vmax+2-shifty)*2+param_civ1.Bx;
3148    isy=2*ceil(isy/2)+1;
3149    set(handles.num_SearchBoxShift_1,'String',num2str(shiftx));
3150    set(handles.num_SearchBoxShift_2,'String',num2str(shifty));
3151    set(handles.num_SearchBoxSize_1,'String',num2str(isx));
3152    set(handles.num_SearchBoxSize_2,'String',num2str(isy));
3153end
3154
3155%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3156% Callbacks in the uipanel Fix1
3157%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3158%------------------------------------------------------------------------
3159% --- Executes on button press in CheckMask.
3160function get_mask_fix1_Callback(hObject, eventdata, handles)
3161%------------------------------------------------------------------------
3162maskval=get(handles.CheckMask,'Value');
3163if isequal(maskval,0)
3164    set(handles.Mask,'String','')
3165else
3166    mask_displ='no mask'; %default
3167    filebase=get(handles.RootPath,'String');
3168    [nbslice, flag_mask]=get_mask(filebase,handles);
3169    if isequal(flag_mask,1)
3170        mask_displ=[num2str(nbslice) 'mask'];
3171    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3172        filebase_a=get(handles.RootFile_1,'String');
3173        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3174        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3175            mask_displ='no mask';
3176        end
3177    end
3178    if isequal(mask_displ,'no mask')
3179        [FileName, PathName, filterindex] = uigetfile( ...
3180            {'*.png', ' (*.png)';
3181            '*.png',  '.png files '; ...
3182            '*.*', 'All Files (*.*)'}, ...
3183            'Pick a mask file *.png',filebase);
3184        mask_displ=fullfile(PathName,FileName);
3185        if ~exist(mask_displ,'file')
3186            mask_displ='no mask';
3187        end
3188    end
3189    if isequal(mask_displ,'no mask')
3190        set(handles.CheckMask,'Value',0)
3191        set(handles.CheckMask,'Value',0)
3192        set(handles.CheckMask,'Value',0)
3193    else
3194        %set(handles.CheckMask,'Value',1)
3195        set(handles.CheckMask,'Value',1)
3196    end
3197    set(handles.Mask,'String',mask_displ)
3198    set(handles.Mask,'String',mask_displ)
3199    set(handles.Mask,'String',mask_displ)
3200end
3201
3202%------------------------------------------------------------------------
3203% --- Executes on button press in CheckMask: select box for mask option
3204function get_mask_civ2_Callback(hObject, eventdata, handles)
3205%------------------------------------------------------------------------
3206maskval=get(handles.CheckMask,'Value');
3207if isequal(maskval,0)
3208    set(handles.Mask,'String','')
3209else
3210    mask_displ='no mask'; %default
3211    filebase=get(handles.RootPath,'String');
3212    [nbslice, flag_mask]=get_mask(filebase,handles);
3213    if isequal(flag_mask,1)
3214        mask_displ=[num2str(nbslice) 'mask'];
3215    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3216        filebase_a=get(handles.RootFile_1,'String');
3217        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3218        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3219            mask_displ='no mask';
3220        end
3221    end
3222    if isequal(mask_displ,'no mask')
3223        [FileName, PathName, filterindex] = uigetfile( ...
3224            {'*.png', ' (*.png)';
3225            '*.png',  '.png files '; ...
3226            '*.*', 'All Files (*.*)'}, ...
3227            'Pick a mask file *.png',filebase);
3228        mask_displ=fullfile(PathName,FileName);
3229        if ~exist(mask_displ,'file')
3230            mask_displ='no mask';
3231        end
3232    end
3233    if isequal(mask_displ,'no mask')
3234        set(handles.CheckMask,'Value',0)
3235        set(handles.CheckMask,'Value',0)
3236    else
3237        set(handles.CheckMask,'Value',1)
3238    end
3239    set(handles.Mask,'String',mask_displ)
3240    set(handles.Mask,'String',mask_displ)
3241end
3242
3243%------------------------------------------------------------------------
3244% --- Executes on button press in CheckMask.
3245function get_mask_fix2_Callback(hObject, eventdata, handles)
3246%------------------------------------------------------------------------
3247maskval=get(handles.CheckMask,'Value');
3248if isequal(maskval,0)
3249    set(handles.Mask,'String','')
3250else
3251    mask_displ='no mask'; %default
3252    filebase=get(handles.RootPath,'String');
3253    [nbslice, flag_mask]=get_mask(filebase,handles);
3254    if isequal(flag_mask,1)
3255        mask_displ=[num2str(nbslice) 'mask'];
3256    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3257        filebase_a=get(handles.RootFile_1,'String');
3258        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3259        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3260            mask_displ='no mask';
3261        end
3262    end
3263    if isequal(mask_displ,'no mask')
3264        [FileName, PathName, filterindex] = uigetfile( ...
3265            {'*.png', ' (*.png)';
3266            '*.png',  '.png files '; ...
3267            '*.*', 'All Files (*.*)'}, ...
3268            'Pick a mask file *.png',filebase);
3269        mask_displ=fullfile(PathName,FileName);
3270        if ~exist(mask_displ,'file')
3271            mask_displ='no mask';
3272        end
3273    end
3274    if isequal(mask_displ,'no mask')
3275        set(handles.CheckMask,'Value',0)
3276    end
3277    set(handles.Mask,'String',mask_displ)
3278end
3279
3280%------------------------------------------------------------------------
3281% --- function called to look for mask files
3282function [nbslice, flag_mask]=get_mask(filebase,handles)
3283%------------------------------------------------------------------------
3284%detect mask files, images with appropriate file base
3285%[filebase '_' xx 'mask'], xx=nbslice
3286%flag_mask=1 indicates detection
3287
3288flag_mask=0;%default
3289nbslice=1;
3290
3291% subdir=get(handles.SubdirCiv1,'String');
3292[Path,Name]=fileparts(filebase);
3293if ~isdir(Path)
3294    msgbox_uvmat('ERROR','no path for input files')
3295    return
3296end
3297% currentdir=pwd;
3298% cd(Path);%move in the dir of the root name filebase
3299maskfiles=dir(fullfile(Path,[Name '_*mask_*.png']));%look for mask files
3300% cd(currentdir);%come back to the current working directory
3301if ~isempty(maskfiles)
3302    %     msgbox_uvmat('ERROR','no mask available, to create it use Tools/Make mask in the upper menu bar of uvmat')
3303    % else
3304    flag_mask=1;
3305    maskname=maskfiles(1).name;% take the first mask file in the list
3306    [Path2,Name,ext]=fileparts(maskname);
3307    Namedouble=double(Name);
3308    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3309    ind_mask=findstr('mask',Name);
3310    i=ind_mask-1;
3311    while val(i)==0 && i>0
3312        i=i-1;
3313    end
3314    nbslice=str2double(Name(i+1:ind_mask-1));
3315    if ~isnan(nbslice) && Name(i)=='_'
3316        flag_mask=1;
3317    else
3318        msgbox_uvmat('ERROR',['bad mask file ' Name ext ' found in ' Path2])
3319        return
3320        nbslice=1;
3321    end
3322end
3323
3324%------------------------------------------------------------------------
3325% --- function called to look for grid files
3326function [nbslice, flag_mask]=get_grid(filebase,handles)
3327%------------------------------------------------------------------------
3328flag_mask=0;%default
3329nbslice=1;
3330[Path,Name]=fileparts(filebase);
3331currentdir=pwd;
3332cd(Path);%move in the dir of the root name filebase
3333maskfiles=dir([Name '_*grid_*.grid']);%look for mask files
3334cd(currentdir);%come back to the current working directory
3335if ~isempty(maskfiles)
3336    flag_mask=1;
3337    maskname=maskfiles(1).name;% take the first mask file in the list
3338    [Path2,Name,ext]=fileparts(maskname);
3339    Namedouble=double(Name);
3340    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3341    ind_mask=findstr('grid',Name);
3342    i=ind_mask-1;
3343    while val(i)==0 && i>0
3344        i=i-1;
3345    end
3346    nbslice=str2double(Name(i+1:ind_mask-1));
3347    if ~isnan(nbslice) && Name(i)=='_'
3348        flag_mask=1;
3349    else
3350        msgbox_uvmat('ERROR',['bad grid file ' Name ext ' found in ' Path2])
3351        return
3352        nbslice=1;
3353    end
3354end
3355
3356%------------------------------------------------------------------------
3357% --- transform numbers to letters
3358function str=num2stra(num,nom_type)
3359%------------------------------------------------------------------------
3360if isempty(nom_type)
3361    str='';
3362elseif strcmp(nom_type(end),'a')
3363    str=char(96+num);
3364elseif strcmp(nom_type(end),'A')
3365    str=char(96+num);
3366elseif isempty(nom_type(2:end))%a single index
3367    str='';
3368else
3369    str=num2str(num);
3370end
3371
3372% %------------------------------------------------------------------------
3373% % --- Executes on button press in ListSubdirCiv1.
3374% function ListSubdirCiv1_Callback(hObject, eventdata, handles)
3375% %------------------------------------------------------------------------
3376% list_subdir_civ1=get(handles.ListSubdirCiv1,'String');
3377% val=get(handles.ListSubdirCiv1,'Value');
3378% SubDir=list_subdir_civ1{val};
3379% if strcmp(SubDir,'new...')
3380%     if get(handles.CheckCiv1,'Value')
3381%         SubDir='CIV'; %default subdirectory
3382%     else
3383%         msgbox_uvmat('ERROR','select CheckCiv1 to perform a new Civ operation')
3384%         return
3385%     end   
3386% end
3387% set(handles.SubdirCiv1,'String',SubDir);
3388% errormsg=find_netcpair_civ(handles,1);
3389% if ~isempty(errormsg)
3390%     msgbox_uvmat('ERROR',errormsg)
3391% end
3392%     
3393%------------------------------------------------------------------------
3394% % --- Executes on button press in ListSubdirCiv2.
3395% function ListSubdirCiv2_Callback(hObject, eventdata, handles)
3396% %------------------------------------------------------------------------
3397% list_subdir_civ2=get(handles.ListSubdirCiv2,'String');
3398% val=get(handles.ListSubdirCiv2,'Value');
3399% SubDir=list_subdir_civ2{val};
3400% if strcmp(SubDir,'new...')
3401%     if get(handles.CheckCiv2,'Value')
3402%         SubDir='CIV'; %default subdirectory
3403%     else
3404%         msgbox_uvmat('ERROR','select CheckCiv2 to perform a new Civ operation')
3405%         return
3406%     end
3407% end
3408% set(handles.SubdirCiv2,'String',SubDir);
3409
3410%------------------------------------------------------------------------
3411% --- Executes on button press in CheckGrid.
3412function CheckGrid_Callback(hObject, eventdata, handles)
3413%------------------------------------------------------------------------
3414value=get(hObject,'Value');
3415hparent=get(hObject,'parent');
3416hchildren=get(hparent,'children');
3417handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3418handle_dx=findobj(hchildren,'tag','num_Dx');
3419handle_dy=findobj(hchildren,'tag','num_Dy');
3420handle_title_dx=findobj(hchildren,'tag','title_Dx');
3421handle_title_dy=findobj(hchildren,'tag','title_Dy');
3422testgrid=0;
3423filegrid='';
3424if value
3425    filebase=get(handles.RootPath,'String');
3426    [nbslice, flag_grid]=get_grid(filebase,handles);% look for a grid with appropriate name
3427    if isequal(flag_grid,1)
3428        filegrid=[num2str(nbslice) 'grid'];
3429        testgrid=1;
3430    else % browse for a grid
3431        filegrid=get(hObject,'UserData');%look for previous grid name stored as UserData
3432        if exist(filegrid,'file')
3433            filebase=filegrid;
3434        end
3435        [FileName, PathName, filterindex] = uigetfile( ...
3436            {'*.grid', ' (*.grid)';
3437            '*.grid',  '.grid files '; ...
3438            '*.*', 'All Files (*.*)'}, ...
3439            'Pick a file',filebase);
3440        filegrid=fullfile(PathName,FileName);
3441        set(hObject,'UserData',filegrid);%store for future use
3442        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filegrid,'file'))
3443            testgrid=1;
3444        end
3445    end
3446end
3447if testgrid
3448    set(handle_dx,'Visible','off');
3449    set(handle_dy,'Visible','off');
3450    set(handle_title_dy,'Visible','off');
3451    set(handle_title_dx,'Visible','off');
3452    set(handle_txtbox,'Visible','on')
3453    set(handle_txtbox,'String',filegrid)
3454else
3455    set(hObject,'Value',0);
3456    set(handle_dx,'Visible','on');
3457    set(handle_dy,'Visible','on');
3458    set(handle_title_dy,'Visible','on');
3459    set(handle_title_dx,'Visible','on');
3460    set(handle_txtbox,'Visible','off')
3461end
3462
3463%% if hObject is on the checkciv1 frame, duplicate action for checkciv2 frame
3464PanelName=get(hparent,'tag');
3465if strcmp(PanelName,'Civ1')
3466    hchildren=get(handles.Civ2,'children');
3467    handle_checkbox=findobj(hchildren,'tag','CheckGrid');
3468    handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3469    handle_dx=findobj(hchildren,'tag','num_Dx');
3470    handle_dy=findobj(hchildren,'tag','num_Dy');
3471    handle_title_dx=findobj(hchildren,'tag','title_Dx');
3472    handle_title_dy=findobj(hchildren,'tag','title_Dy');
3473    set(handle_checkbox,'UserData',filegrid);%store for future use
3474    if testgrid
3475        set(handle_checkbox,'Value',1);
3476        set(handle_dx,'Visible','off');
3477        set(handle_dy,'Visible','off');
3478        set(handle_title_dx,'Visible','off');
3479        set(handle_title_dy,'Visible','off');
3480        set(handle_txtbox,'Visible','on')
3481        set(handle_txtbox,'String',filegrid)
3482%     else
3483%         set(handle_checkbox,'Value',0);
3484%         set(handles.CheckGrid,'Value',0);
3485%         set(handle_dx,'Visible','on');
3486%         set(handle_dy,'Visible','on');
3487%          set(handle_title_dx,'Visible','on');
3488%         set(handle_title_dy,'Visible','on');
3489%         set(handle_txtbox,'Visible','off')
3490    end
3491end
3492
3493%------------------------------------------------------------------------
3494% --- Executes on button press in CheckMask: common to all panels (civ1, Civ2..)
3495function CheckMask_Callback(hObject, eventdata, handles)
3496%------------------------------------------------------------------------
3497value=get(hObject,'Value');
3498hparent=get(hObject,'parent');
3499parent_tag=get(hparent,'Tag');
3500hchildren=get(hparent,'children');
3501handle_txtbox=findobj(hchildren,'tag','Mask');% look for the mask name box in the same panel
3502testmask=0;
3503if value
3504    filebase=get(handles.RootPath,'String');
3505    [nbslice, flag_mask]=get_mask(filebase,handles);% look for a mask with appropriate name
3506    if isequal(flag_mask,1)
3507        filemask=[num2str(nbslice) 'mask'];
3508        testmask=1;
3509    else % browse for a mask
3510        filemask=get(hObject,'UserData');%look for previous mask name stored as UserData
3511        if exist(filemask,'file')
3512            filebase=filemask;
3513        end
3514        [FileName, PathName] = uigetfile( ...
3515            {'*.png', ' (*.png)';
3516            '*.png',  '.png files '; ...
3517            '*.*', 'All Files (*.*)'}, ...
3518            'Pick a mask file *.png',filebase);
3519        filemask=fullfile(PathName,FileName);
3520        set(hObject,'UserData',filemask);%store for future use
3521        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filemask,'file'))
3522            testmask=1;
3523        end
3524    end
3525end
3526if testmask
3527    if strcmp(parent_tag,'Civ1')
3528        set(handles.Mask,'Visible','on')
3529        set(handles.Mask,'String',filemask)
3530    set(handles.CheckMask,'Value',1)
3531    end
3532%     switch parent_tag
3533% %         case 'Fix1'
3534% %             stage=2;
3535%         case 'Civ2'
3536%              stage=3;
3537% %         case 'Fix2'
3538% %             stage=4;
3539%     end
3540%     set(handles.Mask(stage:end),'Visible','on')
3541%     set(handles.Mask(stage:end),'String',filemask)
3542%     set(handles.CheckMask(stage:end),'Value',1)
3543else
3544    set(hObject,'Value',0);
3545    set(handle_txtbox,'Visible','off')
3546end
3547
3548
3549% --- Executes on button press in get_gridpatch1.
3550function get_gridpatch1_Callback(hObject, eventdata, handles)
3551filebase=get(handles.RootPath,'String');
3552[FileName, PathName, filterindex] = uigetfile( ...
3553    {'*.grid', ' (*.grid)';
3554    '*.grid',  '.grid files '; ...
3555    '*.*', 'All Files (*.*)'}, ...
3556    'Pick a file',filebase);
3557filegrid=fullfile(PathName,FileName);
3558set(handles.grid_patch1,'string',filegrid);
3559
3560
3561%------------------------------------------------------------------------
3562% --- Executes on button press in get_gridpatch2.
3563function get_gridpatch2_Callback(hObject, eventdata, handles)
3564%------------------------------------------------------------------------
3565
3566
3567%------------------------------------------------------------------------
3568% --- STEREO Interp
3569function cmd=RUN_STINTERP(stinterpBin,filename_A_nc,filename_B_nc,filename_nc,nx_patch,ny_patch,rho_patch,subdomain_patch,thresh_value,xmlA,xmlB)
3570%------------------------------------------------------------------------
3571namelog=[filename_nc(1:end-3) '_stinterp.log'];
3572cmd=[stinterpBin ' -f1 ' filename_A_nc  ' -f2 ' filename_B_nc ' -f  ' filename_nc ...
3573    ' -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
3574
3575%------------------------------------------------------------------------
3576%--read images and convert them to the uint16 format used for PIV
3577function A=read_image(filename,type_ima,num,movieobject)
3578%------------------------------------------------------------------------
3579%num is the view number needed for an avi movie
3580switch type_ima
3581    case 'movie'
3582        A=read(movieobject,num);
3583    case 'avi'
3584        mov=aviread(filename,num);
3585        A=frame2im(mov(1));
3586    case 'multimage'
3587        A=imread(filename,num);
3588    case 'image'
3589        A=imread(filename);
3590end
3591siz=size(A);
3592if length(siz)==3;%color images
3593    A=sum(double(A),3);
3594    A=uint16(A);
3595end
3596
3597
3598%------------------------------------------------------------------------
3599% --- Executes on button press in get_ref_fix1.
3600function get_ref_fix1_Callback(hObject, eventdata, handles)
3601%------------------------------------------------------------------------
3602filebase=get(handles.RootPath,'String');
3603[FileName, PathName, filterindex] = uigetfile( ...
3604    {'*.nc', ' (*.nc)';
3605    '*.nc',  'netcdf files '; ...
3606    '*.*', 'All Files (*.*)'}, ...
3607    'Pick a file',filebase);
3608
3609fileinput=[PathName FileName];
3610sizf=size(fileinput);
3611if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3612%[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3613[Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3614ref.filebase=fullfile(Path,File);
3615% ref.num_a=stra2num(str_a);
3616% ref.num_b=stra2num(str_b);
3617% ref.num1=str2double(field_count);
3618% ref.num2=str2double(str2);
3619browse=[];%initialisation
3620if ~isequal(ref.ext,'.nc')
3621    msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3622    return
3623end
3624set(handles.ref_fix1,'String',[fullfile(ref.subdir,File) '....nc']);
3625set(handles.ref_fix1,'UserData',ref)
3626menu_field{1}='civ1';
3627Data=nc2struct(fileinput,[]);
3628if isfield(Data,'patch') && isequal(Data.patch,1)
3629    menu_field{2}='filter1';
3630end
3631if isfield(Data,'civ2') && isequal(Data.civ2,1)
3632    menu_field{3}='civ2';
3633end
3634if isfield(Data,'patch2') && isequal(Data.patch2,1)
3635    menu_field{4}='filter2';
3636end
3637set(handles.field_ref1,'String',menu_field);
3638set(handles.field_ref1,'Value',length(menu_field));
3639set(handles.num_MinVel,'Value',2);
3640set(handles.num_MinVel,'String','1');%default threshold
3641set(handles.ref_fix1,'Enable','on')
3642
3643%------------------------------------------------------------------------
3644% --- Executes on button press in get_ref_fix2.
3645function get_ref_fix2_Callback(hObject, eventdata, handles)
3646%------------------------------------------------------------------------
3647if isequal(get(handles.get_ref_fix2,'Value'),1)
3648    filebase=get(handles.RootPath,'String');
3649    [FileName, PathName, filterindex] = uigetfile( ...
3650        {'*.nc', ' (*.nc)';
3651        '*.nc',  'netcdf files '; ...
3652        '*.*', 'All Files (*.*)'}, ...
3653        'Pick a file',filebase);
3654    fileinput=[PathName FileName];
3655    sizf=size(fileinput);
3656    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3657    %[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3658    [Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3659    ref.filebase=fullfile(Path,File);
3660%     ref.num_a=stra2num(str_a);
3661%     ref.num_b=stra2num(str_b);
3662%     ref.num1=str2num(field_count);
3663%     ref.num2=str2num(str2);
3664    browse=[];%initialisation
3665    if ~isequal(ref.ext,'.nc')
3666        msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3667        return
3668    end
3669    set(handles.ref_fix2,'String',[fullfile(ref.subdir,File) '....nc']);
3670    set(handles.ref_fix2,'UserData',ref)
3671    menu_field{1}='civ1';
3672    Data=nc2struct(fileinput,[]);
3673    if isfield(Data,'patch') && isequal(Data.patch,1)
3674        menu_field{2}='filter1';
3675    end
3676    if isfield(Data,'civ2') && isequal(Data.civ2,1)
3677        menu_field{3}='civ2';
3678    end
3679    if isfield(Data,'patch2') && isequal(Data.patch2,1)
3680        menu_field{4}='filter2';
3681    end
3682    set(handles.field_ref2,'String',menu_field);
3683    set(handles.field_ref2,'Value',length(menu_field));
3684    set(handles.num_MinVel,'Value',2);
3685    set(handles.num_MinVel,'String','1');%default threshold
3686    set(handles.ref_fix2,'Enable','on')
3687    set(handles.ref_fix2,'Visible','on')
3688    set(handles.field_ref2,'Visible','on')
3689else
3690    set(handles.ref_fix2,'Visible','off')
3691    set(handles.field_ref2,'Visible','off')
3692end
3693
3694%------------------------------------------------------------------------
3695function ref_fix1_Callback(hObject, eventdata, handles)
3696%------------------------------------------------------------------------
3697set(handles.num_MinVel,'Value',1);
3698set(handles.field_ref1,'Value',1)
3699set(handles.field_ref1,'String',{' '})
3700set(handles.ref_fix1,'UserData',[]);
3701set(handles.ref_fix1,'String','');
3702set(handles.thresh_vel1,'String','0');
3703
3704%------------------------------------------------------------------------
3705function ref_fix2_Callback(hObject, eventdata, handles)
3706%------------------------------------------------------------------------
3707set(handles.num_MinVel,'Value',1);
3708set(handles.field_ref2,'Value',1)
3709set(handles.field_ref2,'String',{' '})
3710set(handles.ref_fix2,'UserData',[]);
3711set(handles.ref_fix2,'String','');
3712set(handles.num_MinVel,'String','0');
3713
3714%------------------------------------------------------------------------
3715% --- TO ABANDON Executes on button press in test_stereo1.
3716function CheckStereo_Callback(hObject, eventdata, handles)
3717%------------------------------------------------------------------------
3718hparent=get(hObject,'parent');
3719parent_tag=get(hparent,'Tag');
3720hchildren=get(hparent,'children');
3721handle_txtbox=findobj(hchildren,'tag','txt_Mask');
3722if isequal(get(hObject,'Value'),0)
3723    set(handles.num_SubdomainSize,'Visible','on')
3724    set(handles.num_FieldSmooth,'Visible','on')
3725else
3726    set(handles.num_SubdomainSize,'Visible','off')
3727    set(handles.num_FieldSmooth,'Visible','off')
3728end
3729
3730% %------------------------------------------------------------------------
3731% % --- Executes on button press in CheckStereo.
3732% function StereoCheck_Callback(hObject, eventdata, handles)
3733% %------------------------------------------------------------------------
3734% if isequal(get(handles.CheckStereo,'Value'),0)
3735%     set(handles.num_SubdomainSize,'Visible','on')
3736%     set(handles.num_FieldSmooth,'Visible','on')
3737% else
3738%     set(handles.num_SubdomainSize,'Visible','off')
3739%     set(handles.num_FieldSmooth,'Visible','off')
3740% end
3741
3742%------------------------------------------------------------------------
3743% --- Executes on button press in TestCiv1: prepare the image correlation function
3744% activated by mouse motion
3745function TestCiv1_Callback(hObject, eventdata, handles)
3746%------------------------------------------------------------------------
3747drawnow
3748if get(handles.TestCiv1,'Value')
3749    set(handles.TestCiv1,'BackgroundColor',[0.7 0.7 0.7])% paint TestCiv1 button to grey to confirm civ launch
3750    ref_i=str2double(get(handles.ref_i,'String'));% read reference i index
3751    if strcmp(get(handles.ref_j,'Visible'),'on')
3752        ref_j=str2double(get(handles.ref_j,'String'));% read reference j index if relevant
3753    else
3754        ref_j=1;%default j index
3755    end
3756    [filecell,i1,i2]=set_civ_filenames(handles,ref_i,ref_j,[1 0 0 0 0 0]);% get the corresponding file name and indices
3757    Data.ListVarName={'ny','nx','A'};
3758    Data.VarDimName= {'ny','nx',{'ny','nx'}};
3759
3760    Data.A=imread(filecell.ima1.civ1{1}); % read the first image
3761    if ndims(Data.A)==3 %case of color image
3762        Data.VarDimName= {'ny','nx',{'ny','nx','rgb'}};
3763    end
3764    Data.ny=[size(Data.A,1) 1];
3765    Data.nx=[1 size(Data.A,2)];
3766    Data.CoordUnit='pixel';% used to set equal scaling for x and y in image dispaly
3767    par_civ1=read_GUI(handles.Civ1);
3768    par_civ1.FileTypeA=get_file_type(filecell.ima1.civ1{1});
3769    par_civ1.ImageWidth=size(Data.A,2);
3770    par_civ1.ImageHeight=size(Data.A,1);
3771    par_civ1.Mask='all';% will provide only the grid set for PIV, no image correlation
3772    par_civ1.FrameIndexA=num2str(i1);
3773    par_civ1.FrameIndexB=num2str(i2);
3774    Param.Civ1=par_civ1;
3775    Grid=civ_matlab(Param);% get the grid of x, y positions set for PIV
3776    hview_field=view_field(Data); %view the image in the GUI view_field
3777    set(0,'CurrentFigure',hview_field)
3778    hhview_field=guihandles(hview_field);
3779    set(hview_field,'CurrentAxes',hhview_field.axes3)
3780    ViewData=get(hview_field,'UserData');
3781    ViewData.CivHandle=handles.civ;% indicate the handle of the civ GUI in view_field
3782    ViewData.axes3.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
3783    ViewData.axes3.X=Grid.Civ1_X; %keep the set of points in memeory
3784    ViewData.axes3.Y=Grid.Civ1_Y;
3785    set(hview_field,'UserData',ViewData)
3786    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3787    if isempty(corrfig)
3788        corrfig=figure;
3789        set(corrfig,'tag','corrfig')
3790        set(corrfig,'name','image correlation')
3791        set(corrfig,'DeleteFcn',{@closeview_field})%
3792    end
3793    set(handles.TestCiv1,'BackgroundColor',[1 0 0])
3794else
3795    set(handles.TestCiv1,'BackgroundColor',[1 0 0])% paint button to red
3796    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3797    if ~isempty(corrfig)
3798        delete(corrfig)
3799    end
3800    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
3801    if ~isempty(hview_field)
3802        delete(hview_field)
3803    end
3804end
3805
3806%------------------------------------------------------------------------
3807%----function introduced for the correlation window figure, activated by deleting this window
3808function closeview_field(gcbo,eventdata)
3809%------------------------------------------------------------------------
3810hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
3811if ~isempty(hview_field)
3812    delete(hview_field)
3813end
3814
3815%------------------------------------------------------------------------
3816% --- Executes on button press in CheckThreshold.
3817function CheckThreshold_Callback(hObject, eventdata, handles)
3818%------------------------------------------------------------------------
3819huipanel=get(hObject,'parent');
3820obj(1)=findobj(huipanel,'Tag','num_MinIma');
3821obj(2)=findobj(huipanel,'Tag','num_MaxIma');
3822obj(3)=findobj(huipanel,'Tag','title_Threshold');
3823if get(hObject,'Value')
3824    set(obj,'Visible','on')
3825else
3826    set(obj,'Visible','off')
3827end
3828
3829
3830
3831
3832%'nomtype2pair': creates nomencalture for index pairs knowing the image nomenclature
3833%---------------------------------------------------------------------
3834function NomTypeNc=nomtype2pair(NomTypeIma,mode)
3835%---------------------------------------------------------------------           
3836% OUTPUT:
3837% NomTypeNc
3838%---------------------------------------------------------------------
3839% INPUT:
3840% 'NomTypeIma': string defining the kind of nomenclature used for images
3841
3842NomTypeNc=NomTypeIma;%default
3843switch mode
3844    case 'pair j1-j2'     
3845    if ~isempty(regexp(NomTypeIma,'a$'))
3846        NomTypeNc=[NomTypeIma 'b'];
3847    elseif ~isempty(regexp(NomTypeIma,'A$'))
3848        NomTypeNc=[NomTypeIma 'B'];
3849    else
3850        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
3851        if ~isempty(r)
3852            NomTypeNc='_1_1-2';
3853        end
3854    end
3855    case 'series(Dj)' 
3856        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
3857        if ~isempty(r)
3858            NomTypeNc='_1_1-2';
3859        end
3860   case 'series(Di)'
3861        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
3862        if ~isempty(r)
3863            NomTypeNc='_1-2_1';
3864        else
3865            NomTypeNc='_1-2';
3866        end
3867end
3868
3869function NomType_Callback(hObject, eventdata, handles)
3870set(handles.RootPath,'BackgroundColor',[1 1 0])%paint RootName edit box in yellow to indicate that the file input is proceeding
3871RootPath=get(handles.RootPath,'String');
3872RootFile=get(handles.RootFile,'String');
3873ref_i=str2num(get(handles.ref_i,'String'));
3874ref_j=str2num(get(handles.ref_j,'String'));
3875NomType=get(handles.NomType,'String');
3876ImaExt=get(handles.ImaExt,'String');
3877fileinput=fullfile_uvmat(RootPath,'',RootFile,ImaExt,NomType,ref_i,[],ref_j);
3878errormsg=display_file_name(handles,fileinput);
3879if ~isempty(errormsg)
3880    msgbox_uvmat('ERROR',errormsg)
3881end
3882set(handles.RootPath,'BackgroundColor',[1 1 1])%paint RootName back to white to indicate that the file input is finished
3883
3884% --- Executes on selection change in Program.
3885function Program_Callback(hObject, eventdata, handles)
3886ListProgram=get(handles.Program,'String');
3887Program=ListProgram{get(handles.Program,'value')};
3888switch Program
3889    case 'CivX'
3890        set(handles.num_MaxDiff,'Visible','off')
3891        set(handles.num_MaxVel,'Visible','off')
3892        set(handles.title_MaxVel,'Visible','off')
3893        set(handles.num_Nx,'Visible','on')
3894        set(handles.num_Ny,'Visible','on')
3895        set(handles.title_Nx,'Visible','on')
3896        set(handles.title_Ny,'Visible','on')
3897        set(handles.title_MaxDiff,'Visible','off')
3898        set(handles.num_CorrSmooth,'Style','edit')
3899        set(handles.num_CorrSmooth,'String','1')
3900        set(handles.BATCH,'Enable','on')
3901        set(handles.CheckThreshold,'Visible','off')
3902        set(handles.CheckDeformation,'Value',1)
3903        set(handles.CheckDecimal,'Value',1)
3904    case {'civ_matlab','civ_matlab.sh'}
3905        set(handles.num_MaxDiff,'Visible','on')
3906        set(handles.num_MaxVel,'Visible','on')
3907        set(handles.title_MaxVel,'Visible','on')
3908        set(handles.title_MaxDiff,'Visible','on')
3909        set(handles.num_Nx,'Visible','off')
3910        set(handles.num_Ny,'Visible','off')
3911        set(handles.title_Nx,'Visible','off')
3912        set(handles.title_Ny,'Visible','off')
3913        set(handles.num_CorrSmooth,'Style','popupmenu')
3914        set(handles.num_CorrSmooth,'Value',1)
3915        set(handles.num_CorrSmooth,'String',{'1';'2'})
3916        set(handles.CheckThreshold,'Visible','on')
3917        set(handles.CheckDeformation,'Value',0)% desactivate (work in progress)
3918        set(handles.CheckDecimal,'Value',0)% desactivate (work in progress)
3919end
3920
3921% --- Executes on button press in TestPatch1.
3922function TestPatch1_Callback(hObject, eventdata, handles)
3923set(handles.TestPatch1,'BackgroundColor',[1 1 0])
3924drawnow
3925if get(handles.TestPatch1,'Value')
3926    ref_i=str2double(get(handles.ref_i,'String'));
3927    if strcmp(get(handles.ref_j,'Visible'),'on')
3928        ref_j=str2double(get(handles.ref_j,'String'));
3929    else
3930        ref_j=1;%default
3931    end
3932    filecell=set_civ_filenames(handles,ref_i,ref_j,[0 0 1 0 0 0]);   
3933    Data.ListVarName={'ny','nx','A'};
3934    Data.VarDimName= {'ny','nx',{'ny','nx'}};   
3935    param_patch1=read_GUI(handles.Patch1);
3936    param_patch1.CivFile=filecell.nc.civ1{1};
3937    Param.Patch1=param_patch1;
3938    for irho=1:7
3939        [Data,errormsg]=civ_matlab(Param);% get the grid of x, y positions set for PIV
3940        if ~isempty(errormsg)
3941            msgbox_uvmat('ERROR',errormsg)
3942            return
3943        end
3944        SmoothingParam(irho)=Param.Patch1.FieldSmooth;
3945        Data.Civ1_U_Diff=Data.Civ1_U_Diff(Data.Civ1_FF==0);
3946        Data.Civ1_V_Diff=Data.Civ1_V_Diff(Data.Civ1_FF==0);
3947        DiffVel(irho)=sqrt(mean(Data.Civ1_U_Diff.*Data.Civ1_U_Diff+Data.Civ1_V_Diff.*Data.Civ1_V_Diff))
3948        NbSites(irho,:)=Data.Civ1_NbSites*numel(Data.Civ1_NbSites)/numel(Data.Civ1_U_Diff);
3949        Param.Patch1.SmoothingParam=2*Param.Patch1.FieldSmooth;
3950    end
3951    figure
3952    plot(SmoothingParam,DiffVel,'b',SmoothingParam,NbSites,'r')
3953    set(handles.TestPatch1,'BackgroundColor',[1 0 0])
3954else
3955    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
3956    if ~isempty(corrfig)
3957        delete(corrfig)
3958    end
3959    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
3960    if ~isempty(hview_field)
3961        delete(hview_field)
3962    end
3963end
3964
3965
3966% --- Executes on button press in TestCiv2.
3967function TestCiv2_Callback(hObject, eventdata, handles)
3968
3969function RootFile_Callback(hObject, eventdata, handles)
3970
3971function SubdirImages_Callback(hObject, eventdata, handles)
3972
3973
3974
3975function errormsg=write_param(Param)
3976%------------------------------------------------------------------------
3977%pixels per cm and matrix of the image times, read from the .civ file by uvmat
3978%changes : filename_cmx -> filename ( no extension )
3979errormsg='';
3980switch Param.Program
3981    case 'CivX'
3982        if Param.CheckCiv1
3983            filename=regexprep(Param.OutputFile,'(\w+)([/\\])(\w+$)','$1$20_CMX$2$3.civ1.cmx');
3984            if isequal(Param.Civ1.Dt,0)
3985                Param.Civ1.Dt=1 ;%case of 'displacement' mode
3986            end
3987            Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'.png','');
3988            Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'.png','');
3989            [fid,errormsg]=fopen(filename,'w');
3990            if isequal(fid,-1)
3991                errormsg=['cmd file ' filename ' cannot be created: ' errormsg];
3992                return
3993            end
3994            fprintf(fid,['##############   CMX file' '\n' ]);
3995            fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
3996            fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
3997            fprintf(fid,  ['XX' '\n' ]);
3998            if isfield(Param.Civ1,'Mask')
3999                fprintf(fid,  ['Mask ' 'y' '\n' ]);
4000                fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.Mask,'\\','\\\\') '\n' ]);
4001            else
4002                fprintf(fid,  ['Mask ' 'n' '\n' ]);
4003                fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4004            end
4005            fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageWidth) ' ' num2str(Param.Civ1.ImageHeight) '\n' ]);   %VERIFIER CAS GENERAL ?
4006            fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.CorrBoxSize(1)) ' ' num2str(Param.Civ1.CorrBoxSize(2)) '\n' ]);
4007            fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.SearchBoxSize(1)) ' ' num2str(Param.Civ1.SearchBoxSize(2)) '\n' ]);
4008            fprintf(fid,   ['RO ' num2str(Param.Civ1.CorrSmooth) '\n' ]);
4009            if isfield(Param.Civ1,'Grid')
4010                fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4011            else
4012                fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
4013            end
4014            fprintf(fid,   ['XX 1.0' '\n' ]);
4015            fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.Time) '\n' ]);
4016            fprintf(fid,  ['PixCmXY ' '1' ' ' '1' '\n' ]);
4017            fprintf(fid,  ['XX 1' '\n' ]);
4018            fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.SearchBoxShift(1)) ' '  num2str(Param.Civ1.SearchBoxShift(2)) '\n' ]);
4019            if isfield(Param.Civ1,'Grid')
4020                fprintf(fid,  ['Grid ' 'y' '\n' ]);
4021                fprintf(fid,   ['GridName ' regexprep(Param.Civ1.Grid,'\\','\\\\') '\n' ]);
4022            else
4023                fprintf(fid,  ['Grid ' 'n' '\n' ]);
4024                fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4025            end
4026            fprintf(fid,   ['XX 85' '\n' ]);
4027            fprintf(fid,   ['XX 1.0' '\n' ]);
4028            fprintf(fid,   ['XX 1.0' '\n' ]);
4029            fprintf(fid,   ['Hart 1' '\n' ]);
4030            fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
4031            fprintf(fid,   ['Deformation 0' '\n' ]);
4032            fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4033            fprintf(fid,   ['IntensityMin 0' '\n' ]);
4034            if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
4035                fprintf(fid,  ['SeuilImage n' '\n' ]);
4036                fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4037            else% Image threshold  activated
4038                if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
4039                    Param.Civ1.MaxIma=2^Param.Civ1.ImageBitDepth;%take the max image value as upper bound by default
4040                end
4041                fprintf(fid,  ['SeuilImage y' '\n' ]);
4042                fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
4043            end
4044            fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
4045            fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
4046            fclose(fid);
4047        end
4048       
4049        if Param.CheckCiv2
4050            filename=regexprep(Param.OutputFile,'(\w+)([/\\])(\w+$)','$1$20_CMX$2$3.civ2.cmx');
4051
4052            if isequal(Param.Civ2.Dt,'0')
4053                Param.Civ2.Dt='1' ;%case of 'displacement' mode
4054            end
4055            Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'.png','');
4056            Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'.png','');% bug : .png appears two times ?
4057            [fid,errormsg]=fopen(filename,'w');
4058            if isequal(fid,-1)
4059                return
4060            end
4061            fprintf(fid,['##############   CMX file' '\n' ]);
4062            fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4063            fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4064            fprintf(fid,  ['XX' '\n' ]);
4065            if isfield(Param.Civ2,'Mask')
4066                fprintf(fid,  ['Mask ' 'y' '\n' ]);
4067                fprintf(fid,  ['MaskName ' regexprep(Param.Civ2.Mask,'\\','\\\\') '\n' ]);
4068            else
4069                fprintf(fid,  ['Mask ' 'n' '\n' ]);
4070                fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4071            end
4072            % fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
4073            % fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
4074            fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageWidth) ' ' num2str(Param.Civ2.ImageHeight) '\n' ]);
4075            % fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
4076            fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n' ]);
4077            fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.CorrBoxSize(1)) ' ' num2str(Param.Civ2.CorrBoxSize(2)) '\n']);
4078            fprintf(fid, ['RO ' num2str(Param.Civ2.CorrSmooth) '\n']);
4079            if isfield(Param.Civ2,'Grid')
4080                fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4081            else
4082                fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
4083            end
4084            % fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
4085            fprintf(fid, ['XX 1.0' '\n' ]);
4086            fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.Time) '\n' ]);
4087            fprintf(fid, ['PixCmXY ' '1' ' ' '1' '\n' ]);
4088            fprintf(fid, ['XX 1' '\n' ]);
4089            fprintf(fid, 'ShiftXY 0 0\n');
4090            if isfield(Param.Civ2,'Grid')
4091                fprintf(fid,  ['Grid ' 'y' '\n' ]);
4092                fprintf(fid,   ['GridName ' regexprep(Param.Civ2.Grid,'\\','\\\\') '\n' ]);
4093            else
4094                fprintf(fid,  ['Grid ' 'n' '\n' ]);
4095                fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4096            end
4097            % fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
4098            % fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
4099            fprintf(fid, ['XX 85' '\n' ]);
4100            fprintf(fid, ['XX 1.0' '\n' ]);
4101            fprintf(fid, ['XX 1.0' '\n' ]);
4102            fprintf(fid, ['Hart 1' '\n' ]);
4103            fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
4104            fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
4105            fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4106            fprintf(fid,   ['IntensityMin 0' '\n' ]);
4107           
4108            if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
4109                fprintf(fid,  ['SeuilImage n' '\n' ]);
4110                fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4111            else% Image threshold  activated
4112                if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
4113                    Param.Civ2.MaxIma=2^Param.Civ2.ImageBitDepth;%take the max image value as upper bound by default
4114                end
4115                fprintf(fid,  ['SeuilImage y' '\n' ]);
4116                fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
4117            end
4118            fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
4119            fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
4120            fclose(fid);
4121        end
4122    case {'civ_matlab','civ_matlab.sh'}
4123        filename=regexprep(Param.OutputFile,'(\w+)([/\\])(\w+$)','$1$20_XML$2$3.xml');
4124        save(struct2xml(Param),filename);
4125end
4126
4127
4128function cmd=write_cmd(Param)
4129
4130% initiate system command
4131cmd=[];
4132
4133switch Param.Program
4134    case 'CivX'
4135        if isunix % check: necessaire aussi en RUN?
4136            cmd=[cmd '#!/bin/bash \n '...
4137                '#$ -cwd \n '...
4138                'hostname && date \n '...
4139                'umask 002 \n'];%allow writting access to created files for user group
4140        end
4141    case 'CivAll'
4142        if isunix % check: necessaire aussi en RUN?
4143            cmd=[cmd '#!/bin/bash \n '...
4144                '#$ -cwd \n '...
4145                'hostname && date \n '...
4146                'umask 002 \n'];%allow writting access to created files for user group
4147        end
4148end
4149
4150filename=regexprep(Param.OutputFile,'.nc','');
4151
4152if Param.CheckCiv1
4153    switch Param.Program
4154        case 'CivX'
4155            if(isunix) %unix (or Mac) system
4156                cmd=[cmd 'cp -f ' regexprep(filename,'(\w+)/(\w+$)','$1/0_CMX/$2.civ1.cmx ') regexprep(filename,'(\w+)/(\w+$)','$1/$2.cmx \n')...% the cmx file gives the name to the nc file
4157                    Param.xml.Civ1Bin ' -f ' regexprep(filename,'(\w+)/(\w+$)','$1/$2.cmx >') regexprep(filename,'(\w+)/(\w+$)','$1/0_LOG/$2.civ1.log \n')... % redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
4158                    'rm ' regexprep(filename,'(\w+)/(\w+$)','$1/$2.cmx \n')];
4159            else %Windows system
4160                filename=regexprep(filename,'\\','\\\\');
4161                cmd=['copy /Y ' regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\0_CMX\\\\$2.civ1.cmx" ') regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\$2.civ1.cmx" \n')...
4162                    '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\') '" -f ' regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\$2.cmx" > ')...
4163                    regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\0_LOG\\\\$2.civ1.log" \n')... % redirect standard output to the log file
4164                    'del ' regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\$2.cmx" \n')];
4165            end
4166        case 'CivAll'
4167            CivAllCmd=[CivAllCmd ' civ1 '];
4168            str=CIV1_CMD_Unified(filecell.nc.civ1{ifile,j},'',Param.Civ1);
4169            fieldnames=fields(str);
4170            [CivAllxml,uid_civ1]=add(CivAllxml,1,'element','civ1');
4171            for ilist=1:length(fieldnames)
4172                val=eval(['str.' fieldnames{ilist}]);
4173                if ischar(val)
4174                    [CivAllxml,uid_t]=add(CivAllxml,uid_civ1,'element',fieldnames{ilist});
4175                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
4176                end
4177            end
4178    end
4179end
4180
4181if Param.CheckFix1
4182    switch Param.Program
4183        case 'CivX'
4184            cmd=[cmd...
4185                cmd_fix(Param,'Fix1') '\n'];
4186        case 'CivAll'%to abandon
4187            fix1.inputFileName=filecell.nc.civ1{ifile,j} ;
4188            fix1.fi1=num2str(param.fix1.flagindex1(1));
4189            fix1.fi2=num2str(param.fix1.flagindex1(2));
4190            fix1.fi3=num2str(param.fix1.flagindex1(3));
4191            fix1.threshC=num2str(param.fix1.thresh_vecC1);
4192            fix1.threshV=num2str(param.fix1.thresh_vel1);
4193            fieldnames=fields(fix1);
4194            [CivAllxml,uid_fix1]=add(CivAllxml,1,'element','fix1');
4195            for ilist=1:length(fieldnames)
4196                val=eval(['fix1.' fieldnames{ilist}]);
4197                if ischar(val)
4198                    [CivAllxml,uid_t]=add(CivAllxml,uid_fix1,'element',fieldnames{ilist});
4199                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
4200                end
4201            end
4202            CivAllCmd=[CivAllCmd ' fix1 '];
4203    end
4204end
4205
4206
4207%CheckPatch1
4208if Param.CheckPatch1
4209    switch Param.Program
4210        case 'CivX'
4211            cmd=[cmd...
4212                cmd_patch(Param,'Patch1') '\n'];
4213        case 'CivAll'
4214            patch1.inputFileName=filecell.nc.civ1{ifile,j} ;
4215            patch1.nopt=subdomain_patch1;
4216            patch1.maxdiff=thresh_patch1;
4217            patch1.ro=rho_patch1;
4218            test_grid=get(handles.get_gridpatch1,'Value');
4219            if test_grid
4220                patch1.gridflag='y';
4221                gridname=get(handles.grid_patch1,'String');
4222                if isequal(gridname(end-3:end),'grid')
4223                    nbslice_grid=str2double(gridname(1:end-4)); %
4224                    if ~isnan(nbslice_grid)
4225                        i1_grid=mod(i1_civ1(ifile)-1,nbslice_grid)+1;
4226                        patch1.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
4227                        %                                 patch1.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
4228                        if ~exist(patch1.gridPatch,'file')
4229                            errormsg='grid file absent for patch1';
4230                            return
4231                        end
4232                    elseif exist(gridname,'file')
4233                        patch1.gridPatch=gridname;
4234                    else
4235                        errormsg='grid file absent for patch1';
4236                        return
4237                    end
4238                end
4239            else
4240                patch1.gridPatch='none';
4241                patch1.gridflag='n';
4242                patch1.m=nx_patch1;
4243                patch1.n=ny_patch1;
4244            end
4245            patch1.convectFlow='n';
4246            fieldnames=fields(patch1);
4247            [CivAllxml,uid_patch1]=add(CivAllxml,1,'element','patch1');
4248            for ilist=1:length(fieldnames)
4249                val=eval(['patch1.' fieldnames{ilist}]);
4250                if ischar(val)
4251                    [CivAllxml,uid_t]=add(CivAllxml,uid_patch1,'element',fieldnames{ilist});
4252                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
4253                end
4254            end
4255            CivAllCmd=[CivAllCmd ' patch1 '];
4256    end
4257end
4258
4259if Param.CheckCiv2
4260    switch Param.Program
4261        case 'CivX'
4262            if(isunix)
4263                cmd=[cmd 'cp -f '  regexprep(filename,'(\w+)/(\w+$)','$1/0_CMX/$2.civ2.cmx ') regexprep(filename,'(\w+)/(\w+$)','$1/$2.cmx \n')...
4264                    Param.xml.Civ2Bin ' -f ' regexprep(filename,'(\w+)/(\w+$)','$1/$2.cmx >') regexprep(filename,'(\w+)/(\w+$)','$1/0_LOG/$2.civ2.log \n')...% redirect standard output to the log file, the result file is named [filename '.nc'] by CIVx
4265                    'rm ' regexprep(filename,'(\w+)/(\w+$)','$1/$2.cmx \n')];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
4266            else
4267                filename=regexprep(filename,'\\','\\\\');
4268                cmd=[cmd 'copy /Y ' regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\0_CMX\\\\$2.civ2.cmx" ') regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\$2.cmx" \n')...
4269                    '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f "' regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\$2.cmx" > ')...
4270                     regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\0_LOG\\\\$2.civ2.log" \n')... % redirect standard output to the log file
4271                    'del ' regexprep(filename,'(\w+)\\\\(\w+$)','"$1\\\\$2.cmx" \n')];
4272            end
4273        case 'CivAll'
4274            CivAllCmd=[CivAllCmd ' civ2 '];
4275            str=CIV2_CMD_Unified(filecell.nc.civ2{ifile,j},'',Param.Civ2);
4276            fieldnames=fields(str);
4277            [CivAllxml,uid_civ2]=add(CivAllxml,1,'element','civ2');
4278            for ilist=1:length(fieldnames)
4279                val=eval(['str.' fieldnames{ilist}]);
4280                if ischar(val)
4281                    [CivAllxml,uid_t]=add(CivAllxml,uid_civ2,'element',fieldnames{ilist});
4282                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
4283                end
4284            end
4285    end
4286end
4287
4288% CheckFix2
4289if Param.CheckFix2==1
4290    switch Param.Program
4291        case 'CivX'
4292            cmd=[cmd...
4293                cmd_fix(Param,'Fix2') '\n'];
4294        case 'CivAll'
4295            fix2.inputFileName=filecell.nc.civ2{ifile,j} ;
4296            fix2.fi1=num2str(flagindex2(1));
4297            fix2.fi2=num2str(flagindex2(2));
4298            fix2.fi3=num2str(flagindex2(3));
4299            fix2.threshC=num2str(thresh_vec2C);
4300            fix2.threshV=num2str(thresh_vel2);
4301            fieldnames=fields(fix2);
4302            [CivAllxml,uid_fix2]=add(CivAllxml,1,'element','fix2');
4303            for ilist=1:length(fieldnames)
4304                val=eval(['fix2.' fieldnames{ilist}]);
4305                if ischar(val)
4306                    [CivAllxml,uid_t]=add(CivAllxml,uid_fix2,'element',fieldnames{ilist});
4307                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
4308                end
4309            end
4310            CivAllCmd=[CivAllCmd ' fix2 '];
4311    end
4312end
4313
4314%CheckPatch2
4315if Param.CheckPatch2==1
4316   
4317    switch Param.Program
4318       
4319        case 'CivX'
4320            cmd=[cmd...
4321                cmd_patch(Param,'Patch2') '\n'];
4322        case 'CivAll'
4323            patch2.inputFileName=filecell.nc.civ1{ifile,j} ;
4324            patch2.nopt=subdomain_patch2;
4325            patch2.maxdiff=thresh_patch2;
4326            patch2.ro=rho_patch2;
4327            test_grid=get(handles.get_gridpatch2,'Value');
4328            if test_grid
4329                patch2.gridflag='y';
4330                gridname=get(handles.grid_patch2,'String');
4331                if isequal(gridname(end-3:end),'grid')
4332                    nbslice_grid=str2double(gridname(1:end-4)); %
4333                    if ~isnan(nbslice_grid)
4334                        i1_grid=mod(i1_civ2(ifile)-1,nbslice_grid)+1;
4335                        patch2.gridPatch=[filecell.filebase '_' fullfile_uvmat('','',gridname,'.grid','_1',i1_grid)];
4336                        %                                 patch2.gridPatch=[filecell.filebase '_' name_generator(gridname,i1_grid,1,'.grid','_i')];
4337                        if ~exist(patch2.gridPatch,'file')
4338                            errormsg='grid file absent for patch2';
4339                            return
4340                        end
4341                    elseif exist(gridname,'file')
4342                        patch2.gridPatch=gridname;
4343                    else
4344                        errormsg='grid file absent for patch2';
4345                        return
4346                    end
4347                end
4348            else
4349                patch2.gridPatch='none';
4350                patch2.gridflag='n';
4351                patch2.m=nx_patch2;
4352                patch2.n=ny_patch2;
4353            end
4354            patch2.convectFlow='n';
4355            fieldnames=fields(patch2);
4356            [CivAllxml,uid_patch2]=add(CivAllxml,1,'element','patch2');
4357            for ilist=1:length(fieldnames)
4358                val=eval(['patch2.' fieldnames{ilist}]);
4359                if ischar(val)
4360                    [CivAllxml,uid_t]=add(CivAllxml,uid_patch2,'element',fieldnames{ilist});
4361                    [CivAllxml,uid_t2]=add(CivAllxml,uid_t,'chardata',val);
4362                end
4363            end
4364            CivAllCmd=[CivAllCmd ' patch2 '];
4365    end
4366end
4367
4368switch Param.Program
4369    case 'CivAll'
4370        save(CivAllxml,[Param.OutputFile '.xml']);
4371        cmd=[cmd sparam.CivBin ' -f ' Param.OutputFile '.xml '  CivAllCmd ' >' Param.OutputFile '.log' '\n'];
4372    case 'civ_matlab'
4373                    switch computer
4374                        case {'PCWIN','PCWIN64'}                     
4375                            filename=regexprep(filename,'\\','\\\\');% add '\' so that '\' are left as characters
4376                        case {'GLNX86','GLNXA64','MACI64'}
4377                    end
4378        cmd=['civ_matlab(''' regexprep(filename,'(\w+)([/\\])(\w+$)','$1$20_XML$2$3.xml') ''','''...
4379            filename '.nc'');'];
4380    case 'civ_matlab.sh'
4381        switch computer
4382            case {'PCWIN','PCWIN64'}
4383                filename=regexprep(filename,'\\','\\\\');% add '\' so that '\' are left as characters
4384                % TODO launch command in DOS
4385            case {'GLNX86','GLNXA64','MACI64'}
4386                cmd=['#!/bin/bash \n '...
4387                    '#$ -cwd \n '...
4388                    'hostname && date \n '...
4389                    'umask 002 \n'...
4390                    Param.xml.CivmBin ' ' Param.xml.RunTime ' ' regexprep(filename,'(\w+)([/\\])(\w+$)','$1$20_XML$2$3.xml') ' ' Param.OutputFile '.nc'];%allow writting access to created files for user group
4391        end
4392end   
4393   
4394
4395function cmd=cmd_fix(Param,fixname)
4396%%
4397switch fixname
4398    case 'Fix1'
4399        fi2_value=num2str(Param.(fixname).CheckF2);
4400        filename=regexprep(Param.OutputFile,'.nc','');
4401    case 'Fix2'
4402        fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
4403        filename=regexprep(Param.OutputFile,'.nc','');       
4404end
4405
4406% filename=regexprep(Param.(fixname).OutFileName,'.nc','');
4407MaskName_string='';%default
4408MaxVel_string='';%default
4409if ~isempty(Param.(fixname).MinVel)
4410    MaxVel_string=[' -threshV ' num2str(Param.(fixname).MinVel)];
4411end
4412if isunix
4413    cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
4414        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4415        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4416        ' >' regexprep(filename,'(\w+)/(\w+$)','$1/0_LOG/$2.')  lower(fixname) '.log 2>&1'];
4417else
4418    cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
4419        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4420        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4421        ' > "' regexprep(filename,'(\w+)\\(\w+$)','$1\\0_LOG\\$2.') lower(fixname) '.log"'];
4422    cmd=regexprep(cmd,'\\','\\\\');
4423end
4424
4425
4426function cmd=cmd_patch(Param,patchname)
4427%% ------------------------------------------------------------------------
4428switch patchname
4429    case 'Patch1'
4430        filename=regexprep(Param.OutputFile,'.nc','');
4431    case 'Patch2'
4432        filename=regexprep(Param.OutputFile,'.nc','');       
4433end
4434% filename=regexprep(Param.(patchname).OutFileName,'.nc','');
4435if isunix
4436    cmd=[Param.xml.PatchBin...
4437        ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
4438        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
4439        ' -nopt ' num2str(Param.(patchname).SubdomainSize) ...
4440        '  > ' regexprep(filename,'(\w+)/(\w+$)','$1/0_LOG/$2.')  lower(patchname) '.log 2>&1']; % redirect standard output to the log file
4441else
4442    cmd=['"' Param.xml.PatchBin...
4443        '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
4444        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).FieldSmooth)...
4445        ' -nopt ' num2str(Param.(patchname).SubdomainSize)...
4446        '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
4447    cmd=regexprep(cmd,'\\','\\\\');
4448end
4449
4450
4451
4452
4453%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4454% USELESS FUNCTIONS BELOW HERE,  TO CLEAN
4455%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4456
4457
4458
4459
4460
4461%------------------------------------------------------------------------
4462% --- CheckCiv1  Unified: TO ABADON
4463function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
4464%------------------------------------------------------------------------
4465%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4466%global CivBin%name of the executable for checkciv1 calculation
4467
4468civ1.image1=par.ImageA;
4469civ1.image2=par.ImageB;
4470civ1.imageSize_X=par.npx;
4471civ1.imageSize_Y=par.npy;
4472civ1.outputFileName=[filename '.nc'];
4473civ1.correlationBoxesSize_X=par.ibx;
4474civ1.correlationBoxesSize_Y=par.iby;
4475civ1.searchBoxesSize_X=par.isx;
4476civ1.searchBoxesSize_Y=par.isy;
4477civ1.globalShift_X=par.shiftx;
4478civ1.globalShift_Y=par.shifty;
4479civ1.ro=par.rho;
4480civ1.hart='y';
4481if isequal(par.gridflag,'y')
4482    civ1.grid=par.gridname;
4483else
4484    civ1.grid='n';
4485    civ1.gridSpacing_X=par.dx;
4486    civ1.gridSpacing_Y=par.dy;
4487end
4488if isequal(par.maskflag,'y')
4489    civ1.mask=par.maskname;
4490end
4491civ1.dt=par.Dt;
4492civ1.unit='pixel';
4493civ1.absolut_time_T0=par.Time;
4494civ1.pixcmx='1';
4495civ1.pixcmy='1';
4496civ1.convectFlow='n';
4497
4498xml_civ1_parameters=civ1;
4499
4500%------------------------------------------------------------------------
4501% --- CheckCiv2  Unified: TO ABADON
4502function civ2=CIV2_CMD_Unified(filename,namelog,par)
4503%------------------------------------------------------------------------
4504%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4505%global CivBin%name of the executable for checkciv1 calculation
4506
4507filename=regexprep(filename,'.nc','');
4508
4509civ2.image1=par.ImageA;
4510civ2.image2=par.ImageB;
4511civ2.imageSize_X=par.npx;
4512civ2.imageSize_Y=par.npy;
4513civ2.inputFileName=[par.filename_nc1 '.nc'];
4514civ2.outputFileName=[filename '.nc'];
4515civ2.correlationBoxesSize_X=par.ibx;
4516civ2.correlationBoxesSize_Y=par.iby;
4517civ2.ro=par.rho;
4518%checkciv2.decimalShift=par.CheckDecimal;
4519%checkciv2.CheckDeformation=par.CheckDeformation;
4520if isequal(par.decimal,'1')
4521    civ2.decimalShift='y';
4522else
4523    civ2.decimalShift='n';
4524end
4525if isequal(par.deformation,'1')
4526    civ2.deformation='y';
4527else
4528    civ2.deformation='n';
4529end
4530if isequal(par.gridflag,'y')
4531    civ2.grid=par.gridname;
4532else
4533    civ2.grid='n';
4534    civ2.gridSpacing_X=par.dx;
4535    civ2.gridSpacing_Y=par.dy;
4536end
4537civ2.gridSpacing_X='10';
4538civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
4539if isequal(par.maskflag,'y')
4540    civ2.mask=par.maskname;
4541else
4542    civ2.mask='n';
4543end
4544civ2.dt=par.Dt;
4545civ2.unit='pixel';
4546civ2.absolut_time_T0=par.Time;
4547civ2.pixcmx='1';
4548civ2.pixcmy='1';
4549civ2.convectFlow='n';
4550
4551
4552% --- Executes on selection change in RunMode.
4553function RunMode_Callback(hObject, eventdata, handles)
Note: See TracBrowser for help on using the repository browser.