source: trunk/src/series/civ_input.m @ 597

Last change on this file since 597 was 597, checked in by sommeria, 8 years ago

civ_series added

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