source: trunk/src/civ.m @ 426

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

compiled matlab civ introduced in Batch mode,
minor bugs fixed for histogram of velocity

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