source: trunk/src/civ.m @ 468

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

bug corrected in civ : reading time in case of xml file and avi
bugs corrrected in series

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