source: trunk/src/civ.m @ 338

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

Number of cores can now be chosen

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