source: trunk/src/civ.m @ 483

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

civ set to accept automatic input in the absence of PARAM.xml. Still problem with run time address
zoom improved to deal with elongated plots
better link between PIV and images in uvmat.

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