source: trunk/src/civ.m @ 440

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

bug repaired in series

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