source: trunk/src/civ.m @ 339

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

name2display replaced by fileparts_uvmat and find_file_series in series.
name2display partially replaced in civ.m (to be continued)
series.fig reorganized with panels.

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