source: trunk/src/civ.m @ 405

Last change on this file since 405 was 399, checked in by sommeria, 13 years ago

implementation of thin plate interpolation (proj on planes with mode 'filter'), rationalisation of variable formats in civ_matlab

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