source: trunk/src/civ.m @ 415

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

bugs corrected: problems with Dt in read_civxdata and uvmat.

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