source: trunk/src/civ.m @ 498

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

various bug corrections, compatibilty with older PIV data

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