source: trunk/src/civ.m @ 476

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

bugs corrected +
* filter parameter multiplied by 1000 in filter_tps*

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