source: trunk/src/civ.m @ 364

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

civ2, fix2, patch2 introduced under Matlab (no interpolation and rotation done yet)
small corrections in plot_field and read_civdata

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