source: trunk/src/civ.m @ 354

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