source: trunk/src/civ.m @ 421

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

bugs corrections and improvements following tutorial presentation

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