source: trunk/src/civ.m @ 465

Last change on this file since 465 was 465, checked in by gostiaux, 12 years ago

write_cmd et write_param generalized
background task included
new conventions for bathc with matlab

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