source: trunk/src/civ.m @ 493

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

various bugs repaired, tests in Windows OS

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