source: trunk/src/civ.m @ 316

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

a few more bugs corrected, now the new civ_matlab works for civ1,fix1, patch1

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