source: trunk/src/civ.m @ 398

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

find_file_series corrected and rationalised, with induced transforms in uvmat, civ, series

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