source: trunk/src/civ.m @ 467

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

options 'local,background,cluster' introduced in civ

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