source: trunk/src/civ.m @ 384

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

pb with masks corrected
bug in fileparts_uvmat corrected
find_file_series corrected so that it finds the root name corresponding tothe existing xml file : for instance Dalsa1_0001 gives root=Dalsa1 instead of Dalsa
bug corrected in uvmat, runpm (j1 and j2 set to 1 when not visible)

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