source: trunk/src/civ.m @ 437

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

rationalisation of civ parameter names
civ results now put in a directory outside the image directory.
*xml file management needs to be updated

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