source: trunk/src/civ.m @ 368

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

various bugs fixed

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