source: trunk/src/civ.m @ 315

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

many corrections, use of the new GUI civ with mask, grid and the new matlab civ1 and fix
pivlab now included in civ_matlab which contains all matlab subfunctions for civ.

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