source: trunk/src/civ.m @ 355

Last change on this file since 355 was 355, checked in by sommeria, 9 years ago

civ updated with new functions for opening files, consistently with uvmat
Bugs to be expected (use previous version then)

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