source: trunk/src/civ.m @ 441

Last change on this file since 441 was 441, checked in by sommeria, 13 years ago

many bugs corrected for the new file organisation

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