source: trunk/src/civ.m @ 362

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

various bugs corrected

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 08-Jan-2012 11:00:13
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.txt_SubdirCiv1,'String',listdir{ValueCiv1})
622    ValueCiv2=get(handles.ListSubdirCiv2,'Value');
623    if ValueCiv2>numel(listdir)
624        ValueCiv2=1;
625    end
626    set(handles.txt_SubdirCiv2,'String',listdir{ValueCiv2})
627else
628    ValueCiv1=Value;
629    ValueCiv2=Value;
630     set(handles.txt_SubdirCiv1,'String',listdir{Value})
631     set(handles.txt_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.txt_SubdirCiv1,'String','CIV')
639    set(handles.txt_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 txt_SubdirCiv1_Callback(hObject, eventdata, handles)
667%------------------------------------------------------------------------
668SubDir=get(handles.txt_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.txt_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 txt_SubdirCiv2_Callback(hObject, eventdata, handles)
690%------------------------------------------------------------------------
691SubDir=get(handles.txt_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.txt_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.txt_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.txt_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
1694t=struct2xml(Param);
1695save(t,[namedoc '.xml']); %save GUI  parameters as xml file
1696saveas(gcbf,namefigfull);%save the interface with name namefigfull (A CHANGER EN FICHIER  .xml)
1697
1698%Save info in personal profile (initiate browser next time) TODO
1699MenuFile={};
1700dir_perso=prefdir;
1701profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1702if exist(profil_perso,'file')
1703    hh=load (profil_perso);
1704      if isfield(hh,'MenuFile')
1705          MenuFile=hh.MenuFile;
1706      end
1707      if isfield(filecell.nc,'civ2')
1708          MenuFile=[filecell.nc.civ2{1,1}; MenuFile];
1709      else
1710           MenuFile=[filecell.nc.civ1{1,1}; MenuFile];
1711      end
1712      save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
1713else
1714    MenuFile=filecell.ima1.civ1(1,1);
1715    save (profil_perso,'MenuFile')
1716end
1717
1718%------------------------------------------------------------------------
1719% --- determine the list of reference indices of processing file
1720function [ref_i,ref_j,errormsg]=find_ref_indices(handles)
1721%------------------------------------------------------------------------
1722errormsg=''; %default error message
1723first_i=str2double(get(handles.first_i,'String'));%first index i
1724last_i=str2double(get(handles.last_i,'String'));%last index i
1725incr_i=str2double(get(handles.incr_i,'String'));% increment
1726if isequal(get(handles.first_j,'Visible'),'on')
1727    first_j=str2double(get(handles.first_j,'String'));%first index j
1728    last_j=str2double(get(handles.last_j,'String'));%last index j
1729    incr_j=str2double(get(handles.incr_j,'String'));% increment
1730else
1731    first_j=1;
1732    last_j=1;
1733    incr_j=1;
1734end
1735ref_i=first_i:incr_i:last_i;% list of i indices (reference values for each pair)
1736ref_j=first_j:incr_j:last_j;% list of j indices (reference values for each pair)
1737if isnan(first_i)||isnan(first_j)
1738    errormsg='first field number not defined';
1739elseif isnan(last_i)||isnan(last_j)
1740    errormsg='last field number not defined';
1741elseif isnan(incr_i)||isnan(incr_j)
1742    errormsg='increment in field number not defined';
1743elseif last_i < first_i || last_j < first_j
1744    errormsg='last field number must be larger than the first one';
1745end
1746
1747%------------------------------------------------------------------------
1748% --- determine the list of filenames and indices needed for launch_job
1749function [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]=...
1750    set_civ_filenames(handles,ref_i,ref_j,checkbox)
1751%------------------------------------------------------------------------
1752filecell=[];%default
1753
1754%% get the root names nomenclature and numbers
1755filebase=get(handles.RootName,'String');
1756
1757if isempty(filebase)||isequal(filebase,'')
1758    msgbox_uvmat('ERROR','please open an image with the upper menu option Open/Browse...')
1759    return
1760end
1761
1762%filebase=regexprep(filebase,'\.fsnet','fsnet');% temporary fix for cluster Coriolis
1763filecell.filebase=filebase;
1764
1765browse=get(handles.RootName,'UserData');
1766compare_list=get(handles.ListCompareMode,'String');
1767val=get(handles.ListCompareMode,'Value');
1768compare=compare_list{val};
1769if strcmp(compare,'displacement')||strcmp(compare,'shift')
1770    mode='displacement';
1771else
1772    mode_list=get(handles.ListPairMode,'String');
1773    mode_value=get(handles.ListPairMode,'Value');
1774    mode=mode_list{mode_value};
1775end
1776%time=get(handles.RootName,'UserData'); %get the set of times
1777ext_ima=get(handles.ImaExt,'String');
1778if strcmp(compare,'displacement')
1779    nom_type_ima1='*';
1780else
1781    nom_type_ima1=get(handles.NomType,'String');
1782end
1783nom_type_nc=nomtype2pair(nom_type_ima1,mode);
1784
1785[num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
1786    find_pair_indices(handles,ref_i,ref_j,mode);
1787%determine the new filebase for 'displacement' ListPairMode (comparison of two series)
1788filebase_B=filebase;% root name of the second field series for stereo
1789if ~strcmp(compare,'PIV')
1790    [Path2,Name2]=fileparts(filebase_B);
1791    Path1=Path2;
1792    Name1=get(handles.RootName_1,'String');% root name of the first field series for stereo
1793    filebase_A=fullfile(Path1,Name1);
1794    if length(Name1)>6
1795        Name1=Name1(end-5:end);
1796    end
1797    if length(Name2)>6
1798        Name2=Name2(end-5:end);
1799    end
1800    filebase_AB=fullfile(Path2,[Name2 '-' Name1]);
1801else
1802%     test_disp=0;
1803    filebase_A=filebase;
1804    nom_type_ima2=nom_type_ima1;
1805    filebase_AB=filebase;
1806end
1807if strcmp(compare,'displacement')||strcmp(compare,'shift')
1808    filebase_ima1=filebase_A;
1809    filebase_ima2=filebase_B;
1810    filebase_nc=filebase_AB; %root name for the result of civ2
1811else
1812    filebase_ima1=filebase_B;
1813    filebase_ima2=filebase_B;
1814    filebase_nc=filebase_B;
1815end
1816[RootPath_ima1,RootFile_ima1]=fileparts(filebase_ima1);
1817[RootPath_ima2,RootFile_ima2]=fileparts(filebase_ima2);
1818[RootPath_nc,RootFile_nc]=fileparts(filebase_nc);
1819[RootPath_A,RootFile_A]=fileparts(filebase_A);
1820[RootPath_AB,RootFile_AB]=fileparts(filebase_AB);
1821   
1822%determine reference files for fix:
1823file_ref_fix1={};%default
1824file_ref_fix2={};
1825nbfield=length(num1_civ1);
1826nbslice=length(num_a_civ1);
1827if checkbox(2)==1% fix1 performed
1828    ref=get(handles.ref_fix1,'UserData');%read data on the ref file stored by get_ref_fix1_Callback
1829    if ~isempty(ref)
1830        first_i=str2double(get(handles.first_i,'String'));
1831        last_i=str2double(get(handles.last_i,'String'));
1832        incr_i=str2double(get(handles.incr_i,'String'));
1833        first_j=str2double(get(handles.first_j,'String'));
1834        last_j=str2double(get(handles.last_j,'String'));
1835        incr_j=str2double(get(handles.incr_j,'String'));
1836        num_i_ref=first_i:incr_i:last_i;
1837        num_j_ref=first_j:incr_j:last_j;
1838        if isequal(mode,'displacement')
1839            num_i1=num_i_ref;
1840 name_genna           num_i2=num_i_ref;
1841            num_j1=num_j_ref;
1842            num_j2=num_j_ref;
1843        elseif isequal(mode,'pair j1-j2')% isequal(mode,'st_pair j1-j2')
1844            num_i1=num_i_ref;
1845            num_i2=num_i1;
1846            num_j1=ref.num_a*ones(size(num_i_ref));
1847            num_j2=ref.num_b*ones(size(num_i_ref));
1848        elseif isequal(mode,'series(Di)') % isequal(mode,'st_series(Di)')
1849            delta1=floor((ref.num2-ref.num1)/2);
1850            delta2=ceil((ref.num2-ref.num1)/2);
1851            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
1852            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
1853            if isempty(ref.num_a)
1854                ref.num_a=1;
1855            end
1856            num_j1=ref.num_a*ones(size(num_i1));
1857            num_j2=num_j1;
1858        elseif isequal(mode,'series(Dj)')%| isequal(mode,'st_series(Dj)')
1859            delta1=floor((ref.num_b-ref.num_a)/2);
1860            delta2=ceil((ref.num_b-ref.num_a)/2);
1861            num_i1=ref.num1*ones(size(num_i_ref));
1862            num_i2=num_i1;
1863            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
1864            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
1865        end
1866        for ifile=1:nbfield
1867            for j=1:nbslice
1868                [RootPath,RootFile]=fileparts(ref.filebase);
1869                file_ref=fullfile_uvmat(RootPath,ref.subdir,RootFile,'.nc',ref.nom_type,num_i1(ifile),num_i2(ifile),num_j1(j),num_j2(j));
1870%                 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);%
1871                file_ref_fix1(ifile,j)={file_ref};
1872                if ~exist(file_ref,'file')
1873                    msgbox_uvmat('ERROR',['reference file ' file_ref ' not found for fix1'])
1874                    filecell=[];
1875                    return
1876                end
1877            end
1878        end
1879    end
1880end
1881
1882%determine reference files for checkfix2:
1883if checkbox(5)==1% fix2 performed
1884    ref=get(handles.ref_fix2,'UserData');
1885    if ~isempty(ref)
1886        first_i=str2double(get(handles.first_i,'String'));
1887        last_i=str2double(get(handles.last_i,'String'));
1888        incr_i=str2double(get(handles.incr_i,'String'));
1889        first_j=str2double(get(handles.first_j,'String'));
1890        last_j=str2double(get(handles.last_j,'String'));
1891        incr_j=str2double(get(handles.incr_j,'String'));
1892        num_i_ref=first_i:incr_i:last_i;
1893        num_j_ref=first_j:incr_j:last_j;
1894        if isequal(mode,'displacement')
1895            num_i1=num_i_ref;
1896            num_i2=num_i_ref;
1897            num_j1=num_j_ref;
1898            num_j2=num_j_ref;
1899        elseif isequal(mode,'pair j1-j2')
1900            num_i1=num_i_ref;
1901            num_i2=num_i1;
1902            num_j1=ref.num_a;
1903            num_j2=ref.num_b;
1904        elseif isequal(mode,'series(Di)')
1905            delta1=floor((ref.num2-ref.num1)/2);
1906            delta2=ceil((ref.num2-ref.num1)/2);
1907            num_i1=num_i_ref-delta1*ones(size(num_i_ref));
1908            num_i2=num_i_ref+delta2*ones(size(num_i_ref));
1909            num_j1=ref.num_a*ones(size(num_i1));
1910            num_j2=num_j1;
1911        elseif isequal(mode,'series(Dj)')
1912            delta1=floor((ref.num_b-ref.num_a)/2);
1913            delta2=ceil((ref.num_b-ref.num_a)/2);
1914            num_i1=ref.num1*ones(size(num_i_ref));
1915            num_i2=num_i1;
1916            num_j1=num_j_ref-delta1*ones(size(num_j_ref));
1917            num_j2=num_j_ref+delta2*ones(size(num_j_ref));
1918        end
1919        for ifile=1:nbfield
1920            for j=1:nbslice
1921                [RootPath,RootFile]=fileparts(ref.filebase);
1922                file_ref=fullfile_uvmat(RootPath,ref.subdir,RootFile,'.nc',ref.nom_type,num_i1(ifile),num_i2(ifile),num_j1(j),num_j2(j));
1923                %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);%
1924                file_ref_fix2(ifile,j)={file_ref};
1925                if ~exist(file_ref,'file')
1926                    msgbox_uvmat('ERROR',['reference file ' file_ref ' not found for fix2'])
1927                    filecell={};
1928                    return
1929                end
1930            end
1931        end
1932    end
1933end
1934
1935%check dir
1936subdir_civ1=get(handles.txt_SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf output data
1937subdir_civ2=get(handles.txt_SubdirCiv2,'String');
1938if isequal(subdir_civ1,''),subdir_civ1='CIV'; end% put default subdir
1939if isequal(subdir_civ2,''),subdir_civ2=subdir_civ1; end% put default subdir
1940% currentdir=pwd;%store the current working directory
1941[Path_ima,Name]=fileparts(filebase);%Path of the image files (.civ)
1942if ~exist(Path_ima,'dir')
1943    msgbox_uvmat('ERROR',['path to images ' Path_ima ' not found'])
1944    filecell={};
1945    return
1946end
1947[xx,message]=fileattrib(Path_ima);
1948if ~isempty(message) && ~isequal(message.UserWrite,1)
1949    msgbox_uvmat('ERROR',['No writting access to ' Path_ima])
1950    filecell={};
1951%     cd(currentdir);
1952    return
1953end
1954
1955%check the existence of the netcdf and image files involved
1956% %%%%%%%%%%%%  case CheckCiv1 activated   %%%%%%%%%%%%%
1957if checkbox(1)==1;
1958    detect=1;
1959    vers=0;
1960    subdir_civ1_new=subdir_civ1;
1961    while detect==1 %create a new subdir if the netcdf files already exist
1962        for ifile=1:nbfield
1963            for j=1:nbslice
1964                [RootPath,RootFile]=fileparts(filebase_nc);
1965                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));
1966               % 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);
1967                detect=exist(filename,'file')==2;
1968                if detect% if a netcdf file already exists
1969                    indstr=regexp(subdir_civ1_new,'\D');
1970                    if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
1971                        vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
1972                        subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
1973                    else
1974                        vers=vers+1;
1975                        subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) '_' num2str(vers)];       
1976                    end
1977                    subdir_civ2=subdir_civ1_new;
1978                    break
1979                end
1980                filecell.nc.civ1(ifile,j)={filename};
1981            end
1982            if detect% if a netcdf file already exists
1983                break
1984            end
1985        end
1986 
1987        %create the new txt_SubdirCiv1
1988        if ~exist(fullfile(Path_ima,subdir_civ1_new),'dir')
1989%             cd(Path_ima);         
1990            [xx,msg1]=mkdir(fullfile(Path_ima,subdir_civ1_new));
1991
1992            if ~strcmp(msg1,'')
1993                msgbox_uvmat('ERROR',['cannot create ' subdir_civ1_new ': ' msg1])%error message for directory creation
1994                filecell={};
1995                return
1996            elseif isunix         
1997                [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
1998                if ~strcmp(msg2,'')
1999                    msgbox_uvmat('ERROR',['pb of permission for  ' fullfile(Path_ima,subdir_civ1_new) ': ' msg2])%error message for directory creation
2000                    filecell={};
2001                    return
2002                end
2003            end
2004%             cd(currentdir);
2005        end
2006        if strcmp(compare,'stereo PIV')&&(strcmp(mode,'pair j1-j2')||strcmp(mode,'series(Dj)')||strcmp(mode,'series(Di)'))%check second nc series
2007            for ifile=1:nbfield
2008                for j=1:nbslice
2009                     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));
2010                   % 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);%
2011                    detect=exist(filename,'file')==2;
2012                    if detect% if a netcdf file already exists
2013                       indstr=regexp(subdir_civ1_new,'\D');
2014                       if indstr(end)<length(subdir_civ1_new) %subdir_civ1 ends by a number
2015                           vers=str2double(subdir_civ1_new(indstr(end)+1:end))+1;
2016                           subdir_civ1_new=[subdir_civ1_new(1:indstr(end)) num2str(vers)];
2017                       else
2018                           vers=vers+1;
2019                           subdir_civ1_new=[subdir_civ1_new '_' num2str(vers)];
2020                       end
2021                       subdir_civ2=subdir_civ1;
2022                       break
2023                    end
2024                    filecell.ncA.civ1(ifile,j)={filename};
2025                end
2026                if detect% if a netcdf file already exists
2027                    break
2028                end
2029            end
2030            %create the new txt_SubdirCiv1
2031            if ~exist(fullfile(Path_ima,subdir_civ1_new),'dir')
2032%                    cd(Path_ima);         
2033                [xx,msg1]=mkdir(fullfile(Path_ima,subdir_civ1_new));
2034%                             cd(currentdir);
2035                if ~strcmp(msg1,'')
2036                    msgbox_uvmat('ERROR',['cannot create ' subdir_civ1_new ': ' msg1])
2037%                     cd(currentdir)
2038                    filecell={};
2039                    return
2040                else
2041                    [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ1_new),'+w','g'); %yield writing access (+w) to user group (g)
2042                    if ~strcmp(msg2,'')
2043                        msgbox_uvmat('ERROR',['pb of permission for ' subdir_civ1_new ': ' msg2])%error message for directory creation
2044%                         cd(currentdir)
2045                        filecell={};
2046                        return
2047                    end
2048                end
2049            end
2050        end
2051    end
2052    subdir_civ1=subdir_civ1_new;
2053    % get image names
2054    for ifile=1:nbfield
2055        for j=1:nbslice
2056             filename=fullfile_uvmat(RootPath_ima1,'',RootFile_ima1,ext_ima,nom_type_ima1,num1_civ1(ifile),[],num_a_civ1(j));
2057           % filename=name_generator(filebase_ima1, num1_civ1(ifile),num_a_civ1(j),ext_ima,nom_type_ima1);
2058            idetect(j)=exist(filename,'file')==2;
2059            filecell.ima1.civ1(ifile,j)={filename}; %first image
2060            filename=fullfile_uvmat(RootPath_ima2,'',RootFile_ima2,ext_ima,nom_type_ima2,num2_civ1(ifile),[],num_b_civ1(j));
2061          %  filename=name_generator(filebase_ima2, num2_civ1(ifile),num_b_civ1(j),ext_ima,nom_type_ima2);
2062            idetect_1(j)=exist(filename,'file')==2;
2063            filecell.ima2.civ1(ifile,j)={filename};%second image
2064        end
2065        [idetectmin,indexj]=min(idetect);
2066        if idetectmin==0,
2067            msgbox_uvmat('ERROR',[filecell.ima1.civ1{ifile,indexj} ' not found'])
2068            filecell={};
2069           % cd(currentdir)
2070            return
2071        end
2072        [idetectmin,indexj]=min(idetect_1);
2073        if idetectmin==0,
2074            msgbox_uvmat('ERROR',[filecell.ima2.civ1{ifile,indexj} ' not found'])
2075            filecell={};
2076            %cd(currentdir)
2077            return
2078        end
2079    end
2080    if strcmp(compare,'stereo PIV') && (strcmp(mode,'pair j1-j2') || strcmp(mode,'series(Dj)') || strcmp(mode,'series(Di)'))
2081        for ifile=1:nbfield
2082            for j=1:nbslice
2083                filename=fullfile_uvmat(RootPath_A,'',RootFile_A,ext_ima,nom_type_ima1,num1_civ1(ifile),[],num_a_civ1(j));
2084               % filename=name_generator(filebase_A, num1_civ1(ifile),num_a_civ1(j),ext_ima,nom_type_ima1);
2085                idetect(j)=exist(filename,'file')==2;
2086                filecell.imaA1.civ1(ifile,j)={filename} ;%first image
2087                filename=fullfile_uvmat(RootPath_A,'',RootFile_A,ext_ima,nom_type_ima2,num2_civ1(ifile),[],num_b_civ1(j));
2088               % filename=name_generator(filebase_A, num2_civ1(ifile),num_b_civ1(j),ext_ima,nom_type_ima2);
2089                idetect_1(j)=exist(filename,'file')==2;
2090                filecell.imaA2.civ1(ifile,j)={filename};%second image
2091            end
2092            [idetectmin,indexj]=min(idetect);
2093            if idetectmin==0,
2094                msgbox_uvmat('ERROR',[filecell.imaA1.civ1{ifile,indexj} ' not found'])
2095                filecell={};
2096               % cd(currentdir)
2097                return
2098            end
2099            [idetectmin,indexj]=min(idetect_1);
2100            if idetectmin==0,
2101                msgbox_uvmat('ERROR',[filecell.imaA2.civ1{ifile,indexj} ' not found'])
2102                filecell={};
2103               % cd(currentdir)
2104                return
2105            end
2106        end
2107    end
2108   
2109    %%%%%%%%%%%%%  checkfix1 or checkpatch1 activated but no checkciv1   %%%%%%%%%%%%%
2110elseif (checkbox(2)==1 || checkbox(3)==1);
2111    for ifile=1:nbfield
2112        for j=1:nbslice
2113            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));
2114           % filename=name_generator(filebase_nc,num1_civ1(ifile),num_a_civ1(j),'.nc',...
2115           %     nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1);%
2116            detect=exist(filename,'file')==2;
2117            if detect==0
2118                msgbox_uvmat('ERROR',[filename ' not found'])
2119                filecell={};
2120               % cd(currentdir)
2121                return
2122            end
2123            filecell.nc.civ1(ifile,j)={filename};
2124        end
2125    end
2126    if strcmp(compare,'stereo PIV')
2127        for ifile=1:nbfield
2128            for j=1:nbslice
2129                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));
2130              %  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);%
2131                filecell.ncA.civ1(ifile,j)={filename};
2132                if ~exist(filename,'file')
2133                    msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2134                    set(handles.RUN, 'Enable','On')
2135                    set(handles.RUN,'BackgroundColor',[1 0 0])
2136                    filecell={};
2137                    %cd(currentdir)
2138                    return
2139                end
2140            end
2141        end
2142    end
2143end
2144
2145%%%%%%%%%%%%%  if checkciv2 performed with pairs different than checkciv1  %%%%%%%%%%%%%
2146testdiff=0;
2147if (checkbox(4)==1)&&...
2148        ((get(handles.ListPairCiv1,'Value')~=get(handles.ListPairCiv2,'Value'))||~strcmp(subdir_civ2,subdir_civ1))
2149    testdiff=1;
2150    detect=1;
2151    vers=0;
2152    subdir_civ2_new=subdir_civ2;
2153    while detect==1 %create a new subdir if the netcdf files already exist
2154        for ifile=1:nbfield
2155            for j=1:nbslice
2156                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));
2157               % 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);%
2158                detect=exist(filename,'file')==2;
2159                if detect% if a netcdf file already exists
2160                    indstr=regexp(subdir_civ2,'\D');
2161                    if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2162                        vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2163                        subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2164                    else
2165                        vers=vers+1;
2166                        subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2167                    end
2168                    break
2169                end
2170                filecell.nc.civ2(ifile,j)={filename};
2171            end
2172            if detect% if a netcdf file already exists
2173                break
2174            end
2175        end
2176        %create the new subdir_civ2_new
2177        if ~exist(fullfile(Path_ima,subdir_civ2_new),'dir')
2178            [xx,m2]=mkdir(fullfile(Path_ima,subdir_civ2_new));
2179            [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2180            if ~isequal(m2,'')
2181                msgbox_uvmat('ERROR',['cannot create ' fullfile(Path_ima,subdir_civ2_new) ': ' m2])
2182                filecell={};
2183               % cd(currentdir)
2184                return
2185            end
2186        end
2187        if strcmp(compare,'stereo PIV')%check second nc series
2188            for ifile=1:nbfield
2189                for j=1:nbslice
2190                    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));
2191                %   filename=name_generator(filebase_A,num1_civ2(ifile),num_a_civ2(j),'.nc',...
2192                 %       nom_type_nc,1,num2_civ2(ifile),num_b_civ1(j),subdir_civ2_new);%
2193                    detect=exist(filename,'file')==2;
2194                    if detect% if a netcdf file already exists
2195                        indstr=regexp(subdir_civ2,'\D');
2196                        if indstr(end)<length(subdir_civ2) %subdir_civ1 ends by a number
2197                           vers=str2double(subdir_civ2(indstr(end)+1:end))+1;
2198                           subdir_civ2_new=[subdir_civ2(1:indstr(end)) num2str(vers)];
2199                        else
2200                           vers=vers+1;
2201                           subdir_civ2_new=[subdir_civ1 '_' num2str(vers)];
2202                        end
2203                        break
2204                    end
2205                    filecell.ncA.civ2(ifile,j)={filename};
2206                end
2207                if detect% if a netcdf file already exists
2208                    break
2209                end
2210            end
2211            subdir_civ2=subdir_civ2_new;
2212            %create the new txt_SubdirCiv1
2213            if ~exist(fullfile(Path_ima,subdir_civ2_new),'dir')
2214                [xx,m2]=mkdir(subdir_civ2_new);
2215                 [xx,msg2] = fileattrib(fullfile(Path_ima,subdir_civ2_new),'+w','g'); %yield writing access (+w) to user group (g)
2216                if ~isequal(m2,'')
2217                    msgbox_uvmat('ERROR', ['cannot create ' fullfile(Path_ima,subdir_civ2_new) ': ' m2])%error message for directory creation
2218                  %  cd(currentdir)
2219                    filecell={};
2220                    return
2221                end
2222            end
2223        end
2224    end
2225    subdir_civ2=subdir_civ2_new;
2226end
2227%cd(currentdir);%come back to the current working directory
2228
2229%%%%%%%%%%%%%  if checkciv2 results are obtained or used  %%%%%%%%%%%%%
2230if checkbox(4)==1 || checkbox(5)==1 || checkbox(6)==1 %civ2
2231    %check source netcdf file of checkciv1 estimates
2232    if checkbox(1)==0; %no civ1 performed
2233        for ifile=1:nbfield
2234            for j=1:nbslice
2235                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));
2236                %filename=name_generator(filebase_nc,num1_civ1(ifile),num_a_civ1(j),'.nc',...
2237%                     nom_type_nc,1,num2_civ1(ifile),num_b_civ1(j),subdir_civ1);%
2238                filecell.nc.civ1(ifile,j)={filename};% name of the civ1 file
2239                if ~exist(filename,'file')
2240                    msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2241                    filecell={};
2242                    return
2243                end
2244                if ~testdiff % civ2 or patch2 are written in the same file as civ1
2245                    if checkbox(4)==0 ; %check the existence of civ2 if it is not calculated
2246                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2247                        if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2248                            msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2249                            filecell=[];
2250                            return
2251                        elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2252                            msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2253                            filecell=[];
2254                            return
2255                        end
2256                    elseif checkbox(3)==0; %check the existence of patch if it is not calculated
2257                        Data=nc2struct(filename,'ListGlobalAttribute','CivStage','patch');
2258                        if ~isempty(Data.CivStage)
2259                            if Data.CivStage<3 %test for civ files
2260                                msgbox_uvmat('ERROR',['no patch data in ' filename])
2261                                filecell=[];
2262                                return
2263                            end
2264                        elseif isempty(Data.patch)||isequal(Data.patch,0)
2265                            msgbox_uvmat('ERROR',['no patch data in ' filename])
2266                            filecell=[];
2267                            return
2268                        end
2269                    end
2270                end
2271            end
2272        end
2273        if strcmp(compare,'stereo PIV')
2274            for ifile=1:nbfield
2275                for j=1:nbslice
2276                    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));
2277                    filecell.ncA.civ2(ifile,j)={filename};
2278                    if ~exist(filename,'file')
2279                        msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2280                        set(handles.RUN, 'Enable','On')
2281                        set(handles.RUN,'BackgroundColor',[1 0 0])
2282                        return
2283                    end
2284                end
2285            end
2286        end
2287    end
2288   
2289    detect=1;
2290    %     while detect==1%creates a new subdir if the netcdf files already contain checkciv2 data
2291    for ifile=1:nbfield
2292        for j=1:nbslice
2293            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));
2294            detect=exist(filename,'file')==2;
2295            filecell.nc.civ2(ifile,j)={filename};
2296        end
2297    end
2298    %get first image names for checkciv2
2299    if checkbox(1)==1 && isequal(num1_civ1,num1_civ2) && isequal(num_a_civ1,num_a_civ2)
2300        filecell.ima1.civ2=filecell.ima1.civ1;
2301    elseif checkbox(4)==1
2302        for ifile=1:nbfield
2303            for j=1:nbslice
2304                filename=fullfile_uvmat(RootPath_ima1,[],RootFile_ima1,ext_ima,nom_type_ima1,num1_civ2(ifile),[],num_a_civ2(j));
2305                %filename=name_generator(filebase_ima1, num1_civ2(ifile),num_a_civ2(j),ext_ima,nom_type_ima1);
2306                idetect_2(j)=exist(filename,'file')==2;
2307                filecell.ima1.civ2(ifile,j)={filename};%first image
2308            end
2309            [idetectmin,indexj]=min(idetect_2);
2310            if idetectmin==0,
2311                msgbox_uvmat('ERROR',['input image ' filecell.ima1.civ2{ifile,indexj} ' not found'])
2312                filecell=[];
2313                return
2314            end
2315        end
2316    end
2317   
2318    %get second image names for checkciv2
2319    if checkbox(1)==1 && isequal(num2_civ1,num2_civ2) && isequal(num_b_civ1,num_b_civ2)
2320        filecell.ima2.civ2=filecell.ima2.civ1;
2321    elseif checkbox(4)==1
2322        for ifile=1:nbfield
2323            for j=1:nbslice
2324                filename=fullfile_uvmat(RootPath_ima2,[],RootFile_ima2,ext_ima,nom_type_ima2,num2_civ2(ifile),[],num_b_civ2(j));
2325               % filename=name_generator(filebase_ima2, num2_civ2(ifile),num_b_civ2(j),ext_ima,nom_type_ima2);
2326                idetect_3(j)=exist(filename,'file')==2;
2327                filecell.ima2.civ2(ifile,j)={filename};%first image
2328            end
2329            [idetectmin,indexj]=min(idetect_3);
2330            if idetectmin==0,
2331                msgbox_uvmat('ERROR',['input image ' filecell.ima2.civ2{ifile,indexj} ' not found'])
2332                filecell=[];
2333                return
2334            end
2335        end
2336    end
2337end
2338if (checkbox(5) || checkbox(6)) && ~checkbox(4)  % need to read an existing netcdf civ2 file
2339    if ~testdiff
2340        filecell.nc.civ2=filecell.nc.civ1;% file already checked
2341    else     % check the civ2 files
2342        for ifile=1:nbfield
2343            for j=1:nbslice
2344                 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));
2345                filecell.nc.civ2(ifile,j)={filename};
2346                if ~exist(filename,'file')
2347                    msgbox_uvmat('ERROR',['input file ' filename ' not found'])
2348                    filecell=[];
2349                    return
2350                else
2351                    Data=nc2struct(filename,'ListGlobalAttribute','CivStage','civ2');
2352                    if ~isempty(Data.CivStage) && Data.CivStage<4 %test for civ files
2353                            msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2354                            filecell=[];
2355                            return
2356                    elseif isempty(Data.civ2)||isequal(Data.civ2,0)
2357                        msgbox_uvmat('ERROR',['no civ2 data in ' filename])
2358                        filecell=[];
2359                        return
2360                    end
2361                end
2362            end
2363        end
2364    end
2365end
2366
2367%%%%%%%%%%%%%  if stereo fields are calculated by PATCH %%%%%%%%%%%%%
2368if strcmp(compare,'stereo PIV')
2369    if  checkbox(3) && isequal(get(handles.test_stereo1,'Value'),1)
2370        for ifile=1:nbfield
2371            for j=1:nbslice
2372                 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));
2373                filecell.st(ifile,j)={filename};
2374            end
2375        end
2376    end
2377    if  checkbox(6) && isequal(get(handles.CheckStereo,'Value'),1)
2378        for ifile=1:nbfield
2379            for j=1:nbslice
2380                 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));
2381                filecell.st(ifile,j)={filename};
2382            end
2383        end
2384    end
2385end
2386set(handles.txt_SubdirCiv1,'String',subdir_civ1);%update the edit box
2387set(handles.txt_SubdirCiv2,'String',subdir_civ2);%update the edit box
2388browse.nom_type_nc=nom_type_nc;
2389set(handles.RootName,'UserData',browse); %update the nomenclature type for uvmat
2390
2391
2392%COPY IMAGES TO THE FORMAT .png IF NEEDED
2393if isequal(nom_type_ima1,'*')%case of movie files
2394    nom_type_imanew1='_i';
2395else
2396    nom_type_imanew1=nom_type_ima1;
2397end
2398if isequal(nom_type_ima2,'*')%case of movie files
2399    nom_type_imanew2='_i';
2400else
2401    nom_type_imanew2=nom_type_ima2;
2402end
2403if ~isequal(ext_ima,'.png')
2404    %%type of image file
2405    type_ima1='none';%default
2406    movieobject1=[];%default
2407    if strcmpi(ext_ima,'.avi')
2408        hhh=which('mmreader');
2409        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()% if the mmreader function is found (recent version of matlab)
2410            type_ima1='movie';
2411            movieobject1=mmreader([filebase_ima2 ext_ima]);
2412        else
2413            type_ima1='avi';
2414        end
2415    elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2416        form=imformats(ext_ima(2:end));
2417        if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2418            if isequal(nom_type_ima1,'*');
2419                type_ima1='multimage';%image series in a single image file
2420            else
2421                type_ima1='image';
2422            end
2423        end
2424    end
2425    type_ima2='none';%default
2426    movieobject2=[];
2427    if strcmpi(ext_ima,'.avi')
2428        hhh=which('mmreader');
2429        if ~isequal(hhh,'')&& mmreader.isPlatformSupported()% if the mmreader function is found (recent version of matlab)
2430            type_ima2='movie';
2431            movieobject2=mmreader([filebase_ima2 ext_ima]);
2432        else
2433            type_ima2='avi';
2434        end
2435    elseif ischar(ext_ima) && ~isempty(ext_ima(2:end))
2436        form=imformats(ext_ima(2:end));
2437        if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
2438            if isequal(nom_type_ima1,'*');
2439                type_ima2='multimage';%image series in a single image file
2440            else
2441                type_ima2='image';
2442            end
2443        end
2444    end
2445    %npxy=get(handles.ImaExt,'UserData');
2446    % %     if numel(npxy)<2
2447    %
2448    %         filename=name_generator(filebase_ima1,num1_civ1(1),num_a_civ1(1),ImaExt,nom_type_ima1);
2449    %         A=imread(filename);
2450    %         npxy=size(A);
2451    % %     end
2452    %     npy=npxy(1);
2453    %     npx=npxy(2);
2454    if checkbox(1) %if civ1 is performed
2455        h = waitbar(0,'copy images to the .png format for civ1');% display a wait bar
2456        for ifile=1:nbfield
2457            waitbar(ifile/nbfield);
2458            for j=1:nbslice
2459                 filename=fullfile_uvmat(RootPath_ima1,[],RootFile_ima1,'.png',nom_type_imanew1,num1_civ1(ifile),[],num_a_civ1(j));
2460%                 filename=name_generator(filebase_ima1,num1_civ1(ifile),num_a_civ1(j),'.png',nom_type_imanew1);
2461                if ~exist(filename,'file')
2462                    A=read_image(filecell.ima1.civ1{ifile,j},type_ima1,num1_civ1(ifile),movieobject1);
2463                    imwrite(A,filename,'BitDepth',16);
2464                end
2465                filecell.ima1.civ1(ifile,j)={filename};
2466                filename=fullfile_uvmat(RootPath_ima2,[],RootFile_ima2,'.png',nom_type_imanew2,num2_civ1(ifile),[],num_b_civ1(j));
2467                %filename=name_generator(filebase_ima2, num2_civ1(ifile),num_b_civ1(j),'.png',nom_type_imanew2);
2468                if ~exist(filename,'file')
2469                    A=read_image(filecell.ima2.civ1{ifile,j},type_ima2,num2_civ1(ifile),movieobject2);
2470                    imwrite(A,filename,'BitDepth',16);
2471                end
2472                filecell.ima2.civ1(ifile,j)={filename};
2473            end
2474        end
2475        close(h)
2476    end
2477    if checkbox(4) %if civ2 is performed
2478        h = waitbar(0,'copy images to the .png format for civ2');% display a wait bar
2479        for ifile=1:nbfield
2480            waitbar(ifile/nbfield);
2481            for j=1:nbslice
2482                filename=fullfile_uvmat(RootPath_ima1,[],RootFile_ima1,'.png',nom_type_imanew1,num1_civ2(ifile),[],num_a_civ2(j));
2483                %filename=name_generator(filebase_ima1,num1_civ2(ifile),num_a_civ2(j),'.png',nom_type_imanew1);
2484                if ~exist(filename,'file')
2485                    A=read_image(cell2mat(filecell.ima1.civ2(ifile,j)),type_ima2,num1_civ2(ifile));
2486                    imwrite(A,filename,'BitDepth',16);
2487                end
2488                filecell.ima1.civ2(ifile,j)={filename};
2489                filename=fullfile_uvmat(RootPath_ima2,[],RootFile_ima2,'.png',nom_type_imanew2,num2_civ2(ifile),[],num_b_civ2(j));
2490               % filename=name_generator(filebase_ima2, num2_civ2(ifile),num_b_civ2(j),'.png',nom_type_imanew2);
2491                if ~exist(filename,'file')
2492                    A=read_image(cell2mat(filecell.ima2.civ2(ifile,j)),type_ima2,num2_civ2(ifile));
2493                    imwrite(A,filename,'BitDepth',16);
2494                end
2495                filecell.ima2.civ2(ifile,j)={filename};
2496            end
2497        end
2498        close(h);
2499    end
2500end
2501
2502%------------------------------------------------------------------------
2503% --- determine the list of index pairs of processing file
2504function [num1_civ1,num2_civ1,num_a_civ1,num_b_civ1,num1_civ2,num2_civ2,num_a_civ2,num_b_civ2]=...
2505    find_pair_indices(handles,ref_i,ref_j,mode)
2506%------------------------------------------------------------------------
2507
2508list_civ1=get(handles.ListPairCiv1,'String');
2509index_civ1=get(handles.ListPairCiv1,'Value');
2510str_civ1=list_civ1{index_civ1};%string defining the image pairs for civ1
2511if isempty(str_civ1)||isequal(str_civ1,'')
2512    msgbox_uvmat('ERROR','no image pair selected for civ1')
2513    return
2514end
2515list_civ2=get(handles.ListPairCiv2,'String');
2516index_civ2=get(handles.ListPairCiv2,'Value');
2517if index_civ2>length(list_civ2)
2518    list_civ2=list_civ1;
2519    index_civ2=index_civ1;
2520end
2521str_civ2=list_civ2{index_civ2};%string defining the image pairs for civ2
2522
2523if isequal (mode,'series(Di)')
2524    lastfield=str2double(get(handles.nb_field,'String'));
2525    num1_civ1=ref_i-floor(index_civ1/2)*ones(size(ref_i));% set of first image numbers
2526    num2_civ1=ref_i+ceil(index_civ1/2)*ones(size(ref_i));
2527    num_a_civ1=ref_j;
2528    num_b_civ1=ref_j;
2529    num1_civ2=ref_i-floor(index_civ2/2)*ones(size(ref_i));
2530    num2_civ2=ref_i+ceil(index_civ2/2)*ones(size(ref_i));
2531    num_a_civ2=ref_j;
2532    num_b_civ2=ref_j;   
2533   
2534    % adjust the first and last field number
2535    lastfield=str2double(get(handles.nb_field,'String'));
2536    if isnan(lastfield)
2537        indsel=find((num1_civ1 >= 1)&(num1_civ2 >= 1));
2538    else
2539        indsel=find((num2_civ1 <= lastfield)&(num2_civ2 <= lastfield)&(num1_civ1 >= 1)&(num1_civ2 >= 1));
2540    end
2541    if length(indsel)>=1
2542        firstind=indsel(1);
2543        lastind=indsel(end);
2544        set(handles.first_i,'String',num2str(ref_i(firstind)))%update the display of first and last fields
2545        set(handles.last_i,'String',num2str(ref_i(lastind)))
2546        ref_i=ref_i(indsel);
2547        num1_civ1=num1_civ1(indsel);
2548        num1_civ2=num1_civ2(indsel);
2549        num2_civ1=num2_civ1(indsel);
2550        num2_civ2=num2_civ2(indsel);
2551    end
2552elseif isequal (mode,'series(Dj)')
2553    lastfield_j=str2double(get(handles.nb_field2,'String'));
2554    num1_civ1=ref_i;% set of first image numbers
2555    num2_civ1=ref_i;
2556    num_a_civ1=ref_j-floor(index_civ1/2)*ones(size(ref_j));
2557    num_b_civ1=ref_j+ceil(index_civ1/2)*ones(size(ref_j));
2558    num1_civ2=ref_i;
2559    num2_civ2=ref_i;
2560    num_a_civ2=ref_j-floor(index_civ2/2)*ones(size(ref_j));
2561    num_b_civ2=ref_j+ceil(index_civ2/2)*ones(size(ref_j));
2562    % adjust the first and last field number
2563    if isnan(lastfield_j)
2564        indsel=find((num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2565    else
2566        indsel=find((num_b_civ1 <= lastfield_j)&(num_b_civ2 <= lastfield_j)&(num_a_civ1 >= 1)&(num_a_civ2 >= 1));
2567    end
2568    if length(indsel)>=1
2569        firstind=indsel(1);
2570        lastind=indsel(end);
2571        set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
2572        set(handles.last_j,'String',num2str(ref_j(lastind)))
2573        ref_j=ref_j(indsel);
2574        num_a_civ1=num_a_civ1(indsel);
2575        num_b_civ1=num_b_civ1(indsel);
2576        num_a_civ2=num_a_civ2(indsel);
2577        num_b_civ2=num_b_civ2(indsel);
2578    end
2579elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
2580    displ_num=get(handles.ListPairCiv1,'UserData');
2581    num1_civ1=ref_i;
2582    num2_civ1=ref_i;
2583    num_a_civ1=displ_num(1,index_civ1);
2584    num_b_civ1=displ_num(2,index_civ1);
2585    num1_civ2=ref_i;
2586    num2_civ2=ref_i;
2587    num_a_civ2=displ_num(1,index_civ2);
2588    num_b_civ2=displ_num(2,index_civ2);
2589elseif isequal(mode,'displacement')
2590    num1_civ1=ref_i;
2591    num2_civ1=ref_i;
2592    num_a_civ1=ref_j;
2593    num_b_civ1=ref_j;
2594    num1_civ2=ref_i;
2595    num2_civ2=ref_i;
2596    num_a_civ2=ref_j;
2597    num_b_civ2=ref_j;
2598end
2599
2600%------------------------------------------------------------------------
2601% --- Executes on button press in ListCompareMode.
2602function ListCompareMode_Callback(hObject, eventdata, handles)
2603%------------------------------------------------------------------------
2604menu=get(handles.ListCompareMode,'String');
2605val=get(handles.ListCompareMode,'Value');
2606option=menu{val};
2607if ~strcmp(option,'PIV') % case 'displacement' or 'stereo PIV'
2608    filebase=get(handles.RootName,'String');
2609    browse=get(handles.RootName,'Userdata');
2610   % browse.nom_type_ima1=browse.nom_type_ima;
2611    set(handles.RootName,'UserData',browse);
2612    set(handles.sub_txt,'Visible','on')
2613    set(handles.RootName_1,'Visible','On');%mkes the second file input window visible
2614    mode_store=get(handles.ListPairMode,'String');%get the present 'mode'
2615    set(handles.ListCompareMode,'UserData',mode_store);%store the mode display
2616    set(handles.ListPairMode,'Visible','off')
2617    if test==2
2618        set(handles.ListPairMode,'Visible','off')
2619        set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2620    else
2621        set(handles.ListPairMode,'Visible','on')
2622        set(handles.ListPairMode,'Value',3) % mode 'Matlab' selected for stereo
2623    end
2624   
2625    %% menuopen an image file with the browser
2626    ind_opening=1;%default
2627    browse.incr_pair=[0 0]; %default
2628    oldfile=get(handles.RootName,'String');
2629     menu={'*.xml;*.civ;*.png;*.jpg;*.tif;*.avi;*.AVI;*.nc;', ' (*.xml,*.civ,*.png,*.jpg ,.tif, *.avi,*.nc)';
2630       '*.xml',  '.xml files '; ...
2631        '*.civ',  '.civ files '; ...
2632        '*.png','.png image files'; ...
2633        '*.jpg',' jpeg image files'; ...
2634        '*.tif','.tif image files'; ...
2635        '*.avi;*.AVI','.avi movie files'; ...
2636        '*.nc','.netcdf files'; ...
2637        '*.*',  'All Files (*.*)'};
2638    [FileName, PathName, filtindex] = uigetfile( menu, 'Pick a file of the second series',oldfile);
2639    fileinput=[PathName FileName];%complete file name
2640    sizf=size(fileinput);
2641    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
2642    [path,name,ext]=fileparts(fileinput);
2643    [path1]=fileparts(filebase);
2644    if isunix
2645        [status,path]=system(['readlink ' path]);
2646        [status,path1]=system(['readlink ' path1]);% look for the true path in case of symbolic paths
2647    end
2648    if ~strcmp(path1,path)
2649        msgbox_uvmat('ERROR','The second image series must be in the same directory as the first one')
2650        return
2651    end
2652    [tild,tild,RootFile,tild,tild,tild,tild,tild,nom_type]=fileparts_uvmat(name);
2653    set(handles.RootName_1,'String',RootFile);
2654    browse=get(handles.RootName,'UserData');
2655    %browse.nom_type_ima_1=nom_type;
2656    set(handles.RootName,'UserData',browse)
2657   
2658    %check image extension
2659    if ~strcmp(ext,get(handles.ImaExt,'String'))
2660        msgbox_uvmat('ERROR','The second image series must have the same extension name as the first one')
2661        return
2662    end
2663
2664else
2665    set(handles.ListPairMode,'Visible','on')
2666    set(handles.RootName_1,'Visible','Off');
2667    set(handles.sub_txt,'Visible','off')
2668    set(handles.RootName_1,'String',[]);
2669    mode_store=get(handles.ListCompareMode,'UserData');
2670    set(handles.ListPairMode,'Value',1)
2671    set(handles.ListPairMode,'String',mode_store)
2672    set(handles.CheckStereo,'Value',0)
2673    set(handles.ListPairMode,'Value',1) % mode 'civX' selected by default
2674end
2675if strcmp(option,'stereo PIV') && get(handles.CheckPatch1,'Value')
2676    set(handles.CheckStereo,'Visible','on')
2677else
2678    set(handles.CheckStereo,'Visible','off')
2679end
2680if strcmp(option,'stereo PIV') && get(handles.CheckPatch2,'Value')
2681    set(handles.CheckStereo,'Visible','on')
2682else
2683    set(handles.CheckStereo,'Visible','off')
2684end
2685ListPairMode_Callback(hObject, eventdata, handles)
2686
2687
2688%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2689% Callbacks in the uipanel Pair Indices
2690%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2691%------------------------------------------------------------------------
2692% --- Executes on button press in ListPairMode.
2693function ListPairMode_Callback(hObject, eventdata, handles)
2694%------------------------------------------------------------------------
2695compare_list=get(handles.ListCompareMode,'String');
2696val=get(handles.ListCompareMode,'Value');
2697compare=compare_list{val};
2698if strcmp(compare,'displacement')||strcmp(compare,'shift')
2699    mode='displacement';
2700else
2701    mode_list=get(handles.ListPairMode,'String');
2702    if ischar(mode_list)
2703        mode_list={mode_list};
2704    end
2705    mode_value=get(handles.ListPairMode,'Value');
2706    mode=mode_list{mode_value};
2707end
2708displ_num=[];%default
2709ref_i=str2double(get(handles.ref_i,'String'));
2710% last_i=str2num(get(handles.last_i,'String'));
2711time=get(handles.ImaDoc,'UserData'); %get the set of times
2712TimeUnit=get(handles.TimeUnit,'String');
2713checkframe=strcmp(TimeUnit,'frame');
2714siztime=size(time);
2715nbfield=siztime(1)-1;
2716nbfield2=siztime(2)-1;
2717indchosen=1;  %%first pair selected by default
2718%displ_num used to define the indices of the civ pairs
2719% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
2720% are relative to the reference indices ref_i and ref_j respectively.
2721if isequal(mode,'pair j1-j2')%| isequal(mode,'st_pair j1-j2')
2722    dt=1;
2723    displ='';
2724    index=0;
2725    numlist_a=[];
2726    numlist_B=[];
2727    %get all the time intervals in bursts
2728    displ_dt=1;%default
2729    nbfield2=min(nbfield2,10);%limitate the number of pairs to 10x10
2730    for numod_a=1:nbfield2-1 %nbfield2 always >=2 for 'pair j1-j2' mode
2731        for numod_b=(numod_a+1):nbfield2
2732            index=index+1;
2733            numlist_a(index)=numod_a;
2734            numlist_b(index)=numod_b;
2735            if size(time,2)>1 && ~checkframe
2736                dt(numod_a,numod_b)=time(ref_i+1,numod_b+1)-time(ref_i+1,numod_a+1);%first time interval dt
2737                displ_dt(index)=dt(numod_a,numod_b);
2738            else
2739                displ_dt(index)=1;
2740            end
2741        end
2742    end
2743    [dtsort,indsort]=sort(displ_dt);
2744    if ~isempty(numlist_a)
2745        displ_num(1,:)=numlist_a(indsort);
2746        displ_num(2,:)=numlist_b(indsort);
2747    end
2748    displ_num(3,:)=0;
2749    displ_num(4,:)=0;
2750    enable_j(handles, 'off')
2751elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)')
2752    index=1:200;
2753    displ_num(1,index)=-floor(index/2);
2754    displ_num(2,index)=ceil(index/2);
2755    displ_num(3:4,index)=zeros(2,200);
2756    enable_j(handles, 'on')
2757elseif isequal(mode,'series(Di)') %| isequal(mode,'st_series(Di)')
2758    index=1:200;
2759    displ_num(1:2,index)=zeros(2,200);
2760    displ_num(3,index)=-floor(index/2);
2761    displ_num(4,index)=ceil(index/2);
2762    enable_i(handles, 'on')
2763    if nbfield2 > 1
2764        enable_j(handles, 'on')
2765    else
2766        enable_j(handles, 'off')
2767    end
2768elseif isequal(mode,'displacement')%the pairs have the same indices
2769    displ_num(1,1)=0;
2770    displ_num(2,1)=0;
2771    displ_num(3,1)=0;
2772    displ_num(4,1)=0;
2773    if nbfield > 1 || nbfield==0
2774        enable_i(handles, 'on')
2775    else
2776        enable_j(handles, 'off')
2777    end
2778    if nbfield2 > 1
2779        enable_j(handles, 'on')
2780    else
2781        enable_j(handles, 'off')
2782    end
2783end
2784set(handles.ListPairCiv1,'UserData',displ_num);
2785errormsg=find_netcpair_civ( handles,1);
2786    if ~isempty(errormsg)
2787    msgbox_uvmat('ERROR',errormsg)
2788    end
2789% find_netcpair_civ2(handles)
2790
2791function enable_i(handles, state)
2792set(handles.itext,'Visible',state)
2793set(handles.first_i,'Visible',state)
2794set(handles.last_i,'Visible',state)
2795set(handles.incr_i,'Visible',state)
2796set(handles.nb_field,'Visible',state)
2797set(handles.ref_i,'Visible',state)
2798
2799function enable_j(handles, state)
2800set(handles.jtext,'Visible',state)
2801set(handles.first_j,'Visible',state)
2802set(handles.last_j,'Visible',state)
2803set(handles.incr_j,'Visible',state)
2804set(handles.nb_field2,'Visible',state)
2805set(handles.ref_j,'Visible',state)
2806
2807
2808%------------------------------------------------------------------------
2809% --- Executes on selection change in ListPairCiv1.
2810function ListPairCiv1_Callback(hObject, eventdata, handles)
2811%------------------------------------------------------------------------
2812%reproduce by default the chosen pair in the checkciv2 menu
2813list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
2814index_pair=get(handles.ListPairCiv1,'Value');
2815displ_num=get(handles.ListPairCiv1,'UserData');
2816% num_a=displ_num(1,index_pair);
2817% num_b=displ_num(2,index_pair);
2818list_pair2=get(handles.ListPairCiv2,'String');%get the menu of image pairs
2819if index_pair<=length(list_pair2)
2820    set(handles.ListPairCiv2,'Value',index_pair);
2821end
2822
2823%update first_i and last_i according to the chosen image pairs
2824mode_list=get(handles.ListPairMode,'String');
2825mode_value=get(handles.ListPairMode,'Value');
2826mode=mode_list{mode_value};
2827if isequal(mode,'series(Di)')
2828    first_i=str2double(get(handles.first_i,'String'));
2829    last_i=str2double(get(handles.last_i,'String'));
2830    incr_i=str2double(get(handles.incr_i,'String'));
2831    num1=first_i:incr_i:last_i;
2832    lastfield=str2double(get(handles.nb_field,'String'));
2833    if ~isnan(lastfield)
2834        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2835            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2836        num1=num1(test_find);
2837    end
2838    set(handles.first_i,'String',num2str(num1(1)));
2839    set(handles.last_i,'String',num2str(num1(end)));
2840elseif isequal(mode,'series(Dj)')
2841    first_j=str2double(get(handles.first_j,'String'));
2842    last_j=str2double(get(handles.last_j,'String'));
2843    incr_j=str2double(get(handles.incr_j,'String'));
2844    num_j=first_j:incr_j:last_j;
2845    lastfield2=str2double(get(handles.nb_field2,'String'));
2846    if ~isnan(lastfield2)
2847        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2848            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2849        num1=num_j(test_find);
2850    end
2851    set(handles.first_j,'String',num2str(num1(1)));
2852    set(handles.last_j,'String',num2str(num1(end)));
2853end
2854
2855%------------------------------------------------------------------------
2856% --- Executes on selection change in ListPairCiv2.
2857function ListPairCiv2_Callback(hObject, eventdata, handles)
2858%------------------------------------------------------------------------
2859index_pair=get(handles.ListPairCiv2,'Value');%get the selected position index in the menu
2860
2861%update first_i and last_i according to the chosen image pairs
2862mode_list=get(handles.ListPairMode,'String');
2863mode_value=get(handles.ListPairMode,'Value');
2864mode=mode_list{mode_value};
2865if isequal(mode,'series(Di)')
2866    first_i=str2double(get(handles.first_i,'String'));
2867    last_i=str2double(get(handles.last_i,'String'));
2868    incr_i=str2double(get(handles.incr_i,'String'));
2869    num1=first_i:incr_i:last_i;
2870    lastfield=str2double(get(handles.nb_field,'String'));
2871    if ~isnan(lastfield)
2872        test_find=(num1-floor(index_pair/2)*ones(size(num1))>0)& ...
2873            (num1+ceil(index_pair/2)*ones(size(num1))<=lastfield);
2874        num1=num1(test_find);
2875    end
2876    set(handles.first_i,'String',num2str(num1(1)));
2877    set(handles.last_i,'String',num2str(num1(end)));
2878elseif isequal(mode,'series(Dj)')
2879    first_j=str2double(get(handles.first_j,'String'));
2880    last_j=str2double(get(handles.last_j,'String'));
2881    incr_j=str2double(get(handles.incr_j,'String'));
2882    num_j=first_j:incr_j:last_j;
2883    lastfield2=str2double(get(handles.nb_field2,'String'));
2884    if ~isnan(lastfield2)
2885        test_find=(num_j-floor(index_pair/2)*ones(size(num_j))>0)& ...
2886            (num_j+ceil(index_pair/2)*ones(size(num_j))<=lastfield2);
2887        num1=num_j(test_find);
2888    end
2889    set(handles.first_j,'String',num2str(num1(1)));
2890    set(handles.last_j,'String',num2str(num1(end)));
2891end
2892
2893%------------------------------------------------------------------------
2894function ref_i_Callback(hObject, eventdata, handles)
2895%------------------------------------------------------------------------
2896mode_list=get(handles.ListPairMode,'String');
2897mode_value=get(handles.ListPairMode,'Value');
2898mode=mode_list{mode_value};
2899errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2900if isequal(mode,'series(Di)') || ...% we do patch2 only
2901        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2902    errormsg=find_netcpair_civ( handles,2);
2903end
2904    if ~isempty(errormsg)
2905    msgbox_uvmat('ERROR',errormsg)
2906    end
2907
2908%------------------------------------------------------------------------
2909function ref_j_Callback(hObject, eventdata, handles)
2910%------------------------------------------------------------------------
2911mode_list=get(handles.ListPairMode,'String');
2912mode_value=get(handles.ListPairMode,'Value');
2913mode=mode_list{mode_value};
2914if isequal(get(handles.CheckCiv1,'Value'),0)|| isequal(mode,'series(Dj)')
2915    errormsg=find_netcpair_civ(handles,1);% update the menu of pairs depending on the available netcdf files
2916end
2917if isequal(mode,'series(Dj)') || ...
2918        (get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0)
2919    errormsg=find_netcpair_civ(handles,2);
2920end
2921    if ~isempty(errormsg)
2922    msgbox_uvmat('ERROR',errormsg)
2923    end
2924
2925%------------------------------------------------------------------------
2926% determine the menu for checkciv1 pairs depending on existing netcdf file at the middle of
2927% the field series set by first_i, incr, last_i
2928function errormsg=find_netcpair_civ(handles,index)
2929%------------------------------------------------------------------------
2930set(gcf,'Pointer','watch')% set the mouse pointer to 'watch' (clock)
2931
2932%% initialisation
2933errormsg='';
2934filebase=get(handles.RootName,'String');
2935[filepath,Nme,ext_dir]=fileparts(filebase);
2936browse=get(handles.RootName,'UserData');
2937compare_list=get(handles.ListCompareMode,'String');
2938val=get(handles.ListCompareMode,'Value');
2939compare=compare_list{val};
2940if strcmp(compare,'displacement')
2941    mode='displacement';
2942else
2943    mode_list=get(handles.ListPairMode,'String');
2944    mode_value=get(handles.ListPairMode,'Value');
2945    if isempty(mode_list)
2946        return
2947    end
2948    mode=mode_list{mode_value};
2949end
2950nom_type_ima=get(handles.NomType,'String');
2951
2952%% determine nom_type_nc, nomenclature type of the .nc files:
2953% nom_type_nc='';%default
2954% if isfield(browse,'nom_type_nc')
2955%     nom_type_nc=browse.nom_type_nc;
2956% end
2957% if isempty(nom_type_nc)
2958    [nom_type_nc]=nomtype2pair(nom_type_ima,mode);
2959% end
2960% browse.nom_type_nc=nom_type_nc;
2961% set(handles.RootName,'UserData',browse)
2962
2963%% reads .nc subdirectoy and image numbers from the interface
2964subdir_civ1=get(handles.txt_SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
2965subdir_civ2=get(handles.txt_SubdirCiv2,'String');%subdirectory subdir_civ2 for the netcdf data
2966ref_i=str2double(get(handles.ref_i,'String'));
2967if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
2968    ref_j=0;
2969else
2970    ref_j=str2double(get(handles.ref_j,'String'));
2971end
2972time=get(handles.ImaDoc,'UserData');%get the set of times
2973TimeUnit=get(handles.TimeUnit,'String');
2974checkframe=strcmp(TimeUnit,'frame');
2975displ_num=get(handles.ListPairCiv1,'UserData');
2976
2977%% eliminate the first pairs inconsistent with the position
2978if isempty(displ_num)
2979    nbpair=0;
2980else
2981    nbpair=length(displ_num(1,:));%nbre of displayed pairs
2982    if  isequal(mode,'series(Di)')  %| isequal(mode,'st_series(Di)')
2983        nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
2984    elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
2985        nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
2986    end
2987end
2988nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
2989
2990%% case with no Civ1 operation, netcdf files need to exist for reading
2991% be performed, while the result is needed for next steps.
2992displ_pair={''};
2993select=ones(size(1:nbpair));%flag for displayed pairs =1 for display
2994testpair=0;
2995[RootPath,RootFile]=fileparts(filebase);
2996if index==1 % case civ1
2997    if ~get(handles.CheckCiv1,'Value') %
2998        if ~exist(fullfile(filepath,subdir_civ1,ext_dir),'dir')
2999            errormsg=['no civ1 file available: subdirectory ' subdir_civ1 ' does not exist'];
3000            set(handles.ListPairCiv1,'String',{});
3001            return
3002        end
3003        for ipair=1:nbpair
3004            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3005                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3006            select(ipair)=exist(filename,'file')==2;% put flag to 0 if the file does not exist
3007        end
3008        % case of no displayed pair
3009        if isequal(select,zeros(size(1:nbpair)))
3010            if isfield(browse,'incr_pair') && ~isequal(browse.incr_pair,[0 0])
3011                num_i1=ref_i-floor(browse.incr_pair(1)/2);
3012                num_i2=ref_i+ceil(browse.incr_pair(1)/2);
3013                num_j1=ref_j-floor(browse.incr_pair(2)/2);
3014                num_j2=ref_j+ceil(browse.incr_pair(2)/2);
3015                filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3016                select(1)=exist(filename,'file')==2;
3017                testpair=1;
3018            else
3019                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3020                    errormsg=['no civ1 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ1];
3021                else
3022                    errormsg=['no civ1 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ1];
3023                end
3024                set(handles.ListPairCiv1,'String',{''});
3025                %COMPLETER CAS STEREO
3026                return
3027            end
3028        end
3029    end
3030else %case civ2 alone
3031    if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
3032        if ~exist(fullfile(filepath,subdir_civ2,ext_dir),'dir')
3033            errordlg(['no civ2 file available: subdirectory ' subdir_civ2 ' does not exist'])
3034            set(handles.ListPairCiv2,'Value',1);
3035            set(handles.ListPairCiv2,'String',{''});
3036            return
3037        end
3038        for ipair=1:nbpair
3039            filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3040                ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3041            select(ipair)=exist(filename,'file')==2;
3042        end
3043        if  isequal(select,zeros(size(1:nbpair)))
3044            if isfield(browse,'incr_pair')
3045                num_i1=ref_i-floor(browse.incr_pair(1)/2);
3046                num_i2=ref_i+floor((browse.incr_pair(1)+1)/2);
3047                num_j1=ref_j-floor(browse.incr_pair(2)/2);
3048                num_j2=ref_j+floor((browse.incr_pair(2)+1)/2);
3049                filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3050                select(1)=exist(filename,'file')==2;
3051            else
3052                if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3053                    errormsg=['no civ2 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ2];
3054                else
3055                    errormsg=['no civ2 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ2];
3056                end
3057                set(handles.ListPairCiv2,'Value',1);
3058                set(handles.ListPairCiv2,'String',{''});
3059                return
3060            end
3061        end
3062    end
3063end
3064
3065%% determine the menu display in .ListPairCiv1
3066% the menu depends on the mode defined in ListPairMode_callback through the array displ_num:
3067% displ_num(1,:)=indices j1
3068% displ_num(2,:)=indices j2
3069% displ_num(3,:)=indices i1
3070% displ_num(4,:)=indices i2
3071% in mode 'pair j1-j2', j1 and j2 are the file indices, else the indices
3072% are relative to the reference indices ref_i and ref_j respectively.
3073if isequal(mode,'series(Di)')
3074    if testpair
3075        displ_pair{1}=['Di= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3076    else
3077        for ipair=1:nbpair
3078            if select(ipair)
3079                displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3080                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
3081                    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
3082                else
3083                    dt=1;
3084                end
3085                 displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3086            else
3087                displ_pair{ipair}='...'; %pair not displayed in the menu
3088            end
3089        end
3090    end
3091elseif isequal(mode,'series(Dj)')
3092    if testpair
3093        displ_pair{1}=['Dj= ' num2str(-floor(browse.incr_pair(1)/2)) '|' num2str(ceil(browse.incr_pair(1)/2))];
3094    else
3095        for ipair=1:nbpair
3096            if select(ipair)
3097                displ_pair{ipair}=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2))];
3098                if ~checkframe && size(time,1)>=ref_i+1+displ_num(4,ipair) && size(time,2)>=ref_j+1+displ_num(2,ipair)
3099                    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
3100                    displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3101                end
3102            else
3103                displ_pair{ipair}='...'; %pair not displayed in the menu
3104            end
3105        end
3106    end
3107elseif isequal(mode,'pair j1-j2')%case of pairs
3108    for ipair=1:nbpair
3109        if select(ipair)
3110            if ~checkframe && size(time,2)>1
3111            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
3112            else % time set by default to i index
3113                dt=1;
3114            end
3115            displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair),nom_type_ima) '-' num2stra(displ_num(2,ipair),nom_type_ima) ...
3116                ' :dt= ' num2str(dt*1000)];
3117        else
3118            displ_pair{ipair}='...'; %pair not displayed in the menu
3119        end
3120    end
3121elseif isequal(mode,'displacement')
3122    displ_pair={'Di=Dj=0'};
3123end
3124if index==1
3125set(handles.ListPairCiv1,'String',displ_pair');
3126end
3127
3128%% determine the default selection in the pair menu
3129ichoice=find(select,1);% index of selected pair
3130if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3131initial=get(handles.ListPairCiv1,'Value');%initial choice of pair
3132if initial>nbpair || (numel(select)>=initial && ~isequal(select(initial),1))
3133    set(handles.ListPairCiv1,'Value',ichoice);% first valid pair proposed by default in the menu
3134end
3135initial=get(handles.ListPairCiv2,'Value');
3136if initial>length(displ_pair')%|~isequal(select(initial),1)
3137    if ichoice <= length(displ_pair')
3138        set(handles.ListPairCiv2,'Value',ichoice);% same pair proposed by default for civ2
3139    else
3140        set(handles.ListPairCiv2,'Value',1);% same pair proposed by default for civ2
3141    end
3142end
3143set(handles.ListPairCiv2,'String',displ_pair');
3144set(gcf,'Pointer','arrow')
3145
3146%------------------------------------------------------------------------
3147% determine the menu for checkciv2 pairs depending on the existing netcdf file at the
3148%middle of the series set by first_i, incr, last_i
3149% function find_netcpair_civ2(handles)
3150% %------------------------------------------------------------------------
3151% set(gcf,'Pointer','watch')
3152% %nomenclature types
3153% filebase=get(handles.RootName,'String');
3154% [filepath,Nme,ext_dir]=fileparts(filebase);
3155% browse=get(handles.RootName,'UserData');
3156% compare_list=get(handles.ListCompareMode,'String');
3157% val=get(handles.ListCompareMode,'Value');
3158% compare=compare_list{val};
3159% if strcmp(compare,'displacement')
3160%     mode='displacement';
3161% else
3162%     mode_list=get(handles.ListPairMode,'String');
3163%     if isempty(mode_list)
3164%         msgbox_uvmat('ERROR','please enter an input image or netcdf file')
3165%         return
3166%     end
3167%     mode_value=get(handles.ListPairMode,'Value');
3168%     mode=mode_list{mode_value};
3169% end
3170%
3171% % nomenclature type of the .nc files
3172% nom_type_ima='ima_num';%default
3173% NomTypeIma=get(handles.NomType,'String');
3174% nom_type_nc='_1-2';%default
3175% if isfield(browse,'nom_type_nc')
3176%     nom_type_nc=browse.nom_type_nc;
3177% end
3178% 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')
3179%     nom_type_nc='netc_old';%nom_type for the netcdf files
3180% elseif isequal(nom_type_ima,'none')||isequal(nom_type_nc,'none')
3181%     nom_type_nc='none';
3182% elseif isequal(nom_type_ima,'avi')||isequal(nom_type_ima,'_i')||isequal(nom_type_ima,'ima_num')||isequal(nom_type_nc,'_1-2')
3183%     nom_type_nc='_1-2';
3184% else
3185%     if  isequal(mode,'series(Di)')%|isequal(mode,'st_series(Di)')
3186%         nom_type_nc='_1-2_1'; % PIV in volume
3187%     else
3188%         nom_type_nc='_1_1-2';
3189%     end
3190% end
3191% browse.nom_type_nc=nom_type_nc;
3192% set(handles.RootName,'UserData',browse)
3193%
3194% %reads .nc subdirectory and image numbers from the interface
3195% subdir_civ1=get(handles.txt_SubdirCiv1,'String');%subdirectory subdir_civ1 for the netcdf data
3196% subdir_civ2=get(handles.txt_SubdirCiv2,'String');%subdirectory subdir_civ2 for the netcdf data
3197% ref_i=str2double(get(handles.ref_i,'String'));
3198% if isequal(mode,'pair j1-j2')%|isequal(mode,'st_pair j1-j2')
3199%     ref_j=0;
3200% else
3201%     ref_j=str2double(get(handles.ref_j,'String'));
3202% end
3203% time=get(handles.ImaDoc,'UserData'); %get the set of times
3204% TimeUnit=get(handles.TimeUnit,'String');
3205% checkframe=strcmp(TimeUnit,'frame');
3206% % if isempty(time)
3207% %     time=[0 1];%default
3208% % end
3209% displ_num=get(handles.ListPairCiv1,'UserData');
3210%
3211% %eliminate the first pairs inconsistent with the position
3212% if isempty(displ_num)
3213%     nbpair=0;
3214% else
3215%     nbpair=length(displ_num(1,:));%nbre of displayed pairs
3216%     if  isequal(mode,'series(Di)')% | isequal(mode,'st_series(Di)')
3217%         nbpair=min(2*ref_i-1,nbpair);%limit the number of pairs with positive first index
3218%     elseif  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3219%         nbpair=min(2*ref_j-1,nbpair);%limit the number of pairs with positive first index
3220%     end
3221% end
3222% nbpair=min(200,nbpair);%limit the number of displayed pairs to 200
3223%
3224% %% look for existing processed pairs at the reference indices if Civ1 will not
3225% % be performed, while the result is needed for next steps.
3226% displ_pair={''}; %default
3227% select=ones(size(1:nbpair));%default =1 for numbers of displayed pairs
3228% [RootPath,RootFile]=fileparts(filebase);
3229% if ~get(handles.CheckCiv2,'Value') && ~get(handles.CheckCiv1,'Value') && ~get(handles.CheckFix1,'Value') && ~get(handles.CheckPatch1,'Value')
3230%     if ~exist(fullfile(filepath,subdir_civ2,ext_dir),'dir')
3231%         errordlg(['no civ2 file available: subdirectory ' subdir_civ2 ' does not exist'])
3232%         set(handles.ListPairCiv2,'Value',1);
3233%         set(handles.ListPairCiv2,'String',{''});
3234%         return
3235%     end
3236%     for ipair=1:nbpair
3237%         filename=fullfile_uvmat(RootPath,subdir_civ1,RootFile,'.nc',nom_type_nc,...
3238%             ref_i+displ_num(3,ipair),ref_i+displ_num(4,ipair),ref_j+displ_num(1,ipair),ref_j+displ_num(2,ipair));
3239%        % filename=name_generator(filebase,ref_i+displ_num(3,ipair),ref_j+displ_num(1,ipair),'.nc',nom_type_nc,1,...
3240%         %    ref_i+displ_num(4,ipair),ref_j+displ_num(2,ipair),subdir_civ1);
3241%         select(ipair)=exist(filename,'file')==2;
3242%     end
3243%     if  isequal(select,zeros(size(1:nbpair)))
3244%         if isfield(browse,'incr_pair')
3245%             num_i1=ref_i-floor(browse.incr_pair(1)/2);
3246%             num_i2=ref_i+floor((browse.incr_pair(1)+1)/2);
3247%             num_j1=ref_j-floor(browse.incr_pair(2)/2);
3248%             num_j2=ref_j+floor((browse.incr_pair(2)+1)/2);
3249%             filename=fullfile_uvmat(RootPath,subdir_civ2,RootFile,'.nc',nom_type_nc,num_i1,num_i2,num_j1,num_j2);
3250%             %filename=name_generator(filebase,num_i1,num_j1,'.nc',nom_type_nc,1,num_i2,num_j2,subdir_civ2);
3251%             select(1)=exist(filename,'file')==2;
3252%         else
3253%             if  isequal(mode,'series(Dj)')% | isequal(mode,'st_series(Dj)')
3254%                 msgbox_uvmat('ERROR',['no civ2 file available for the selected reference index j=' num2str(ref_j) ' and subdirectory ' subdir_civ2])
3255%             else
3256%                 msgbox_uvmat('ERROR',['no civ2 file available for the selected reference index i=' num2str(ref_i) ' and subdirectory ' subdir_civ2])
3257%             end
3258%             set(handles.ListPairCiv2,'Value',1);
3259%             set(handles.ListPairCiv2,'String',{''});
3260%             return
3261%         end
3262%     end
3263% end
3264% if isequal(mode,'series(Di)')
3265%     for ipair=1:nbpair
3266%         if select(ipair)
3267%             displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
3268%             if  ~checkframe && size(time,1)>=ref_i+displ_num(4,ipair) && size(time,2)>=ref_j+displ_num(2,ipair)
3269%                 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
3270%                 displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3271%             end
3272%         else
3273%             displ_pair{ipair}='...'; %pair not displayed in the menu
3274%         end
3275%     end
3276% elseif isequal(mode,'series(Dj)') %| isequal(mode,'st_series(Dj)') % series on the j index
3277%     for ipair=1:nbpair
3278%         if select(ipair)
3279%             displ_pair{ipair}=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
3280%             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
3281%                 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
3282%             else
3283%                 dt=1;
3284%             end
3285%                 displ_pair{ipair}=[displ_pair{ipair} ' :dt= ' num2str(dt*1000)];
3286%         else
3287%             displ_pair{ipair}='...'; %pair not displayed in the menu
3288%         end
3289%     end
3290% elseif isequal(mode,'pair j1-j2')% | isequal(mode,'st_pair j1-j2') %case of pairs
3291%     for ipair=1:nbpair
3292%         if select(ipair)
3293%             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
3294%             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
3295%             else
3296%                 dt=1;
3297%             end
3298%             displ_pair{ipair}=['j= ' num2stra(displ_num(1,ipair)+1,nom_type_ima) '-' num2stra(displ_num(2,ipair)+1,nom_type_ima) ...
3299%                 ' :dt= ' num2str(dt*1000)];
3300%                 
3301%         else
3302%             displ_pair{ipair}='...'; %pair not displayed in the menu
3303%         end
3304%     end
3305% elseif isequal(mode,'displacement')
3306%     displ_pair={'Di=Dj=0'};
3307% end
3308% val=get(handles.ListPairCiv2,'Value');
3309% ichoice=find(select,1);
3310% if (isempty(ichoice) || ichoice < 1); ichoice=1; end;
3311% if get(handles.CheckCiv2,'Value')==0 && get(handles.CheckCiv1,'Value')==0 && get(handles.CheckFix1,'Value')==0 && get(handles.CheckPatch1,'Value')==0
3312%     val=ichoice;% first valid pair proposed by default in the menu
3313% end
3314% if val>length(displ_pair')
3315%     set(handles.ListPairCiv2,'Value',1);% first valid pair proposed by default in the menu
3316% else
3317%     set(handles.ListPairCiv2,'Value',val);
3318% end
3319% set(handles.ListPairCiv2,'String',displ_pair');
3320% set(gcf,'Pointer','arrow')
3321
3322%-------------------------------------------------------------------
3323% ---
3324function closeview_field(gcbo,eventdata)
3325hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
3326    if ~isempty(hview_field)
3327        delete(hview_field)
3328    end
3329   
3330   
3331%------------------------------------------------------------------------   
3332% call 'view_field.fig' to display the  field selected in the list of 'status'
3333function open_view_field(hObject, eventdata)
3334%------------------------------------------------------------------------
3335list=get(hObject,'String');
3336index=get(hObject,'Value');
3337rootroot=get(hObject,'UserData');
3338filename=list{index};
3339ind_dot=strfind(filename,'...');
3340filename=filename(1:ind_dot-1);
3341filename=fullfile(rootroot,filename);
3342delete(get(hObject,'parent'))%delete the display figure to stop the check process
3343if exist(filename,'file')%visualise the vel field if it exists
3344    uvmat(filename)
3345    set(gcbo,'Value',1)
3346end
3347
3348%------------------------------------------------------------------------   
3349% launched by pressing OK on the status figure
3350function close_GUI(hObject, eventdata)
3351%------------------------------------------------------------------------
3352    delete(gcbf)
3353   
3354%------------------------------------------------------------------------   
3355% launched by deleting the status figure
3356function stop_status(hObject, eventdata)
3357%------------------------------------------------------------------------
3358hciv=findobj(allchild(0),'tag','civ');
3359hhciv=guidata(hciv);
3360set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
3361set(hhciv.status,'BackgroundColor',[0 1 0])
3362
3363
3364%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3365% Callbacks in the uipanel Reference Indices
3366%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3367%------------------------------------------------------------------------
3368function first_i_Callback(hObject, eventdata, handles)
3369%------------------------------------------------------------------------
3370first_i=str2double(get(handles.first_i,'String'));
3371set(handles.ref_i,'String', num2str(first_i))% reference index for pair dt = first index
3372ref_i_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3373
3374%------------------------------------------------------------------------
3375function first_j_Callback(hObject, eventdata, handles)
3376%------------------------------------------------------------------------
3377first_j=str2num(get(handles.first_j,'String'));
3378set(handles.ref_j,'String', num2str(first_j))% reference index for pair dt = first index
3379ref_j_Callback(hObject, eventdata, handles)%refresh dispaly of dt for pairs (in case of non constant dt)
3380
3381%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3382% Callbacks in the uipanel Civ1
3383%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3384%------------------------------------------------------------------------
3385% --- Executes on button press in SearchRange: determine the search range num_Searchx,num_Searchy
3386function SearchRange_Callback(hObject, eventdata, handles)
3387%------------------------------------------------------------------------
3388%determine pair numbers
3389if strcmp(get(handles.umin,'Visible'),'off')
3390    set(handles.u_title,'Visible','on')
3391    set(handles.v_title,'Visible','on')
3392    set(handles.umin,'Visible','on')
3393    set(handles.umax,'Visible','on')
3394    set(handles.vmin,'Visible','on')
3395    set(handles.vmax,'Visible','on')
3396    set(handles.CoordUnit,'Visible','on')
3397    set(handles.TimeUnit,'Visible','on')
3398    set(handles.slash_title,'Visible','on')
3399    set(handles.min_title,'Visible','on')
3400    set(handles.max_title,'Visible','on')
3401    set(handles.unit_title,'Visible','on')
3402else
3403    get_search_range(hObject, eventdata, handles)
3404end
3405
3406%------------------------------------------------------------------------
3407% ---  determine the search range num_Searchx,num_Searchy and shift
3408function get_search_range(hObject, eventdata, handles)
3409umin=str2double(get(handles.umin,'String'));
3410umax=str2double(get(handles.umax,'String'));
3411vmin=str2double(get(handles.umin,'String'));
3412vmax=str2double(get(handles.vmax,'String'));
3413%switch min_title and max_title in case of error
3414if umax<=umin
3415    umin_old=umin;
3416    umin=umax;
3417    umax=umin_old;
3418    set(handles.umin,'String', num2str(umin))
3419    set(handles.umax,'String', num2str(umax))
3420end
3421if vmax<=vmin
3422    vmin_old=vmin;
3423    vmin=vmax;
3424    vmax=vmin_old;
3425    set(handles.vmin,'String', num2str(vmin))
3426    set(handles.vmax,'String', num2str(vmax))
3427end   
3428if ~(isnan(umin)||isnan(umax)||isnan(vmin)||isnan(vmax))
3429    list_pair=get(handles.ListPairCiv1,'String');%get the menu of image pairs
3430    index=get(handles.ListPairCiv1,'Value');
3431    displ_num=get(handles.ListPairCiv1,'UserData');
3432    time=get(handles.ImaDoc,'UserData'); %get the set of times
3433    pxcm_xy=get(handles.SearchRange,'UserData');
3434    pxcmx=pxcm_xy(1);
3435    pxcmy=pxcm_xy(2);
3436    mode_list=get(handles.ListPairMode,'String');
3437    mode_value=get(handles.ListPairMode,'Value');
3438    mode=mode_list{mode_value};
3439    if isequal (mode, 'series(Di)' )
3440        ref_i=str2double(get(handles.ref_i,'String'));
3441        num1=ref_i-floor(index/2);%  first image numbers
3442        num2=ref_i+ceil(index/2);
3443        num_a=1;
3444        num_b=1;
3445    elseif isequal (mode, 'series(Dj)')
3446        num1=1;
3447        num2=1;
3448        ref_j=str2double(get(handles.ref_j,'String'));
3449        num_a=ref_j-floor(index/2);%  first image numbers
3450        num_b=ref_j+ceil(index/2);
3451    elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
3452        ref_i=str2double(get(handles.ref_i,'String'));
3453        num1=ref_i;
3454        num2=ref_i;
3455        num_a=displ_num(1,index);
3456        num_b=displ_num(2,index);
3457    end
3458    dt=time(num2,num_b)-time(num1,num_a);
3459    ibx=str2double(get(handles.num_Bx,'String'));
3460    iby=str2double(get(handles.num_By,'String'));
3461    umin=dt*pxcmx*umin;
3462    umax=dt*pxcmx*umax;
3463    vmin=dt*pxcmy*vmin;
3464    vmax=dt*pxcmy*vmax;
3465    shiftx=round((umin+umax)/2);
3466    shifty=round((vmin+vmax)/2);
3467    isx=(umax+2-shiftx)*2+ibx;
3468    isx=2*ceil(isx/2)+1;
3469    isy=(vmax+2-shifty)*2+iby;
3470    isy=2*ceil(isy/2)+1;
3471    set(handles.num_Shiftx,'String',num2str(shiftx));
3472    set(handles.num_Shifty,'String',num2str(shifty));
3473    set(handles.num_Searchx,'String',num2str(isx));
3474    set(handles.num_Searchy,'String',num2str(isy));
3475end
3476
3477%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3478% Callbacks in the uipanel Fix1
3479%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3480%------------------------------------------------------------------------
3481% --- Executes on button press in CheckMask.
3482function get_mask_fix1_Callback(hObject, eventdata, handles)
3483%------------------------------------------------------------------------
3484maskval=get(handles.CheckMask,'Value');
3485if isequal(maskval,0)
3486    set(handles.txt_Mask,'String','')
3487else
3488    mask_displ='no mask'; %default
3489    filebase=get(handles.RootName,'String');
3490    [nbslice, flag_mask]=get_mask(filebase,handles);
3491    if isequal(flag_mask,1)
3492        mask_displ=[num2str(nbslice) 'mask'];
3493    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3494        filebase_a=get(handles.RootName_1,'String');
3495        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3496        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3497            mask_displ='no mask';
3498        end
3499    end
3500    if isequal(mask_displ,'no mask')
3501        [FileName, PathName, filterindex] = uigetfile( ...
3502            {'*.png', ' (*.png)';
3503            '*.png',  '.png files '; ...
3504            '*.*', 'All Files (*.*)'}, ...
3505            'Pick a mask file *.png',filebase);
3506        mask_displ=fullfile(PathName,FileName);
3507        if ~exist(mask_displ,'file')
3508            mask_displ='no mask';
3509        end
3510    end
3511    if isequal(mask_displ,'no mask')
3512        set(handles.CheckMask,'Value',0)
3513        set(handles.CheckMask,'Value',0)
3514        set(handles.CheckMask,'Value',0)
3515    else
3516        %set(handles.CheckMask,'Value',1)
3517        set(handles.CheckMask,'Value',1)
3518    end
3519    set(handles.txt_Mask,'String',mask_displ)
3520    set(handles.txt_Mask,'String',mask_displ)
3521    set(handles.txt_Mask,'String',mask_displ)
3522end
3523
3524%------------------------------------------------------------------------
3525% --- Executes on button press in CheckMask: select box for mask option
3526function get_mask_civ2_Callback(hObject, eventdata, handles)
3527%------------------------------------------------------------------------
3528maskval=get(handles.CheckMask,'Value');
3529if isequal(maskval,0)
3530    set(handles.txt_Mask,'String','')
3531else
3532    mask_displ='no mask'; %default
3533    filebase=get(handles.RootName,'String');
3534    [nbslice, flag_mask]=get_mask(filebase,handles);
3535    if isequal(flag_mask,1)
3536        mask_displ=[num2str(nbslice) 'mask'];
3537    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3538        filebase_a=get(handles.RootName_1,'String');
3539        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3540        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3541            mask_displ='no mask';
3542        end
3543    end
3544    if isequal(mask_displ,'no mask')
3545        [FileName, PathName, filterindex] = uigetfile( ...
3546            {'*.png', ' (*.png)';
3547            '*.png',  '.png files '; ...
3548            '*.*', 'All Files (*.*)'}, ...
3549            'Pick a mask file *.png',filebase);
3550        mask_displ=fullfile(PathName,FileName);
3551        if ~exist(mask_displ,'file')
3552            mask_displ='no mask';
3553        end
3554    end
3555    if isequal(mask_displ,'no mask')
3556        set(handles.CheckMask,'Value',0)
3557        set(handles.CheckMask,'Value',0)
3558    else
3559        set(handles.CheckMask,'Value',1)
3560    end
3561    set(handles.txt_Mask,'String',mask_displ)
3562    set(handles.txt_Mask,'String',mask_displ)
3563end
3564
3565%------------------------------------------------------------------------
3566% --- Executes on button press in CheckMask.
3567function get_mask_fix2_Callback(hObject, eventdata, handles)
3568%------------------------------------------------------------------------
3569maskval=get(handles.CheckMask,'Value');
3570if isequal(maskval,0)
3571    set(handles.txt_Mask,'String','')
3572else
3573    mask_displ='no mask'; %default
3574    filebase=get(handles.RootName,'String');
3575    [nbslice, flag_mask]=get_mask(filebase,handles);
3576    if isequal(flag_mask,1)
3577        mask_displ=[num2str(nbslice) 'mask'];
3578    elseif get(handles.ListCompareMode,'Value')>1 & ~isequal(mask_displ,'no mask')% look for the second mask series
3579        filebase_a=get(handles.RootName_1,'String');
3580        [nbslice_a, flag_mask_a]=get_mask(filebase_a,handles);
3581        if isequal(flag_mask_a,0) || ~isequal(nbslice_a,nbslice)
3582            mask_displ='no mask';
3583        end
3584    end
3585    if isequal(mask_displ,'no mask')
3586        [FileName, PathName, filterindex] = uigetfile( ...
3587            {'*.png', ' (*.png)';
3588            '*.png',  '.png files '; ...
3589            '*.*', 'All Files (*.*)'}, ...
3590            'Pick a mask file *.png',filebase);
3591        mask_displ=fullfile(PathName,FileName);
3592        if ~exist(mask_displ,'file')
3593            mask_displ='no mask';
3594        end
3595    end
3596    if isequal(mask_displ,'no mask')
3597        set(handles.CheckMask,'Value',0)
3598    end
3599    set(handles.txt_Mask,'String',mask_displ)
3600end
3601
3602%------------------------------------------------------------------------
3603% --- function called to look for mask files
3604function [nbslice, flag_mask]=get_mask(filebase,handles)
3605%------------------------------------------------------------------------
3606%detect mask files, images with appropriate file base
3607%[filebase '_' xx 'mask'], xx=nbslice
3608%flag_mask=1 indicates detection
3609
3610flag_mask=0;%default
3611nbslice=1;
3612
3613% subdir=get(handles.txt_SubdirCiv1,'String');
3614[Path,Name]=fileparts(filebase);
3615if ~isdir(Path)
3616    msgbox_uvmat('ERROR','no path for input files')
3617    return
3618end
3619% currentdir=pwd;
3620% cd(Path);%move in the dir of the root name filebase
3621maskfiles=dir(fullfile(Path,[Name '_*mask_*.png']));%look for mask files
3622% cd(currentdir);%come back to the current working directory
3623if ~isempty(maskfiles)
3624    %     msgbox_uvmat('ERROR','no mask available, to create it use Tools/Make mask in the upper menu bar of uvmat')
3625    % else
3626    flag_mask=1;
3627    maskname=maskfiles(1).name;% take the first mask file in the list
3628    [Path2,Name,ext]=fileparts(maskname);
3629    Namedouble=double(Name);
3630    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3631    ind_mask=findstr('mask',Name);
3632    i=ind_mask-1;
3633    while val(i)==0 && i>0
3634        i=i-1;
3635    end
3636    nbslice=str2double(Name(i+1:ind_mask-1));
3637    if ~isnan(nbslice) && Name(i)=='_'
3638        flag_mask=1;
3639    else
3640        msgbox_uvmat('ERROR',['bad mask file ' Name ext ' found in ' Path2])
3641        return
3642        nbslice=1;
3643    end
3644end
3645
3646%------------------------------------------------------------------------
3647% --- function called to look for grid files
3648function [nbslice, flag_mask]=get_grid(filebase,handles)
3649%------------------------------------------------------------------------
3650flag_mask=0;%default
3651nbslice=1;
3652[Path,Name]=fileparts(filebase);
3653currentdir=pwd;
3654cd(Path);%move in the dir of the root name filebase
3655maskfiles=dir([Name '_*grid_*.grid']);%look for mask files
3656cd(currentdir);%come back to the current working directory
3657if ~isempty(maskfiles)
3658    flag_mask=1;
3659    maskname=maskfiles(1).name;% take the first mask file in the list
3660    [Path2,Name,ext]=fileparts(maskname);
3661    Namedouble=double(Name);
3662    val=(48>Namedouble)|(Namedouble>57);% select the non-numerical characters
3663    ind_mask=findstr('grid',Name);
3664    i=ind_mask-1;
3665    while val(i)==0 && i>0
3666        i=i-1;
3667    end
3668    nbslice=str2double(Name(i+1:ind_mask-1));
3669    if ~isnan(nbslice) && Name(i)=='_'
3670        flag_mask=1;
3671    else
3672        msgbox_uvmat('ERROR',['bad grid file ' Name ext ' found in ' Path2])
3673        return
3674        nbslice=1;
3675    end
3676end
3677
3678%------------------------------------------------------------------------
3679% --- transform numbers to letters
3680function str=num2stra(num,nom_type)
3681%------------------------------------------------------------------------
3682if isempty(nom_type)
3683    str='';
3684elseif strcmp(nom_type(end),'a')
3685    str=char(96+num);
3686elseif strcmp(nom_type(end),'A')
3687    str=char(96+num);
3688elseif isempty(nom_type(2:end))%a single index
3689    str='';
3690else
3691    str=num2str(num);
3692end
3693
3694%------------------------------------------------------------------------
3695% --- Executes on button press in ListSubdirCiv1.
3696function ListSubdirCiv1_Callback(hObject, eventdata, handles)
3697%------------------------------------------------------------------------
3698list_subdir_civ1=get(handles.ListSubdirCiv1,'String');
3699val=get(handles.ListSubdirCiv1,'Value');
3700SubDir=list_subdir_civ1{val};
3701if strcmp(SubDir,'new...')
3702    if get(handles.CheckCiv1,'Value')
3703        SubDir='CIV'; %default subdirectory
3704    else
3705        msgbox_uvmat('ERROR','select CheckCiv1 to perform a new Civ operation')
3706        return
3707    end   
3708end
3709set(handles.txt_SubdirCiv1,'String',SubDir);
3710errormsg=find_netcpair_civ(handles,1);
3711if ~isempty(errormsg)
3712    msgbox_uvmat('ERROR',errormsg)
3713end
3714   
3715%------------------------------------------------------------------------
3716% --- Executes on button press in ListSubdirCiv2.
3717function ListSubdirCiv2_Callback(hObject, eventdata, handles)
3718%------------------------------------------------------------------------
3719list_subdir_civ2=get(handles.ListSubdirCiv2,'String');
3720val=get(handles.ListSubdirCiv2,'Value');
3721SubDir=list_subdir_civ2{val};
3722if strcmp(SubDir,'new...')
3723    if get(handles.CheckCiv2,'Value')
3724        SubDir='CIV'; %default subdirectory
3725    else
3726        msgbox_uvmat('ERROR','select CheckCiv2 to perform a new Civ operation')
3727        return
3728    end
3729end
3730set(handles.txt_SubdirCiv2,'String',SubDir);
3731
3732%------------------------------------------------------------------------
3733% --- Executes on button press in CheckGrid.
3734function CheckGrid_Callback(hObject, eventdata, handles)
3735%------------------------------------------------------------------------
3736value=get(hObject,'Value');
3737hparent=get(hObject,'parent');
3738hchildren=get(hparent,'children');
3739handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3740handle_dx=findobj(hchildren,'tag','num_Dx');
3741handle_dy=findobj(hchildren,'tag','num_Dy');
3742handle_title_dx=findobj(hchildren,'tag','title_Dx');
3743handle_title_dy=findobj(hchildren,'tag','title_Dy');
3744testgrid=0;
3745filegrid='';
3746if value
3747    filebase=get(handles.RootName,'String');
3748    [nbslice, flag_grid]=get_grid(filebase,handles);% look for a grid with appropriate name
3749    if isequal(flag_grid,1)
3750        filegrid=[num2str(nbslice) 'grid'];
3751        testgrid=1;
3752    else % browse for a grid
3753        filegrid=get(hObject,'UserData');%look for previous grid name stored as UserData
3754        if exist(filegrid,'file')
3755            filebase=filegrid;
3756        end
3757        [FileName, PathName, filterindex] = uigetfile( ...
3758            {'*.grid', ' (*.grid)';
3759            '*.grid',  '.grid files '; ...
3760            '*.*', 'All Files (*.*)'}, ...
3761            'Pick a file',filebase);
3762        filegrid=fullfile(PathName,FileName);
3763        set(hObject,'UserData',filegrid);%store for future use
3764        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filegrid,'file'))
3765            testgrid=1;
3766        end
3767    end
3768end
3769if testgrid
3770    set(handle_dx,'Visible','off');
3771    set(handle_dy,'Visible','off');
3772    set(handle_title_dy,'Visible','off');
3773    set(handle_title_dx,'Visible','off');
3774    set(handle_txtbox,'Visible','on')
3775    set(handle_txtbox,'String',filegrid)
3776else
3777    set(hObject,'Value',0);
3778    set(handle_dx,'Visible','on');
3779    set(handle_dy,'Visible','on');
3780    set(handle_title_dy,'Visible','on');
3781    set(handle_title_dx,'Visible','on');
3782    set(handle_txtbox,'Visible','off')
3783end
3784
3785%% if hObject is on the checkciv1 frame, duplicate action for checkciv2 frame
3786PanelName=get(hparent,'tag');
3787if strcmp(PanelName,'Civ1')
3788    hchildren=get(handles.Civ2,'children');
3789    handle_checkbox=findobj(hchildren,'tag','CheckGrid');
3790    handle_txtbox=findobj(hchildren,'tag','txt_Grid');
3791    handle_dx=findobj(hchildren,'tag','num_Dx');
3792    handle_dy=findobj(hchildren,'tag','num_Dy');
3793    handle_title_dx=findobj(hchildren,'tag','title_Dx');
3794    handle_title_dy=findobj(hchildren,'tag','title_Dy');
3795    set(handle_checkbox,'UserData',filegrid);%store for future use
3796    if testgrid
3797        set(handle_checkbox,'Value',1);
3798        set(handle_dx,'Visible','off');
3799        set(handle_dy,'Visible','off');
3800        set(handle_title_dx,'Visible','off');
3801        set(handle_title_dy,'Visible','off');
3802        set(handle_txtbox,'Visible','on')
3803        set(handle_txtbox,'String',filegrid)
3804%     else
3805%         set(handle_checkbox,'Value',0);
3806%         set(handles.CheckGrid,'Value',0);
3807%         set(handle_dx,'Visible','on');
3808%         set(handle_dy,'Visible','on');
3809%          set(handle_title_dx,'Visible','on');
3810%         set(handle_title_dy,'Visible','on');
3811%         set(handle_txtbox,'Visible','off')
3812    end
3813end
3814%------------------------------------------------------------------------
3815% --- Executes on button press in CheckMask.
3816function CheckMask_Callback(hObject, eventdata, handles)
3817%------------------------------------------------------------------------
3818value=get(hObject,'Value');
3819hparent=get(hObject,'parent');
3820parent_tag=get(hparent,'Tag');
3821hchildren=get(hparent,'children');
3822handle_txtbox=findobj(hchildren,'tag','txt_Mask');
3823% handle_dx=findobj(hchildren,'tag','num_Dx');
3824% handle_dy=findobj(hchildren,'tag','num_Dy');
3825testmask=0;
3826if value
3827    filebase=get(handles.RootName,'String');
3828    [nbslice, flag_mask]=get_mask(filebase,handles);% look for a mask with appropriate name
3829    if isequal(flag_mask,1)
3830        filemask=[num2str(nbslice) 'mask'];
3831        testmask=1;
3832    else % browse for a mask
3833        filemask=get(hObject,'UserData');%look for previous mask name stored as UserData
3834        if exist(filemask,'file')
3835            filebase=filemask;
3836        end
3837        [FileName, PathName] = uigetfile( ...
3838            {'*.png', ' (*.png)';
3839            '*.png',  '.png files '; ...
3840            '*.*', 'All Files (*.*)'}, ...
3841            'Pick a mask file *.png',filebase);
3842        filemask=fullfile(PathName,FileName);
3843        set(hObject,'UserData',filemask);%store for future use
3844        if ~(isempty(FileName)||isempty(PathName)||isequal(FileName,0)||~exist(filemask,'file'))
3845            testmask=1;
3846        end
3847    end
3848end
3849if testmask
3850%     stage=4;%default
3851    if strcmp(parent_tag,'Civ1')
3852            set(handles.txt_Mask,'Visible','on')
3853        set(handles.txt_Mask,'String',filemask)
3854    set(handles.CheckMask,'Value',1)
3855    end
3856%     switch parent_tag
3857% %         case 'Fix1'
3858% %             stage=2;
3859%         case 'Civ2'
3860%              stage=3;
3861% %         case 'Fix2'
3862% %             stage=4;
3863%     end
3864%     set(handles.txt_Mask(stage:end),'Visible','on')
3865%     set(handles.txt_Mask(stage:end),'String',filemask)
3866%     set(handles.CheckMask(stage:end),'Value',1)
3867else
3868    set(hObject,'Value',0);
3869    set(handle_txtbox,'Visible','off')
3870end
3871
3872
3873% --- Executes on button press in get_gridpatch1.
3874function get_gridpatch1_Callback(hObject, eventdata, handles)
3875% hObject    handle to get_gridpatch1 (see GCBO)
3876% eventdata  reserved - to be defined in a future version of MENUMATLAB
3877% handles    structure with handles and user data (see GUIDATA)
3878
3879filebase=get(handles.RootName,'String');
3880[FileName, PathName, filterindex] = uigetfile( ...
3881    {'*.grid', ' (*.grid)';
3882    '*.grid',  '.grid files '; ...
3883    '*.*', 'All Files (*.*)'}, ...
3884    'Pick a file',filebase);
3885filegrid=fullfile(PathName,FileName);
3886set(handles.grid_patch1,'string',filegrid);
3887% set(handles.grid_patch2,'string',filegrid
3888
3889%------------------------------------------------------------------------
3890% --- Executes on button press in get_gridpatch2.
3891function get_gridpatch2_Callback(hObject, eventdata, handles)
3892%------------------------------------------------------------------------
3893
3894
3895%------------------------------------------------------------------------
3896% --- STEREO Interp
3897function cmd=RUN_STINTERP(stinterpBin,filename_A_nc,filename_B_nc,filename_nc,nx_patch,ny_patch,rho_patch,subdomain_patch,thresh_value,xmlA,xmlB)
3898%------------------------------------------------------------------------
3899namelog=[filename_nc(1:end-3) '_stinterp.log'];
3900cmd=[stinterpBin ' -f1 ' filename_A_nc  ' -f2 ' filename_B_nc ' -f  ' filename_nc ...
3901    ' -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
3902
3903%------------------------------------------------------------------------
3904%--read images and convert them to the uint16 format used for PIV
3905function A=read_image(filename,type_ima,num,movieobject)
3906%------------------------------------------------------------------------
3907%num is the view number needed for an avi movie
3908switch type_ima
3909    case 'movie'
3910        A=read(movieobject,num);
3911    case 'avi'
3912        mov=aviread(filename,num);
3913        A=frame2im(mov(1));
3914    case 'multimage'
3915        A=imread(filename,num);
3916    case 'image'
3917        A=imread(filename);
3918end
3919siz=size(A);
3920if length(siz)==3;%color images
3921    A=sum(double(A),3);
3922    A=uint16(A);
3923end
3924
3925
3926%------------------------------------------------------------------------
3927% --- Executes on button press in get_ref_fix1.
3928function get_ref_fix1_Callback(hObject, eventdata, handles)
3929%------------------------------------------------------------------------
3930filebase=get(handles.RootName,'String');
3931[FileName, PathName, filterindex] = uigetfile( ...
3932    {'*.nc', ' (*.nc)';
3933    '*.nc',  'netcdf files '; ...
3934    '*.*', 'All Files (*.*)'}, ...
3935    'Pick a file',filebase);
3936
3937fileinput=[PathName FileName];
3938sizf=size(fileinput);
3939if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3940%[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3941[Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3942ref.filebase=fullfile(Path,File);
3943% ref.num_a=stra2num(str_a);
3944% ref.num_b=stra2num(str_b);
3945% ref.num1=str2double(field_count);
3946% ref.num2=str2double(str2);
3947browse=[];%initialisation
3948if ~isequal(ref.ext,'.nc')
3949    msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3950    return
3951end
3952set(handles.ref_fix1,'String',[fullfile(ref.subdir,File) '....nc']);
3953set(handles.ref_fix1,'UserData',ref)
3954menu_field{1}='civ1';
3955Data=nc2struct(fileinput,[]);
3956if isfield(Data,'patch') && isequal(Data.patch,1)
3957    menu_field{2}='filter1';
3958end
3959if isfield(Data,'civ2') && isequal(Data.civ2,1)
3960    menu_field{3}='civ2';
3961end
3962if isfield(Data,'patch2') && isequal(Data.patch2,1)
3963    menu_field{4}='filter2';
3964end
3965set(handles.field_ref1,'String',menu_field);
3966set(handles.field_ref1,'Value',length(menu_field));
3967set(handles.num_MinVel,'Value',2);
3968set(handles.num_MinVel,'String','1');%default threshold
3969set(handles.ref_fix1,'Enable','on')
3970
3971%------------------------------------------------------------------------
3972% --- Executes on button press in get_ref_fix2.
3973function get_ref_fix2_Callback(hObject, eventdata, handles)
3974%------------------------------------------------------------------------
3975if isequal(get(handles.get_ref_fix2,'Value'),1)
3976    filebase=get(handles.RootName,'String');
3977    [FileName, PathName, filterindex] = uigetfile( ...
3978        {'*.nc', ' (*.nc)';
3979        '*.nc',  'netcdf files '; ...
3980        '*.*', 'All Files (*.*)'}, ...
3981        'Pick a file',filebase);
3982    fileinput=[PathName FileName];
3983    sizf=size(fileinput);
3984    if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end %stop if fileinput not a character string
3985    %[Path,File,field_count,str2,str_a,str_b,ref.ext,ref.nom_type,ref.subdir]=name2display(fileinput);
3986    [Path,ref.subdir,File,ref.num1,ref.num2,ref.num_a,ref.num_b,ref.ext,ref.nom_type]=fileparts_uvmat(fileinput);
3987    ref.filebase=fullfile(Path,File);
3988%     ref.num_a=stra2num(str_a);
3989%     ref.num_b=stra2num(str_b);
3990%     ref.num1=str2num(field_count);
3991%     ref.num2=str2num(str2);
3992    browse=[];%initialisation
3993    if ~isequal(ref.ext,'.nc')
3994        msgbox_uvmat('ERROR','the reference file must be in netcdf format (*.nc)')
3995        return
3996    end
3997    set(handles.ref_fix2,'String',[fullfile(ref.subdir,File) '....nc']);
3998    set(handles.ref_fix2,'UserData',ref)
3999    menu_field{1}='civ1';
4000    Data=nc2struct(fileinput,[]);
4001    if isfield(Data,'patch') && isequal(Data.patch,1)
4002        menu_field{2}='filter1';
4003    end
4004    if isfield(Data,'civ2') && isequal(Data.civ2,1)
4005        menu_field{3}='civ2';
4006    end
4007    if isfield(Data,'patch2') && isequal(Data.patch2,1)
4008        menu_field{4}='filter2';
4009    end
4010    set(handles.field_ref2,'String',menu_field);
4011    set(handles.field_ref2,'Value',length(menu_field));
4012    set(handles.num_MinVel,'Value',2);
4013    set(handles.num_MinVel,'String','1');%default threshold
4014    set(handles.ref_fix2,'Enable','on')
4015    set(handles.ref_fix2,'Visible','on')
4016    set(handles.field_ref2,'Visible','on')
4017else
4018    set(handles.ref_fix2,'Visible','off')
4019    set(handles.field_ref2,'Visible','off')
4020end
4021
4022%------------------------------------------------------------------------
4023function ref_fix1_Callback(hObject, eventdata, handles)
4024%------------------------------------------------------------------------
4025set(handles.num_MinVel,'Value',1);
4026set(handles.field_ref1,'Value',1)
4027set(handles.field_ref1,'String',{' '})
4028set(handles.ref_fix1,'UserData',[]);
4029set(handles.ref_fix1,'String','');
4030set(handles.thresh_vel1,'String','0');
4031
4032%------------------------------------------------------------------------
4033function ref_fix2_Callback(hObject, eventdata, handles)
4034%------------------------------------------------------------------------
4035set(handles.num_MinVel,'Value',1);
4036set(handles.field_ref2,'Value',1)
4037set(handles.field_ref2,'String',{' '})
4038set(handles.ref_fix2,'UserData',[]);
4039set(handles.ref_fix2,'String','');
4040set(handles.num_MinVel,'String','0');
4041
4042%------------------------------------------------------------------------
4043% --- Executes on button press in test_stereo1.
4044function test_stereo1_Callback(hObject, eventdata, handles)
4045%------------------------------------------------------------------------
4046if isequal(get(handles.test_stereo1,'Value'),0)
4047    set(handles.subdomain_patch1,'Visible','on')
4048    set(handles.rho_patch1,'Visible','on')
4049else
4050    set(handles.subdomain_patch1,'Visible','off')
4051    set(handles.rho_patch1,'Visible','off')
4052end
4053
4054%------------------------------------------------------------------------
4055% --- Executes on button press in CheckStereo.
4056function StereoCheck_Callback(hObject, eventdata, handles)
4057%------------------------------------------------------------------------
4058if isequal(get(handles.CheckStereo,'Value'),0)
4059    set(handles.num_SubdomainSize,'Visible','on')
4060    set(handles.num_SmoothingParam,'Visible','on')
4061else
4062    set(handles.num_SubdomainSize,'Visible','off')
4063    set(handles.num_SmoothingParam,'Visible','off')
4064end
4065
4066%------------------------------------------------------------------------
4067% --- Executes on button press in TestCiv1: display image correlation function
4068function TestCiv1_Callback(hObject, eventdata, handles)
4069%------------------------------------------------------------------------
4070set(handles.TestCiv1,'BackgroundColor',[1 1 0])
4071drawnow
4072if get(handles.TestCiv1,'Value')
4073    ref_i=str2double(get(handles.ref_i,'String'));
4074    if strcmp(get(handles.ref_j,'Visible'),'on')
4075        ref_j=str2double(get(handles.ref_j,'String'));
4076    else
4077        ref_j=1;%default
4078    end
4079    [filecell,i1,i21,j1,j2,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,file_ref_fix1,file_ref_fix2]=...
4080        set_civ_filenames(handles,ref_i,ref_j,[1 0 0 0 0 0]);
4081    Data.ListVarName={'ny','nx','A'};
4082    Data.VarDimName= {'ny','nx',{'ny','nx'}};
4083    Data.A=imread(filecell.ima1.civ1{1});
4084    Data.ny=[size(Data.A,1) 1];
4085    Data.nx=[1 size(Data.A,2)];
4086    par_civ1=read_GUI(handles.Civ1);
4087    par_civ1.ImageWidth=size(Data.A,1);
4088    par_civ1.ImageHeight=size(Data.A,2);
4089    par_civ1.Mask='all';% will provide only the grid set for PIV, no image correlation
4090    Param.Civ1=par_civ1;
4091    Grid=civ_matlab(Param);% get the grid of x, y positions set for PIV
4092    hview_field=view_field(Data);
4093    set(0,'CurrentFigure',hview_field)
4094    hhview_field=guihandles(hview_field);
4095    set(hview_field,'CurrentAxes',hhview_field.axes3)
4096    ViewData=get(hview_field,'UserData');
4097    ViewData.CivHandle=handles.civ;% indicate the handle of the civ GUI in view_field
4098    ViewData.axes3.B=imread(filecell.ima2.civ1{1});%store the second image in the UserData of the GUI view_field
4099    ViewData.axes3.X=Grid.Civ1_X; %keep the set of points in memeory
4100    ViewData.axes3.Y=Grid.Civ1_Y;
4101    set(hview_field,'UserData',ViewData)
4102    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4103    if isempty(corrfig)
4104        corrfig=figure;
4105        set(corrfig,'tag','corrfig')
4106        set(corrfig,'name','image correlation')
4107        set(corrfig,'DeleteFcn',{@closeview_field})%
4108    end
4109    set(handles.TestCiv1,'BackgroundColor',[1 0 0])
4110else
4111    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4112    if ~isempty(corrfig)
4113        delete(corrfig)
4114    end
4115    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field   
4116    if ~isempty(hview_field)
4117        delete(hview_field)
4118    end
4119end
4120
4121
4122%------------------------------------------------------------------------
4123% --- Executes on button press in CheckThreshold.
4124function CheckThreshold_Callback(hObject, eventdata, handles)
4125%------------------------------------------------------------------------
4126huipanel=get(hObject,'parent');
4127obj(1)=findobj(huipanel,'Tag','num_MinIma');
4128obj(2)=findobj(huipanel,'Tag','num_MaxIma');
4129obj(3)=findobj(huipanel,'Tag','title_Threshold');
4130if get(hObject,'Value')
4131    set(obj,'Visible','on')
4132else
4133    set(obj,'Visible','off')
4134end
4135
4136
4137%------------------------------------------------------------------------
4138% % --- Executes on button press in ListPairMode.
4139% function CivMode_Callback(hObject, eventdata, handles)
4140% %------------------------------------------------------------------------
4141% Listprog=get(handles.ListPairMode,'String');
4142% index=get(handles.ListPairMode,'Value');
4143% prog=Listprog{index};
4144% switch prog
4145%     case 'MenuCivX'
4146%         set(handles.thresh_patch1,'Visible','off')
4147%         set(handles.thresh_text1,'Visible','off')
4148%         set(handles.num_MaxDiff,'Visible','off')
4149%         set(handles.title_MaxDiff,'Visible','off')
4150%         set(handles.num_Rho,'Style','edit')
4151%         set(handles.num_Rho,'String','1')
4152%         set(handles.BATCH,'Enable','on')
4153%     case 'CivAll'
4154%         if get(handles.CheckPatch1,'Value')
4155%             set(handles.thresh_patch1,'Visible','on')
4156%             set(handles.thresh_text1,'Visible','on')
4157%         end
4158%         set(handles.num_Rho,'Style','edit')
4159%         set(handles.num_Rho,'String','1')
4160%         set(handles.BATCH,'Enable','on')
4161%     case 'CivUvmat'
4162%       
4163% end
4164
4165%------------------------------------------------------------------------
4166function cmd=cmd_civ1(filename,Param)
4167%------------------------------------------------------------------------
4168%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4169%changes : filename_cmx -> filename ( no extension )
4170cmd='';
4171errormsg=''; %default
4172filename=regexprep(filename,'.nc',''); %file name for the result
4173if isequal(Param.Civ1.Dt,0)
4174    Param.Civ1.Dt=1 ;%case of 'displacement' mode
4175end
4176Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'.png','');
4177Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'.png','');
4178fid=fopen([filename '.civ1.cmx'],'w');
4179if isequal(fid,-1)
4180    display(['cmd file ' filename ' cannot be created'])
4181    return
4182end
4183fprintf(fid,['##############   CMX file' '\n' ]);
4184fprintf(fid,   ['FirstImage ' regexprep(Param.Civ1.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4185fprintf(fid,   ['LastImage  ' regexprep(Param.Civ1.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4186fprintf(fid,  ['XX' '\n' ]);
4187if isfield(Param.Civ1,'Mask')
4188    fprintf(fid,  ['Mask ' 'y' '\n' ]);
4189    fprintf(fid,  ['MaskName ' regexprep(Param.Civ1.Mask,'\\','\\\\') '\n' ]);
4190else
4191    fprintf(fid,  ['Mask ' 'n' '\n' ]);
4192    fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4193end
4194fprintf(fid,   ['ImageSize ' num2str(Param.Civ1.ImageWidth) ' ' num2str(Param.Civ1.ImageHeight) '\n' ]);   %VERIFIER CAS GENERAL ?
4195fprintf(fid,   ['CorrelationBoxesSize ' num2str(Param.Civ1.Bx) ' ' num2str(Param.Civ1.By) '\n' ]);
4196fprintf(fid,   ['SearchBoxeSize ' num2str(Param.Civ1.Searchx) ' ' num2str(Param.Civ1.Searchy) '\n' ]);
4197fprintf(fid,   ['RO ' num2str(Param.Civ1.Rho) '\n' ]);
4198if isfield(Param.Civ1,'Grid')
4199    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4200else
4201    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ1.Dx) ' ' num2str(Param.Civ1.Dy) '\n' ]);
4202end
4203fprintf(fid,   ['XX 1.0' '\n' ]);
4204fprintf(fid,   ['Dt_TO ' num2str(Param.Civ1.Dt) ' ' num2str(Param.Civ1.Time) '\n' ]);
4205fprintf(fid,  ['PixCmXY ' '1' ' ' '1' '\n' ]);
4206fprintf(fid,  ['XX 1' '\n' ]);
4207fprintf(fid,   ['ShiftXY ' num2str(Param.Civ1.Shiftx) ' '  num2str(Param.Civ1.Shifty) '\n' ]);
4208if isfield(Param.Civ1,'Grid')
4209    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4210    fprintf(fid,   ['GridName ' regexprep(Param.Civ1.Grid,'\\','\\\\') '\n' ]);
4211else
4212    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4213    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4214end
4215fprintf(fid,   ['XX 85' '\n' ]);
4216fprintf(fid,   ['XX 1.0' '\n' ]);
4217fprintf(fid,   ['XX 1.0' '\n' ]);
4218fprintf(fid,   ['Hart 1' '\n' ]);
4219fprintf(fid,  [ 'DecimalShift 0' '\n' ]);
4220fprintf(fid,   ['Deformation 0' '\n' ]);
4221fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4222fprintf(fid,   ['IntensityMin 0' '\n' ]);
4223if ~isfield(Param.Civ1,'MinIma')% Image threshold not activated
4224    fprintf(fid,  ['SeuilImage n' '\n' ]);
4225    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4226else% Image threshold  activated
4227    if isempty(Param.Civ1.MaxIma)||isnan(Param.Civ1.MaxIma)
4228        Param.Civ1.MaxIma=2^Param.Civ1.ImageBitDepth;%take the max image value as upper bound by default
4229    end
4230    fprintf(fid,  ['SeuilImage y' '\n' ]);
4231    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ1.MinIma) ' ' num2str(Param.Civ1.MaxIma) '\n' ]);
4232end
4233fprintf(fid,   ['ImageToUse ' Param.Civ1.term_a ' ' Param.Civ1.term_b '\n' ]); % VERIFIER ?
4234fprintf(fid,   ['ImageUsedBefore null null' '\n' ]);
4235fclose(fid);
4236
4237if(isunix) %unix (or Mac) system
4238    cmd=['cp -f ' filename '.civ1.cmx ' filename '.cmx \n '];% the cmx file gives the name to the nc file
4239    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
4240    cmd=[cmd 'rm ' filename '.cmx'];
4241else %Windows system
4242    filename=regexprep(filename,'\\','\\\\');
4243    cmd=['copy /Y "' filename '.civ1.cmx" "' filename '.cmx" \n '];
4244    cmd=[cmd '"' regexprep(Param.xml.Civ1Bin,'\\','\\\\')...
4245        '" -f "' filename '.cmx" >"' filename '.civ1.log" \n ' ]; % redirect standard output to the log file
4246    cmd=[cmd 'del "' filename '.cmx"'];
4247end
4248
4249
4250function cmd=cmd_fix(filename,Param,fixname)
4251%%
4252switch fixname
4253    case 'Fix1'
4254        fi2_value=num2str(Param.(fixname).CheckF2);
4255    case 'Fix2'
4256        fi2_value=num2str(Param.(fixname).CheckF4);%need to understand why...
4257end
4258filename=regexprep(filename,'.nc','');
4259MaskName_string='';%default
4260% if Param.(fixname).CheckMask
4261%     MaskName_string=[' -maskName "' Param.(fixname).Mask '"'];
4262% end
4263MaxVel_string='';%default
4264if ~isempty(Param.(fixname).MaxVel)
4265    MaxVel_string=[' -threshV ' num2str(Param.(fixname).MaxVel)];
4266end
4267if isunix
4268    cmd=[Param.xml.FixBin ' -f ' filename '.nc -fi1 ' num2str(Param.(fixname).CheckFmin2) ...
4269        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4270        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4271        ' >' filename '.' lower(fixname) '.log 2>&1'];
4272else
4273    cmd=['"' Param.xml.FixBin '" -f "' filename '.nc" -fi1 ' num2str(Param.(fixname).CheckFmin2)...
4274        ' -fi2 ' fi2_value ' -fi3 ' num2str(Param.(fixname).CheckF3) ...
4275        ' -threshC ' num2str(Param.(fixname).MinCorr) MaxVel_string MaskName_string...
4276        ' > "' filename '.' lower(fixname) '.log"'];
4277    cmd=regexprep(cmd,'\\','\\\\');
4278end
4279
4280
4281function cmd=cmd_patch(filename,Param,patchname)
4282%% ------------------------------------------------------------------------
4283filename=regexprep(filename,'.nc','');
4284if isunix
4285    cmd=[Param.xml.PatchBin...
4286        ' -f ' filename '.nc -m ' num2str(Param.(patchname).Nx)...
4287        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).SmoothingParam)...
4288        ' -nopt ' num2str(Param.(patchname).SubdomainSize) ...
4289        '  > ' filename '.' lower(patchname) '.log 2>&1']; % redirect standard output to the log file
4290else
4291    cmd=['"' Param.xml.PatchBin...
4292        '" -f "' filename '.nc" -m ' num2str(Param.(patchname).Nx)...
4293        ' -n ' num2str(Param.(patchname).Ny) ' -ro ' num2str(Param.(patchname).SmoothingParam)...
4294        ' -nopt ' num2str(Param.(patchname).SubdomainSize)...
4295        '  > "' filename '.' lower(patchname) '.log" 2>&1']; % redirect standard output to the log file
4296    cmd=regexprep(cmd,'\\','\\\\');
4297end
4298
4299%------------------------------------------------------------------------
4300% --- CheckCiv2  CheckCiv2  CheckCiv2 CheckCiv2
4301function cmd=cmd_civ2(filename,Param)
4302%------------------------------------------------------------------------
4303%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4304% global civ2Bin sge%name of the executable for checkciv1 calculation
4305filename=regexprep(filename,'.nc','');
4306if isequal(Param.Civ2.Dt,'0')
4307    Param.Civ2.Dt='1' ;%case of 'displacement' mode
4308end
4309Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'.png','');
4310Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'.png','');% bug : .png appears two times ?
4311[fid,errormsg]=fopen([filename '.civ2.cmx'],'w');
4312if isequal(fid,-1)
4313    msgbox_uvmat('ERROR',errormsg)
4314    cmd='';
4315    return
4316end
4317fprintf(fid,['##############   CMX file' '\n' ]);
4318fprintf(fid,   ['FirstImage ' regexprep(Param.Civ2.ImageA,'\\','\\\\') '\n' ]);% for windows compatibility
4319fprintf(fid,   ['LastImage  ' regexprep(Param.Civ2.ImageB,'\\','\\\\') '\n' ]);% for windows compatibility
4320fprintf(fid,  ['XX' '\n' ]);
4321if isfield(Param.Civ2,'Mask')
4322    fprintf(fid,  ['Mask ' 'y' '\n' ]);
4323    fprintf(fid,  ['MaskName ' regexprep(Param.Civ2.Mask,'\\','\\\\') '\n' ]);
4324else
4325    fprintf(fid,  ['Mask ' 'n' '\n' ]);
4326    fprintf(fid,  ['MaskName ' 'noFile use default' '\n' ]);
4327end
4328% fprintf(fid, ['Mask ' Param.Civ2.MaskFlag '\n' ]);
4329% fprintf(fid, ['MaskName ' regexprep(Param.Civ2.MaskName,'\\','\\\\') '\n' ]);% for windows compatibility
4330fprintf(fid,   ['ImageSize ' num2str(Param.Civ2.ImageWidth) ' ' num2str(Param.Civ2.ImageHeight) '\n' ]); 
4331% fprintf(fid, ['ImageSize ' num2str(Param.Civ2.npx) ' ' num2str(Param.Civ2.npy) '\n' ]);   %VERIFIER CAS GENERAL ?
4332fprintf(fid, ['CorrelationBoxesSize ' num2str(Param.Civ2.Bx) ' ' num2str(Param.Civ2.By) '\n' ]);
4333fprintf(fid, ['SearchBoxeSize ' num2str(Param.Civ2.Bx) ' ' num2str(Param.Civ2.By) '\n']);
4334fprintf(fid, ['RO ' num2str(Param.Civ2.Rho) '\n']);
4335if isfield(Param.Civ2,'Grid')
4336    fprintf(fid,   ['GridSpacing ' '25' ' ' '25' '\n' ]);
4337else
4338    fprintf(fid,   ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n' ]);
4339end
4340% fprintf(fid, ['GridSpacing ' num2str(Param.Civ2.Dx) ' ' num2str(Param.Civ2.Dy) '\n']);
4341fprintf(fid, ['XX 1.0' '\n' ]);
4342fprintf(fid, ['Dt_TO ' num2str(Param.Civ2.Dt) ' ' num2str(Param.Civ2.Time) '\n' ]);
4343fprintf(fid, ['PixCmXY ' '1' ' ' '1' '\n' ]);
4344fprintf(fid, ['XX 1' '\n' ]);
4345fprintf(fid, 'ShiftXY 0 0\n');
4346if isfield(Param.Civ2,'Grid')
4347    fprintf(fid,  ['Grid ' 'y' '\n' ]);
4348    fprintf(fid,   ['GridName ' regexprep(Param.Civ2.Grid,'\\','\\\\') '\n' ]);
4349else
4350    fprintf(fid,  ['Grid ' 'n' '\n' ]);
4351    fprintf(fid,   ['GridName ' 'noFile use default' '\n' ]);
4352end
4353% fprintf(fid, ['Grid ' Param.Civ2.GridFlag '\n' ]);
4354% fprintf(fid, ['GridName ' regexprep(Param.Civ2.GridName,'\\','\\\\') '\n']);
4355fprintf(fid, ['XX 85' '\n' ]);
4356fprintf(fid, ['XX 1.0' '\n' ]);
4357fprintf(fid, ['XX 1.0' '\n' ]);
4358fprintf(fid, ['Hart 1' '\n' ]);
4359fprintf(fid, ['DecimalShift ' num2str(Param.Civ2.CheckDecimal) '\n']);
4360fprintf(fid, ['Deformation ' num2str(Param.Civ2.CheckDeformation) '\n']);
4361fprintf(fid,  ['CorrelationMin 0' '\n' ]);
4362fprintf(fid,   ['IntensityMin 0' '\n' ]);
4363
4364if ~isfield(Param.Civ2,'MinIma')% Image threshold not activated
4365    fprintf(fid,  ['SeuilImage n' '\n' ]);
4366    fprintf(fid,   ['SeuilImageValues 0 4096' '\n' ]);%not used in principle
4367else% Image threshold  activated
4368    if isempty(Param.Civ2.MaxIma)||isnan(Param.Civ2.MaxIma)
4369        Param.Civ2.MaxIma=2^Param.Civ2.ImageBitDepth;%take the max image value as upper bound by default
4370    end
4371    fprintf(fid,  ['SeuilImage y' '\n' ]);
4372    fprintf(fid,   ['SeuilImageValues ' num2str(Param.Civ2.MinIma) ' ' num2str(Param.Civ2.MaxIma) '\n' ]);
4373end
4374fprintf(fid,   ['ImageToUse ' Param.Civ2.term_a ' ' Param.Civ2.term_b '\n' ]); % VERIFIER ?
4375fprintf(fid, ['ImageUsedBefore ' regexprep(Param.Civ2.filename_nc1,'\\','\\\\') '\n']);
4376fclose(fid);
4377
4378if(isunix)
4379    cmd=['cp -f ' filename '.civ2.cmx ' filename '.cmx\n'...
4380        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
4381        'rm ' filename '.cmx \n'];%rename .cmx as .checkciv2.cmx, the result file is named [filename '.nc'] by CIVx
4382else
4383    filename=regexprep(filename,'\\','\\\\');
4384    cmd=['copy /Y "' filename '.civ2.cmx" "' filename '.cmx" \n'...
4385        '"' regexprep(Param.xml.Civ2Bin,'\\','\\\\') '" -f "' filename  '.cmx" >"' filename '.civ2.log" \n'...
4386        'del "' filename '.cmx" \n'];
4387end
4388
4389%------------------------------------------------------------------------
4390% --- CheckCiv1  Unified: TO ABADON
4391function xml_civ1_parameters=CIV1_CMD_Unified(filename,namelog,par)
4392%------------------------------------------------------------------------
4393%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4394%global CivBin%name of the executable for checkciv1 calculation
4395
4396civ1.image1=par.ImageA;
4397civ1.image2=par.ImageB;
4398civ1.imageSize_X=par.npx;
4399civ1.imageSize_Y=par.npy;
4400civ1.outputFileName=[filename '.nc'];
4401civ1.correlationBoxesSize_X=par.ibx;
4402civ1.correlationBoxesSize_Y=par.iby;
4403civ1.searchBoxesSize_X=par.isx;
4404civ1.searchBoxesSize_Y=par.isy;
4405civ1.globalShift_X=par.shiftx;
4406civ1.globalShift_Y=par.shifty;
4407civ1.ro=par.rho;
4408civ1.hart='y';
4409if isequal(par.gridflag,'y')
4410    civ1.grid=par.gridname;
4411else
4412    civ1.grid='n';
4413    civ1.gridSpacing_X=par.dx;
4414    civ1.gridSpacing_Y=par.dy;
4415end
4416if isequal(par.maskflag,'y')
4417    civ1.mask=par.maskname;
4418end
4419civ1.dt=par.Dt;
4420civ1.unit='pixel';
4421civ1.absolut_time_T0=par.Time;
4422civ1.pixcmx='1';
4423civ1.pixcmy='1';
4424civ1.convectFlow='n';
4425
4426xml_civ1_parameters=civ1;
4427
4428%------------------------------------------------------------------------
4429% --- CheckCiv2  Unified: TO ABADON
4430function civ2=CIV2_CMD_Unified(filename,namelog,par)
4431%------------------------------------------------------------------------
4432%pixels per cm and matrix of the image times, read from the .civ file by uvmat
4433%global CivBin%name of the executable for checkciv1 calculation
4434
4435filename=regexprep(filename,'.nc','');
4436
4437civ2.image1=par.ImageA;
4438civ2.image2=par.ImageB;
4439civ2.imageSize_X=par.npx;
4440civ2.imageSize_Y=par.npy;
4441civ2.inputFileName=[par.filename_nc1 '.nc'];
4442civ2.outputFileName=[filename '.nc'];
4443civ2.correlationBoxesSize_X=par.ibx;
4444civ2.correlationBoxesSize_Y=par.iby;
4445civ2.ro=par.rho;
4446%checkciv2.decimalShift=par.CheckDecimal;
4447%checkciv2.CheckDeformation=par.CheckDeformation;
4448if isequal(par.decimal,'1')
4449    civ2.decimalShift='y';
4450else
4451    civ2.decimalShift='n';
4452end
4453if isequal(par.deformation,'1')
4454    civ2.deformation='y';
4455else
4456    civ2.deformation='n';
4457end
4458if isequal(par.gridflag,'y')
4459    civ2.grid=par.gridname;
4460else
4461    civ2.grid='n';
4462    civ2.gridSpacing_X=par.dx;
4463    civ2.gridSpacing_Y=par.dy;
4464end
4465civ2.gridSpacing_X='10';
4466civ2.gridSpacing_Y='10';%NOTE: faut mettre gridSpacing pourque ca tourne, meme si c'est la grille qui est utilisee
4467if isequal(par.maskflag,'y')
4468    civ2.mask=par.maskname;
4469else
4470    civ2.mask='n';
4471end
4472civ2.dt=par.Dt;
4473civ2.unit='pixel';
4474civ2.absolut_time_T0=par.Time;
4475civ2.pixcmx='1';
4476civ2.pixcmy='1';
4477civ2.convectFlow='n';
4478
4479
4480% --- Executes on button press in TestPatch1.
4481function TestPatch1_Callback(hObject, eventdata, handles)
4482set(handles.TestPatch1,'BackgroundColor',[1 1 0])
4483drawnow
4484if get(handles.TestPatch1,'Value')
4485    ref_i=str2double(get(handles.ref_i,'String'));
4486    if strcmp(get(handles.ref_j,'Visible'),'on')
4487        ref_j=str2double(get(handles.ref_j,'String'));
4488    else
4489        ref_j=1;%default
4490    end
4491    [filecell,i1,i21,j1,j2,i1_civ2,i2_civ2,j1_civ2,j2_civ2,nom_type_nc,file_ref_fix1,file_ref_fix2]=...
4492        set_civ_filenames(handles,ref_i,ref_j,[0 0 1 0 0 0]);
4493   
4494    Data.ListVarName={'ny','nx','A'};
4495    Data.VarDimName= {'ny','nx',{'ny','nx'}};
4496   
4497    param_patch1=read_GUI(handles.Patch1);
4498    param_patch1.CivFile=filecell.nc.civ1{1};
4499    Param.Patch1=param_patch1;
4500    for irho=1:7
4501        [Data,errormsg]=civ_matlab(Param);% get the grid of x, y positions set for PIV
4502        if ~isempty(errormsg)
4503            msgbox_uvmat('ERROR',errormsg)
4504            return
4505        end
4506        SmoothingParam(irho)=Param.Patch1.SmoothingParam;
4507        Data.Civ1_U_Diff=Data.Civ1_U_Diff(Data.Civ1_FF==0);
4508        Data.Civ1_V_Diff=Data.Civ1_V_Diff(Data.Civ1_FF==0);
4509        DiffVel(irho)=sqrt(mean(Data.Civ1_U_Diff.*Data.Civ1_U_Diff+Data.Civ1_V_Diff.*Data.Civ1_V_Diff))
4510        NbSites(irho,:)=Data.Civ1_NbSites*numel(Data.Civ1_NbSites)/numel(Data.Civ1_U_Diff);
4511        Param.Patch1.SmoothingParam=2*Param.Patch1.SmoothingParam;
4512    end
4513    figure
4514    plot(SmoothingParam,DiffVel,'b',SmoothingParam,NbSites,'r')
4515    set(handles.TestPatch1,'BackgroundColor',[1 0 0])
4516else
4517    corrfig=findobj(allchild(0),'tag','corrfig');% look for a current figure for image correlation display
4518    if ~isempty(corrfig)
4519        delete(corrfig)
4520    end
4521    hview_field=findobj(allchild(0),'tag','view_field');% look for view_field
4522    if ~isempty(hview_field)
4523        delete(hview_field)
4524    end
4525end
4526%'nomtype2pair': creates nomencalture for index pairs knowing the image nomenclature
4527%---------------------------------------------------------------------
4528% [nom_type_pair]=nomtype2pair(nom_type,Dti,Dtj);
4529%---------------------------------------------------------------------           
4530
4531% OUTPUT:
4532%nom_type_nc
4533
4534%---------------------------------------------------------------------
4535% INPUT:
4536% 'nom_type': string defining the kind of nomenclature used:
4537     %nom_type='': constant name [filebase ext] (default output if 'nom_type' is undefined)
4538     %nom_type='*': the same  file [filebase ext] contains successive fields (ex avi movies)
4539     %nom_type='_i': series of files with a single index i preceded by '_'(e.g. 'aa_45.png').
4540     %nom_type='#' series of indexed images wich is not series_i [filebase index ext], e.g. 'aa045.jpg' or 'aa45.tif'
4541     %nom_type='_i_j' matrix of files with two indices i and j separated by '_'(e.g. 'aa_45_2.png')
4542     %nom_type='_i1-i2' from pairs from a single index (e.g. 'aa_45-47.nc')
4543     %nom_type='_i_j1-j2'pairs of j indices (e.g. 'aa_45_2-3.nc')
4544     %nom_type='_i1-i2_j' pairs of i indices (e.g. 'aa_45-46_2.nc')
4545     %nom_type='#a','#A', with a numerical index and an index letter(e.g.'aa045b.png'), OBSOLETE (replaced by 'series_i_j')
4546     %nom_type='%03d' or '%04d', series of indexed images with numbers completed with zeros to 3 or 4 digits, e.g.'aa045.tif'
4547     %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'
4548     %nom_type='raw_SMD', same as '#a' but with no extension ext='', OBSOLETE
4549     %nom_type='#_ab' from pairs of '#a' images (e.g. 'aa045bc.nc'), ext='.nc', OBSOLETE (replaced by 'netc_2D')
4550     %nom_type='%3dab' from pairs of '%3da' images (e.g. 'aa045bc.nc'), ext='.nc', OBSOLETE (replaced by 'netc_2D')
4551% Dti: ~=0 if i index pairs are used
4552% Dtj: ~=0 if i index pairs are used
4553
4554function NomTypeNc=nomtype2pair(NomTypeIma,mode)
4555
4556%determine nom_type_nc:
4557NomTypeNc='';%default
4558switch mode
4559    case 'pair j1-j2'     
4560    if ~isempty(regexp(NomTypeIma,'a$'))
4561        NomTypeNc=[NomTypeIma 'b'];
4562    elseif ~isempty(regexp(NomTypeIma,'A$'))
4563        NomTypeNc=[NomTypeIma 'B'];
4564    else
4565        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4566        if ~isempty(r)
4567            NomTypeNc='_1_1-2';
4568        end
4569    end
4570    case 'series(Dj)' 
4571        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4572        if ~isempty(r)
4573            NomTypeNc='_1_1-2';
4574        end
4575   case 'series(Di)'
4576        r=regexp(NomTypeIma,'(?<num1>\d+)_(?<num2>\d+)$','names');
4577        if ~isempty(r)
4578            NomTypeNc='_1-2_1';
4579        else
4580            NomTypeNc='_1-2';
4581        end
4582end
4583
4584function NomType_Callback(hObject, eventdata, handles)
Note: See TracBrowser for help on using the repository browser.