source: trunk/src/civ.m @ 370

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

bug corrected in civ_uvmat civ2, opening new files made more convenient in civ

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