source: trunk/src/civ.m @ 435

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

civ improved to deal with movies. Introduction of a file type mmreader needed for Matlab 2009 (Videoreader not available)

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