source: trunk/src/civ.m @ 389

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

several bugs corrected: object managing, tps filter...

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