source: trunk/src/civ.m @ 418

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