source: trunk/src/civ.m @ 367

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

Batch on legi clusters works with civ matlab

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