source: trunk/src/civ.m @ 485

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