source: trunk/src/civ.m @ 397

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

civ_matlab and patch improved, changes in the management of interpolation (still in progress).
adapatation to movies (use of VideoReader?)

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