source: trunk/src/civ.m @ 360

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

civ: bugs corrected. Iintroduction of an xm file for parameters read using the new fct fill_GUI (to test and improve)
cleaning in uvmat. Possibility of using blank increment added (go to the next available file)
fullfile_uvmat: case of two equal indices in a pair, bug repair.
find_fileseries: improved speed.

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