source: trunk/src/civ.m @ 363

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

civ2 introduced in civ_matlab (still bugs)
bugs corrected in civ and fill_GUI, read_GUI
comments in get_field

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