source: trunk/src/civ.m @ 482

Last change on this file since 482 was 482, checked in by gostiaux, 12 years ago

New conventions to launch jobs

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