function oki = straightCIv1(actionstr)

%	STRAIGHT command interpreter

%       STRAIGHT --- Speech Transformation and Representation using
%       Adaptive Interpolation of weiGHTed spectrum
%	Interactive interface for trial use
%
%       (c) Copyright ATR Human Information Processing Research
%       Laboratories, 1996,1997
%       Author and Inventor: Hideki Kawahara
%       02/July/1996
%       04/July/1996
%       07/July/1996
%	07/Sep./1996
%	01/Nov./1996
%	25/Nov./1996 TEMPO enhancement
%	30/Nov./1996 This version is with AG window trick
%	25/Dec./1996 This version is with AG window trick
%	27/Dec./1996 using fundamentalness as U/V measure
%	02/Feb./1997 without V/UV decision
%	05/Feb./1997 Bug Fix
%	10/Feb./1997 Maximum liklihood F0 tracking
%	15/Feb./1997 frequency range division
%	15/Feb./1997 Big bug fix in spectral calculation
%	22/Feb./1997 No need for temporal smoothing (thanks for the new window)
%	11/Mar./1997 New wavelet for F0 extraction
%	03/May /1997 Quick bug fix for Matlab v5
%	30/May /1997 Quick bug fix for Matlab v5
%	21/June/1997 Quick bug fix for new fundamentalness
%	12/Aug./1997 Revised optimum smoother (minor revision)
%	13/Aug./1997 Revised SPIKES scaling property and TD enhancement
%	19/Dec./1997 Revised for mixed mode excitation
%	09/Jan./1998 GUI command line interpreter
%	29/Jan./1998 Integrated with mixed mode and GUI
%	02/Feb./1998 Minor inconvenience fix
%	03/Fev./1998 Minor bug fix
%	13/April/1999 New pitch extractor
%	19/April/1999 Minor modificatio to display information
%	22/April/1999 Minor modificatio for unvoiced spectrum
%	05/May  /1999 New periodic/aperiodic mixing ratio
%	21/July/1999  reduced version with crisp V/UV decision
%	17/Feb./2001 Bug fix for multi channel sound files
%	30/May/2001 New aperiodicity measure and control
%	8/April/2002 modified to remove magic numbers
%	26/June/2002 minor modification: two globals are added.
%	08/Dec./2002 Default parameters were made user definable.
%   04/Feb./2003 Aperiodicity correction and bug fix in STRAIGHTbody proc.
%   31/Aug./2004 Bug fix for f0 abnormal values
%	30/April/2005 modification for Matlab v7.0 compatibility

global n2sgram nsgram n3sgram n2sgrambk nwsgram xold x f0floor f0ceil fs framem shiftm f0shiftm ...
  fftl eta pc framel fftl2 acth pwth pcnv fconv sconv delsp gdbw cornf fname ofname delfracind ...
  tpath cpath ... %%paraminitialized
  mag delfrac hr f0raw f0l f0var f0varL sy pcorr pecorr ... %%gobjlist ...
  upsampleon hhb pwt pwh amp defaultendian indefaultendian outdefaultendian f0varbak

global maphandles

global bv % 02/Sept./1999
global apv dpv % 21/Sept./1999
global defaultch % 16/Feb./2001
global apve dpve % 22/Oct./2001

global f0v vrv % 25/June/2002 for debug
global ecrt % 03/Feb./2003 for C/N based correction of dpv

oki = true;

switch(actionstr)
  %-----------------------------------------------
  %	Initialization part
  %-----------------------------------------------
  case 'GUIinitialize'
    clear global
    straightCIv1 initializeparams;
    straightPanel98bak;
    syncgui;
    straightCIv1 syncbuttons;
  case 'resetparamsbtn'
    straightCIv1 initializeparams;
    syncgui;
  case 'initialize'
    clear global n2sgram nsgram n3sgram n2sgrambk nwsgram xold x f0raw f0l sy hhb
    straightCIv1 initializeparams;
    syncgui;
    straightCIv1 syncbuttons;
  case 'initializeparams'
    if exist('defaultparams.m','file')==0 %	08/Dec./2002
      f0floor=40;
      f0ceil=800;
      fs=22050;	% sampling frequency (Hz)
      framem=40;	% default frame length for pitch extraction (ms)
      shiftm=1;       % default frame shift (ms) for spectrogram
      f0shiftm=1;     % default frame shift (ms) for F0 information
      fftl=1024;	% default FFT length
      eta=1.4;        % time window stretch factor
      pc=0.6;         % exponent for nonlinearity
      mag=0.2;      % This parameter should be revised.
      framel=framem*fs/1000;

      if fftl < framel
        fftl=2^ceil(log(framel)/log(2));
      end;
      fftl2=fftl/2;
      defaultch=1; % 17/Feb./2001

      %-------------- Decision parameter for source information

      acth=0.5;	% Threshold for normalized correlation (dimension less)
      pwth=32;	% Threshold for instantaneous power below maximum (dB)

      %-----------------------------------------------------
      %       Synthesis parameters
      %-----------------------------------------------------

      pcnv=1.0; 	% pitch stretch
      fconv=1.0; 	% frequency stretch
      sconv=1.0; 	% time stretch

      %	  delsp=2; 	%  standard deviation of random group delay in ms
      delsp=0.5; 	%  standard deviation of random group delay in ms 26/June/2002
      gdbw=70; 	% smoothing window length of random group delay (in Hz)
      %	  cornf=3000;  	% corner frequency for random phase (Hz)
      cornf=4000;  	% corner frequency for random phase (Hz) 26/June 2002
      delfrac=0.2;  % This parameter should be revised.
      delfracind=0;

      %-----------------------------------------------------
      %	file parameters
      %-----------------------------------------------------

      fname='none';		% input data file name

      hr='on';
      tpath=pwd;
      if strcmp(computer,'MAC2')==0
        tpath=[tpath '/'];
      end;
      upsampleon=0;
    else %	08/Dec./2002
      defaultparams;
    end; % of if exist('defaultparams.m','file')==0 %	08/Dec./2002
    defaultendian=chkdefaultendian;
    indefaultendian=defaultendian;
    outdefaultendian=defaultendian;
  case 'resetvalues'
    straightCIv1 initializeparams
    syncgui;

    %-----------------------------------------------------
    %	file I/O part
    %-----------------------------------------------------
  case 'bininputformat'
    hh=findobj('Tag','bininputformat');
    indefaultendian=get(hh,'Value');
  case 'binoutputformat'
    hh=findobj('Tag','binoutputformat');
    outdefaultendian=get(hh,'Value');
  case 'readfile'
    [fname,cpath]=uigetfile(...
      {'*.wav';'*.aif';'*.WAV';'*.aiff';'*.dat';'*.dat'},...
      'sound file input');
    if fname(1)~=0
      tcpath=[char(39) cpath char(39)];
      eval(['cd ' tcpath]);
      if ~isempty(strfind(lower(fname),'.wav')) % 16/Feb./2001
        [x,fs]=audioread(fname);
        x=x*32768;
      elseif ~isempty(strfind(lower(fname),'.aif')) % 16/Feb./2001
        [x,fs]=aiffread(fname);
      else
        if indefaultendian==1
          fid=fopen(fname,'r','ieee-le');
        else
          fid=fopen(fname,'r','ieee-be');
        end;
        x=fread(fid,'short')';
        fclose(fid);
      end;
      [tnn,tmm]=size(x); % 16/Feb./2001
      if min(tnn,tmm)>1 % 16/Feb./2001
        switch tnn>tmm
          case 1,
            x=x(:,defaultch);
          case 0,
            x=x(defaultch,:);
        end;
      end;
      x=x(:)'; % make sure that the vector is row vector
      xold=x;
      x=xold+std(x)/1000*randn(size(x));  % 03/Feb./2001
    else
      disp('file input is cancelled. ');
      disp(' ');
    end;
    syncgui;
    straightCIv1 syncbuttons;

  case 'savefile'
    tcpath=[char(39) tpath char(39)];
    eval(['cd ' tcpath]);
    tsy=sy; tfs=fs;
    if upsampleon
      switch fs
        case {8000, 10000, 11025, 12000}
          tfs=fs*4; tsy=interp(sy,4);
        case {16000, 20000, 22050, 24000}
          tfs=fs*2; tsy=interp(sy,2);
      end;
    end;
    [ofname,tpath]=uiputfile('*','sound file output');
    if ofname(1)~=0
      if ~isempty(strfind(ofname,'.wav'))
        audiowrite([tpath ofname], tsy/32768,tfs);
      elseif ~isempty(strfind(ofname,'.aif'))
        ok=aiffwrite(tsy,tfs,16,ofname);
        if isempty(ok)
          disp(['File output is failed. ' ofname ' was not written.']);
        end;
      else
        if outdefaultendian==1
          fid2=fopen([tpath ofname],'w','ieee-le');
        else
          fid2=fopen([tpath ofname],'w','ieee-be');
        end;
        fwrite(fid2,tsy,'short');
        fclose(fid2);
      end;
      disp(['% Saved successfully as: ' ofname]);
      disp(' ');
    else
      disp('file output is cancelled. ');
      disp(' ');
    end;

    %-----------------------------------------------------
    %	Display spectrogram group
    %-----------------------------------------------------
  case 'dispnsgram'
    mxil=max(max(20*log10(nsgram+0.001)));
    [nsy,nsx]=size(nsgram);
    figure;
    imagesc((0:nsx-1)*shiftm,(0:nsy-1)/nsy*fs/2, ...
      max(20*log10(nsgram+0.001),mxil-50));
    axis('xy'); colormap(1-gray);
    title(['Equal resolution spectrum of ' fname ' ' date ' ' mktstr]);
    xlabel('time (ms)');
    ylabel('frequency (Hz)');
  case 'dispnwsgram'
    mxil=max(max(20*log10(nwsgram+0.001)));
    [nsy,nsx]=size(nwsgram);
    figure;
    imagesc((0:nsx-1)*shiftm,(0:nsy-1)/nsy*fs/2, ...
      max(20*log10(nwsgram+0.001),mxil-50));
    axis('xy'); colormap(1-gray);
    title(['Wide band spectrum of ' fname ' ' date ' ' mktstr]);
    xlabel('time (ms)');
    ylabel('frequency (Hz)');
  case 'dispn2sgram'
    mxil=max(max(20*log10(n2sgram+0.001)));
    [nsy,nsx]=size(n2sgram);
    figure;
    imagesc((0:nsx-1)*shiftm,(0:nsy-1)/nsy*fs/2,...
      max(real(20*log10(n2sgram+0.001)),mxil-50));
    axis('xy'); colormap(1-gray);
    title(['enhanced spectrum of ' fname ' ' date ' ' mktstr]);
    xlabel('time (ms)');
    ylabel('frequency (Hz)');
  case 'dispn2sgrambk'
    mxil=max(max(20*log10(n2sgrambk+0.001)));
    [nsy,nsx]=size(n2sgrambk);
    figure;
    imagesc((0:nsx-1)*shiftm,(0:nsy-1)/nsy*fs/2,...
      max(real(20*log10(n2sgrambk+0.001)),mxil-50));
    axis('xy'); colormap(1-gray);
    title(['Interpolated spectrum of ' fname ' ' date ' ' mktstr]);
    xlabel('time (ms)');
    ylabel('frequency (Hz)');
  case 'dispn3sgram'
    mxil=max(max(20*log10(n3sgram+0.001)));
    [nsy,nsx]=size(n3sgram);
    figure;
    imagesc((0:nsx-1)*shiftm,(0:nsy-1)/nsy*fs/2,...
      max(real(20*log10(n3sgram+0.001)),mxil-50));
    axis('xy'); colormap(1-gray);
    title(['enhanced spectrum (without 2nd strctr) of ' fname ' ' date ' ' mktstr]);
    xlabel('time (ms)');
    ylabel('frequency (Hz)');
  case 'disphhbspectrograme'
    bb=1:length(n2sgram(1,:));
    mmx=hhb(:,bb).*n3sgram+(1-hhb(:,bb)).*nwsgram;
    mxil=max(max(20*log10(mmx+0.001)));
    [nsy,nsx]=size(mmx);
    figure;
    imagesc((0:nsx-1)*shiftm,(0:nsy-1)/nsy*fs/2,...
      max(real(20*log10(mmx+0.001)),mxil-50));
    axis('xy'); colormap(1-gray);
    title(['final composite spectrum of ' fname ' ' date ' ' mktstr]);
    xlabel('time (ms)');
    ylabel('frequency (Hz)');
  case 'showF0'
    figure(gcf+1); subplot(111);plot((1:length(f0l))*f0shiftm,f0l); grid on;
    title(['F0 of ' fname ' ' date ' ' mktstr]);
    ylabel('frequency (Hz)'); xlabel('time (ms)');

    %-----------------------------------------------
    %	audio display part
    %-----------------------------------------------
  case 'playoriginal'
    straightsound(xold,fs);
  case 'playsynth'
    straightsound(sy,fs);

    %-----------------------------------------------
    %	parameter modification part
    %-----------------------------------------------
  case 'peekvars'  % This is the most poweful interaction
    keyboard;
    syncgui;
    straightCIv1 syncbuttons;
  case 'getfsmenu'
    fs=getfsfrommenu(gco);
    syncgui;
  case 'editf0ceil'
    f0ceil=getvalufromedit(gco,800);
    syncgui;
  case 'editf0floor'
    f0floor=getvalufromedit(gco,40);
    syncgui;
  case 'editshiftm'
    f0shiftm=getvalufromedit(gco,1);
    shiftm=f0shiftm;
    syncgui;
  case 'fftledit'
    syncgui;
  case 'wndwstrtchedit'
    eta=getvalufromedit(gco,1.4);
    syncgui;
  case 'pwrcnstntedit'
    pc=getvalufromedit(gco,0.6);
    syncgui;
  case 'magfactoredit'
    mag=getvalufromedit(gco,0.2);
    syncgui;
  case 'delfracedit'
    delfrac=getvalufromedit(gco,0.2);
    syncgui;
  case 'delspedit'
    delsp=getvalufromedit(gco,2);
    syncgui;
  case 'cornfedit'
    cornf=getvalufromedit(gco,2400);
    syncgui;
  case 'gdbwedit'
    gdbw=getvalufromedit(gco,70);
    syncgui;
  case 'pcnvedit'
    pcnv=getvalufromedit(gco,1);
    syncgui;
  case 'fconvedit'
    fconv=getvalufromedit(gco,1);
    syncgui;
  case 'sconvedit'
    sconv=getvalufromedit(gco,1);
    syncgui;
  case 'tpathedit'
    tpath=get(gco,'Value');
    syncgui;
  case 'pcnvslider'
    pcnv=10.0.^get(gco,'Value');
    syncgui;
  case 'fconvslider'
    fconv=3.0.^get(gco,'Value');
    syncgui;
  case 'sconvslider'
    sconv=10.0.^get(gco,'Value');
    syncgui;
  case 'delfracradio'
    delfracind=~delfracind;
    syncgui;
  case 'delspradio'
    delfracind=~delfracind;
    syncgui;
  case 'upsamplebtn'
    upsampleon=~upsampleon;
    syncgui;

    %--------------------------------------------------
    %	non-linear manipulations
    %--------------------------------------------------
  case 'FqNLbtn'
    hh=findobj('Tag','FqNLbtn');
    if get(hh,'UserData') ==0 ||  isempty(get(hh,'UserData'))
      set(hh,'UserData',1);
      set(hh,'BackgroundColor',[0.9 0.33333 0.33333]);
      bendline initialize;
    else
      set(hh,'UserData',0);
      set(hh,'BackgroundColor',[0.733333 0.733333 0.733333]);
      bendline close;
    end;

    %	This part is obsolate. This part will be revised completely.
  case 'interactSGRAM'
    figure;
    mxil=max(max(20*log10(n2sgram)));
    imagesc(max(20*log10(n2sgram),mxil-45));
    axis('xy'); colormap(1-gray);
    title(['Interpolated spectrum of ' fname ' ' date ' ' mktstr]);
    disp('%	Now you have to define trajectory using mouse');
    disp('%	Please type "return", if you are ready.');
    disp('%	It is recommended for you to select important portion ');
    disp('%	using "zoom on" command.');
    disp('%	Please do not forget to issue "zoom off" before continue.');
    disp('%	In graphical input interaction, click defines point and return');
    disp('%	notifies it is the last point.');
    keyboard;
    disp('%	Interaction started. Put the cursor inside the graphics.');
    zoom off;
    getTrace;
    disp('%	You can modify spectrum using the following command.');
    disp('%       n2sgram=n2sgrambk.*(1+nsgm).^X;');
    disp('%		X*6 dB amplification is made.');
    disp('%		Default 6dB amplification was already done.');
    disp('%	If you are OK, type "return". ');
    disp('%	Otherwise, please change.');
    n2sgram=n2sgrambk.*(1+nsgm);

    %-------------------------------------------
    %	mapping control part
    %-------------------------------------------
  case 'frequencymapmod'
    [nii,~]=size(n2sgram);
    vx=(0:nii-1)/(nii-1);
    idcv=vx*maphandles(20)+sin(vx*pi)*maphandles(21)+sin(2*pi*vx)*maphandles(22);
    fconv=max(1,min(nii,idcv*(nii-1)+1));

    %-------------------------------------------
    %	synthesis part
    %-------------------------------------------
  case 'synthesizechar' % This part is useless now
    disp('%-------- Current Synthesis parameters ------');
    disp(['%	delsp=' num2str(delsp) ...
      ';     % standard deviation of random group delay in ms']);
    disp(['%	gdbw=' num2str(gdbw) ...
      ';    % smoothing window length of random group delay (in Hz)']);
    disp(['%	cornf=' num2str(cornf) ...
      ';  % corner frequency for random phase (in Hz)']);
    disp(['%	pcnv=' num2str(pcnv) ...
      ';    % pitch stretch']);
    disp(['%	fconv=' num2str(fconv) ...
      ';   % frequency stretch']);
    disp(['%	sconv=' num2str(sconv) ...
      ';   % time stretch']);
    disp('%	');
    disp('%	If you are happy with these parameters please type "return".');
    disp('%	You can change these setting using Matlab command(s)');
    disp('%	If you want to restore default parameters please type');
    disp('%	"default22kparams"  There are similar prog. for 12k,16k files.');
    keyboard;
    disp('%	Now, synthesis is in progress. Please wait a moment.');
    syncgui;
    straightCIv1 synthesize

  case 'synthesizegradedqqq'  % OBSOLATE!!!
    hh=findobj('Tag','FqNLbtn');
    if ~isempty(hh)
      if ~isempty(get(hh,'UserData'))
        if get(hh,'UserData')==1
          straightCIv1 frequencymapmod
        end;
      end;
    end;
    sy=straightSynthTC01(n3sgram,nwsgram,f0raw,hhb,shiftm,fs, ...
      pcnv,fconv,sconv,gdbw,delfrac,delsp,cornf,delfracind);
    dBsy=powerchk(sy,fs,15); % 23/Sept./1999
    cf=(20*log10(32768)-22)-dBsy;
    sy=sy*(10.0.^(cf/20));
    disp('%	Done!');
    straightCIv1 syncbuttons;

  case 'synthesizegraded'
    hh=findobj('Tag','FqNLbtn');
    if ~isempty(hh)
      if ~isempty(get(hh,'UserData') )
        if get(hh,'UserData')==1
          straightCIv1 frequencymapmod
        end;
      end;
    end;
    sy=straightSynthTB07ca(n3sgram,f0raw,shiftm,fs, ...
      pcnv,fconv,sconv,gdbw,delfrac,delsp,cornf,delfracind, ...
      aperiodiccomp(apv,dpv,5,f0raw,f0shiftm),1); % 8/April/2002
    dBsy=powerchk(sy,fs,15); % 23/Sept./1999
    cf=(20*log10(32768)-22)-dBsy;
    sy=sy*(10.0.^(cf/20));
    disp('%	Done!');
    straightCIv1 syncbuttons;

  case 'synthesize'
    hh=findobj('Tag','FqNLbtn');
    if ~isempty(hh)
      if ~isempty(get(hh,'UserData') )
        if get(hh,'UserData')==1
          straightCIv1 frequencymapmod
        end;
      end;
    end;
    sy=straightSynthTB06(n3sgram,f0raw,f0var,f0varL,shiftm,fs, ...
      pcnv,fconv,sconv,gdbw,delfrac,delsp,cornf,delfracind);
    dBsy=powerchk(sy,fs,15); % 23/Sept./1999
    cf=(20*log10(32768)-22)-dBsy;
    sy=sy*(10.0.^(cf/20));
    disp('%	Done!');
    straightCIv1 syncbuttons;

    %------------------------------------------------------
    %	analysis part
    %	This part is modified to introduce a new F0 and
    %	source information extraction method. (19/April/1999)
    %------------------------------------------------------
  case 'source'
    nvo=24;
    nvc=ceil(log(f0ceil/f0floor)/log(2)*nvo);
    [f0v,vrv,dfv,~,aav]=fixpF0VexMltpBG4(xold,fs,f0floor,nvc,nvo,1.2,1,shiftm,1,5,0.5,1);
    title([fname '  ' datestr(now,0)]);
    %drawnow;
    [~,~]=size(f0v);
    subplot(614);
    [pwt,pwh]=plotcpower(xold,fs,shiftm);drawnow;

    [f0raw,irms,~,amp]=f0track5(f0v,vrv,dfv,pwt,pwh,aav,shiftm);
    f0t=f0raw;avf0=mean(f0raw(f0raw>0));
    f0t(f0t==0)=f0t(f0t==0)*NaN;tt=1:length(f0t);
    %	  keyboard;
    subplot(615);plot(tt*shiftm,f0t,'g');grid on;
    if ~isnan(avf0)
      axis([1 max(tt)*shiftm ...
        min(avf0/sqrt(2),0.95*min(f0raw(f0raw>0)))  ...
        max(avf0*sqrt(2),1.05*max(f0raw(f0raw>0)))]);
    end;
    ylabel('F0 (Hz)');
    %----------- 31/July/1999
    hold on;
    dn=floor(fs/(f0ceil*3*2)); % fix by H.K. at 28/Jan./2003
    [f0raw,ecr]=refineF06(decimate(xold,dn),fs/dn,f0raw,1024,1.1,3,f0shiftm,1,length(f0raw)); % 31/Aug./2004
    f0t=f0raw;%%avf0=mean(f0raw(f0raw>0));
    f0t(f0t==0)=f0t(f0t==0)*NaN;tt=1:length(f0t);
    subplot(615);plot(tt*shiftm,f0t,'k');hold off;
    drawnow
    %----------- 31/July/1999

    tirms=irms;
    tirms(f0raw==0)=tirms(f0raw==0)*NaN;
    tirms(f0raw>0)=-20*log10(tirms(f0raw>0));
    ecrt=ecr;
    ecrt(f0raw==0)=ecrt(f0raw==0)*NaN;
    subplot(616);hrms=plot(tt*shiftm,tirms,'g',tt*shiftm,20*log10(ecrt),'r'); %31/July/1999
    set(hrms,'LineWidth',2);hold on
    plot(tt*shiftm,-10*log10(vrv),'k.');
    grid on;hold off
    axis([1 max(tt)*shiftm -10 60]);
    xlabel('time (ms)');ylabel('C/N (dB)');
    drawnow;
    irmsz=irms*0;

    %---------- This part is for maintaining compatibility with old synthesis routine ----
    f0var=max(0.00001,irms-irmsz).^2;
    f0var(f0var>0.99)=f0var(f0var>0.99)*0+100;
    f0var(f0raw==0)=f0var(f0raw==0)*0+100;
    f0varbak = f0var;  % backup for f0var (18/July/1999)
    f0var=f0var/2;  %  2 is a magic number. If everything is OK, it should be 1.
    f0var=(f0var>0.9);  % This modification is to make V/UV decision crisp  (18/July/1999)
    f0varL=f0var;
    %-------------------------------------------------------------------------------------
    f0raw(f0raw<=0)=f0raw(f0raw<=0)*0; % safeguard 31/August/2004
    f0raw(f0raw>f0ceil)=f0raw(f0raw>f0ceil)*0+f0ceil; % safeguard 31/August/2004

    straightCIv1 syncbuttons;

    %--------------------------------------------------------------
    %	classic STRAIGHT with a single V/UV measure
    %--------------------------------------------------------------
  case 'straightcore'
    disp('% Now, adaptive window analysis has started. Please wait a moment.');
    [n2sgrambk,nsgram]=straightBodyC03ma(xold,fs,shiftm,fftl,f0raw,f0var,f0varL,eta,pc); %%
    if mag>0
      n2sgram=specreshape(fs,n2sgrambk,eta,pc,mag,f0raw);
    else
      n2sgram=n2sgrambk;
    end;
    straightCIv1 syncbuttons;

    %--------------------------------------------------------------
    %	revised STRAIGHT with a multi band graded V/UV decision (OBSOLATE!!)
    %--------------------------------------------------------------
  case 'bandcorrbtnqqq'
    [n2sgrambk,nsgram,nwsgram]= ...
      straightBodyB04m(xold,fs,shiftm,fftl,f0raw,eta,pc);
    straightCIv1 syncbuttons;
    if mag>0
      n2sgram=specreshape(fs,n2sgrambk,eta,pc,mag,f0raw);
    else
      n2sgram=n2sgrambk;
    end;

    [pcorr,pecorr]=BcorrMap(xold,fs,f0raw,shiftm);

    wvm3=wfromMap4(pcorr,pecorr,n2sgram,fs);
    emap=max(pcorr,pecorr);
    hh=wvm3'*emap;

    a=0.32;b=15;c=0.15;   % blending parameter; this is very tentative
    hhb=max(0,(1.0./(1+exp(-(hh-a)*b))-1.0/(1+exp(-(c-a)*b))) ...
      /(1.0/(1+exp(-(1-a)*b))-1.0/(1+exp(-(c-a)*b))));
    straightCIv1 syncbuttons;

    %-----------------------------------------

    %   MBE type analysis  2/Sept./1999

    %-----------------------------------------

  case 'bandcorrbtn'
        [n2sgrambk,nsgram]=straightBodyC03ma(xold,fs,shiftm,fftl,f0raw,f0var,f0varL,eta,pc);
    if mag>0
      n2sgram=specreshape(fs,n2sgrambk,eta,pc,mag,f0raw);
    else
      n2sgram=n2sgrambk;
    end;

    [apvq,dpvq,apve,dpve]=aperiodicpartERB2(xold,fs,f0raw,f0shiftm,5,fftl/2+1); % 10/April/2002
    apv=10*log10(apvq); % for compatibility
    dpv=10*log10(dpvq); % for compatibility
    %- ---------
    %   Notes on aperiodicity estimation: The previous implementation of
    %   aperiodicity estimation was sensitive to low frequency noise. It is a
    %   bad news, because environmental noise usually has its power in the low
    %   frequency region. The following corrction uses the C/N information
    %   which is the byproduct of fixed point based F0 estimation.
    %   by H.K. 04/Feb./2003
    %- ---------
    dpv=correctdpv(apv,dpv,5,f0raw,ecrt,f0shiftm,fs); % Aperiodicity correction 04/Feb./2003 by H.K.

    bv=boundmes2(apv,dpv,fs,f0shiftm,5,fftl/2+1);

    figure;

    semilogy((0:length(bv)-1)*f0shiftm,0.5./10.0.^(bv));grid on;
    straightCIv1 syncbuttons;

  case 'remove2ndstructue'
    n3sgram=rmv2nd(n2sgram,f0raw,fs);
    straightCIv1 syncbuttons;

  case 'bypassbtn'
    n3sgram=n2sgram;
    straightCIv1 syncbuttons;

    %-----------------------------------------------------------------
    %	suppress buttons which are nor appropriate
    %-----------------------------------------------------------------
  case 'syncbuttons'
    hh=findobj('Tag','analyzesrcbtn');
    if length(xold) >fftl
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','bandcorrbtn');
    if length(f0raw) >5
      set(hh,'Enable','on');  % Enabled again 02/Sept./1999

    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','analyzespcbtn');
    if length(f0raw) >5
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','bypassbtn');
    if length(n2sgram) >2
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','remove2ndbtn');
    if length(n2sgram) >2
      %		  set(hh,'Enable','on');  % commented out at 21/July/1999
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','synthgradbtn');
    if (length(bv) >2) && (length(n3sgram)>2)
      set(hh,'Enable','on');  % enabled again at 02/Sept./1999
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','synthesizebtn');
    if length(n3sgram) >2
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','savetobtn');
    if length(sy) >fftl
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','adaptivespecbtn');
    if length(nsgram) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','widespecbtn');
    if length(nwsgram) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','smoothedspecbtn');
    if length(n2sgrambk) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','dispn2sgrambtn');
    if length(n2sgram) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','removedspecbtn');
    if length(n3sgram) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','cmpstspecgrambtn');
    if length(hhb) >1
      %		  set(hh,'Enable','on');  %  commented out on 21/July/1999
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','playorgbtn');
    if length(xold) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;
    %----------------------------------------------------
    hh=findobj('Tag','playsynthbtn');
    if length(sy) >1
      set(hh,'Enable','on');
    else
      set(hh,'Enable','off');
    end;

end;
end

function defaultendian=chkdefaultendian
%	defaultendian	: 1-littel endian, 2-big endian

gg=computer;
switch gg(1:3)
  case 'PCW'
    defaultendian=1;
  case 'MAC'
    defaultendian=2;
  case 'SUN'
    defaultendian=2;
  case 'SOL'
    defaultendian=2;
  case 'HP7'
    defaultendian=1;
  case 'SGI'
    defaultendian=2;
  case 'ALP'
    defaultendian=1;
  case 'AXP'
    defaultendian=1;
  case 'LNX'
    defaultendian=1;
  otherwise
    defaultendian=2;
end;
end


function test_issue1601

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY bids_sidecar ft_read_header ft_read_sens

%%

cd(dccnpath('/home/common/matlab/fieldtrip/data/test/issue1601'));

%%

hdr  = ft_read_header('sub-RESP0521/ses-1/ieeg/sub-RESP0521_ses-1_task-Sleep_run-060307_ieeg.vhdr');
dat  = ft_read_data  ('sub-RESP0521/ses-1/ieeg/sub-RESP0521_ses-1_task-Sleep_run-060307_ieeg.vhdr');
evt  = ft_read_event ('sub-RESP0521/ses-1/ieeg/sub-RESP0521_ses-1_task-Sleep_run-060307_ieeg.vhdr');
elec = ft_read_sens  ('sub-RESP0521/ses-1/ieeg/sub-RESP0521_ses-1_task-Sleep_run-060307_ieeg.vhdr');


pkg load image
files = dir('tmp/all/*.jpg');
for d=1:length(files)
file_name = fullfile('tmp/all', files(d).name);
fprintf('%s\n', file_name);
I = imread(file_name);
max_wh = max(size(I));
if max_wh > 1024
    I = imresize(I, 1024/max_wh);
end

b = pencil_draw(I);
R = colour_pencil_draw(I);
imwrite(b, strcat('pencil_',files(d).name), 'jpg');
imwrite(R, strcat('colour_',files(d).name), 'jpg');
end


function varargout = plot(varargin)
% plot method for GIfTI objects
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: plot.m 5888 2014-02-19 19:54:12Z guillaume $

% if ishandle(varargin{1})
%     h = figure(varargin{1});
% else
%     h = figure;
%     %axis equal;
%     %axis off;
%     %camlight;
%     %camlight(-80,-10);
%     %lighting phong;
% end
% cameramenu;

cdata = [];
ax = [];
if nargin == 1
    this = varargin{1};
    h = gcf;
else
    if ishandle(varargin{1})
        ax = varargin{1};
        h = figure(get(ax,'parent'));
        this = varargin{2};
    else
        this = varargin{1};
        h = gcf;
        cdata = subsref(varargin{2},struct('type','.','subs','cdata'));
    end
    if nargin > 2
        indc = varargin{3};
    else
        indc = 1;
    end
end

if isempty(ax), ax = axes('Parent',h); end
axis(ax,'equal');
axis(ax,'off');
hp = patch(struct(...
    'vertices',  subsref(this,struct('type','.','subs','vertices')),...
    'faces',     subsref(this,struct('type','.','subs','faces'))),...
    'FaceColor', 'b',...
    'EdgeColor', 'none',...
    'Parent',ax);

if ~isempty(cdata)
    set(hp,'FaceVertexCData',cdata(:,indc), 'FaceColor','interp')
end

axes(ax);
camlight;
camlight(-80,-10);
lighting phong;
axes(ax);
cameramenu;

if nargout
    varargout{1} = hp;
end


function demo(no_compile)

% AUTORIGHTS
% -------------------------------------------------------
% Copyright (C) 2011-2012 Ross Girshick
% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick
%
% This file is part of the voc-releaseX code
% (http://people.cs.uchicago.edu/~rbg/latent/)
% and is available under the terms of an MIT-like license
% provided in COPYING. Please retain this notice and
% COPYING if you use this file (or a portion of it) in
% your project.
% -------------------------------------------------------

startup;

if ~exist('no_compile', 'var')
  fprintf('compiling the code...');
  compile;
  fprintf('done.\n\n');
end

load('VOC2007/car_final');
model.vis = @() visualizemodel(model, ...
                  1:2:length(model.rules{model.start}));
test('000034.jpg', model, 1);

load('INRIA/inriaperson_final');
model.vis = @() visualizemodel(model, ...
                  1:2:length(model.rules{model.start}));
test('000061.jpg', model, 2);

load('VOC2007/person_grammar_final');
model.class = 'person grammar';
model.vis = @() visualize_person_grammar_model(model, 6);
test('000061.jpg', model, 2);

load('VOC2007/bicycle_final');
model.vis = @() visualizemodel(model, ...
                  1:2:length(model.rules{model.start}));
test('000084.jpg', model, 1);

function test(imname, model, num_dets)
cls = model.class;
fprintf('///// Running demo for %s /////\n\n', cls);

% load and display image
im = imread(imname);
clf;
image(im);
axis equal;
axis on;
title('input image');
disp('input image');
disp('press any key to continue'); pause;
disp('continuing...');

% load and display model
model.vis();
disp([cls ' model visualization']);
disp('press any key to continue'); pause;
disp('continuing...');

% detect objects
tic;
[ds, bs] = imgdetect(im, model, -1);
toc;
top = nms(ds, 0.5);
top = top(1:min(length(top), num_dets));
ds = ds(top, :);
bs = bs(top, :);
clf;
if model.type == model_types.Grammar
  bs = [ds(:,1:4) bs];
end
showboxes(im, reduceboxes(model, bs));
title('detections');
disp('detections');
disp('press any key to continue'); pause;
disp('continuing...');

if model.type == model_types.MixStar
  % get bounding boxes
  bbox = bboxpred_get(model.bboxpred, ds, reduceboxes(model, bs));
  bbox = clipboxes(im, bbox);
  top = nms(bbox, 0.5);
  clf;
  showboxes(im, bbox(top,:));
  title('predicted bounding boxes');
  disp('bounding boxes');
  disp('press any key to continue'); pause;
end

fprintf('\n');


function computeAllModelChoiceTime_HN(pathSet,pathModels,training,param,maxOrder,nBoot,seed)
% -------------------------------------------------------------------------
% function computeAllModelChoice_HN(pathSet,pathModels,training,param,maxOrder,nBoot,imbalance,batchNum)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function computes feature set selection for a given feature set type
% and for all experiments with different degrees of freedom. See ref. [1,2]
% for more details.
% -------------------------------------------------------------------------
% REFERENCES:
% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the
%     early prediction of different tumour outcomes in head and neck cancer.
%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy.
%     doi:
% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and
%     MRI texture features for the prediction of lung metastases in soft-tissue
%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14),
%     5471-5496. doi:10.1088/0031-9155/60/14/5471
% -------------------------------------------------------------------------
% INPUTS:
% 1. pathSet: Full path to the Feature Set folder of the corresponding experiment.
%             --> Ex: '/myProject/WORKSPACE/COHORT-BASED-RESULTS/Experiment1/FSET'
% 2. pathModels: Full path to the Models folder of the corresponding experiment.
%                --> Ex: '/myProject/WORKSPACE/COHORT-BASED-RESULTS/Experiment1/MODELS'
% 3. training: Structure defining all parameters for the given experiment
%              to perform. See masterScript_HN.m for more details.
% 4. param: Cell of two strings, defining 1) The feature set type/name; and
%           2) the outcome to model
% 5. maxOrder: Integer specifying the maximal model order to construct.
%              --> Ex: 10
% 6. nBoot: Number of bootstrap samples to use.
%           --> Ex: 100
% 7. imbalance: String specifying the type of imbalance-adjustement strategy
%               employed. Either 'IABR' for imbalance-adjusted bootstrap
%               resampling (see ref.[1]), or 'IALR' for imbalance-adjusted
%               logistic regression (see ref.[2]).
%               --> Ex: 'IALR'
% 8. batchNum: (optional input). If present, integer that specifies the
%              batch number for parallelization purposes.
%              --> Ex: 6
% -------------------------------------------------------------------------
% OUTPUTS: Mutivariable models are saved in a folder named 'MODELS' in the
% corresponding folder of "pathExperiment"
% -------------------------------------------------------------------------
% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: March 2016
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015  Martin Vallieres
%
%    This package is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This package is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this package.  If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------

startpath = pwd;
warning off

cd(pathSet)
fSetName = param{1};
outcomeName = param{2};
outcome = training.(outcomeName).timeToEvent;
censoring = 1 - training.(outcomeName).outcome;
fSet = load(['FSET_',fSetName,'_',outcomeName]); fSet = struct2cell(fSet); fSet = fSet{1};

tic
fprintf(['\n--> SELECTING FEATURES (MODEL ORDERS OF 1 to % u) FOR "',fSetName,'" FEATURE SET AND "',outcomeName,'" OUTCOME ... '],maxOrder)
[models] = featureSelectionTime_HN(fSet.Data,outcome,maxOrder,nBoot,fSet.Info,censoring,seed);
cd(pathModels), save(['MODELS_',fSetName,'_',outcomeName],'models')
fprintf('DONE!\n'), toc

cd(startpath)
end


function [robfitstatus] = canlab_glm_group_levels_run1input(wd, c)
% child process of canlab_glm_group_levels
% (see canlab_glm_README.txt for an overview)
%
% ..
%    Copyright (C) 2013  Luka Ruzic
% ..

load(fullfile(wd,sprintf('env_%04d',c)));
%% PREP

% diaryname = fullfile(wd,sprintf('diary_%04d.log',c));
cd(grpmodeldir)

robfitstatus = 0; %#ok
% grfstatus = 0;

%% robfit
cmd = 'robfit(EXPT, includedcons(c), 0, EXPT.mask)';
% diary(diaryname), fprintf('> %s\n',cmd); diary off
fprintf('> %s\n',cmd);
try
    eval(cmd)
    robfitstatus = 1;
catch exc
    if OPTS.nocatch, cd(STARTINGDIR); rethrow(exc);
    else fprintf('> %s\n',getReport(exc,'extended')); end
    %     else diary(diaryname), fprintf(getReport(exc,'extended')), diary off; end
    robfitstatus = -1;
end

%% grf  % having problems with this running in parallel (display problems?)
% if OPTS.run_grf
%     robdir = filenames(fullfile(grpmodeldir,sprintf('robust%04d',includedcons(c))),'char','absolute');
%     if ~isempty(robdir)
%         announce_string('SIGNIFICANT CLUSTER SIZE ESTIMATION using GRF')
%         try
%             load(fullfile(robdir,'SETUP.mat'));
%
%             cmd = 'sigclext = estimate_cluster_extent(.05, pthresh, SETUP.files);';
%             fprintf('> %s\n',cmd)
%             eval(cmd);
%             close all
%
%             fout = fullfile(robdir,'significant_cluster_extents_grf.txt');
%             dlmwrite(fout,[pthresh' sigclext(:,1)],'precision','%g','delimiter',' '); %#ok
%
%         grfstatus = 1;
%         catch exc
%             if OPTS.nocatch, cd(STARTINGDIR); rethrow(exc)
%             else fprintf('> %s\n',getReport(exc,'extended')); end
%             grfstatus = -1;
%         end
%     end
% end

end

function announce_string(string)

s = sprintf('--  %s  --',string);
l = regexprep(s,'.','-');
fprintf('> \n> \n> \n> %s\n> %s\n> %s\n> \n',l,s,l);

end


function inspect_qsubcellfun5

% WALLTIME 00:10:00
% MEM 1gb
% DEPENDENCY

% this test script pertains to
% http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1255

%%

y = qsubcellfun(@inspect_qsubcellfun5_fn, {1, 2, 3}, 'memreq', 0, 'timreq', 500)
y = qsubcellfun(@inspect_qsubcellfun5_fn, {1, 2, 3}, 'memreq', 0, 'timreq', 500, 'stack', 3)

%%

fc = qsubcompile(@inspect_qsubcellfun5_fn)
y = qsubcellfun(fc, {1, 2, 3}, 'memreq', 0, 'timreq', 500)

%%

y = qsubcellfun(@inspect_qsubcellfun5_fn, {1, 2, 3}, 'memreq', 0, 'timreq', 500, 'compile', true, 'stack', 1)


function outputinchar = converttochar(inputinsym)

% This file is part of SOSTOOLS - Sum of Squares Toolbox ver 3.00.
%
% Copyright (C)2002, 2004, 2013  A. Papachristodoulou (1), J. Anderson (1),
%                                G. Valmorbida (1), S. Prajna (2),
%                                P. Seiler (3), P. A. Parrilo (4)
% (1) Department of Engineering Science, University of Oxford, Oxford, U.K.
% (2) Control and Dynamical Systems - California Institute of Technology,
%     Pasadena, CA 91125, USA.
% (3) Aerospace and Engineering Mechanics Department, University of
%     Minnesota, Minneapolis, MN 55455-0153, USA.
% (4) Laboratory for Information and Decision Systems, M.I.T.,
%     Massachusetts, MA 02139-4307
%
% Send bug reports and feedback to: sostools@cds.caltech.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.

char1 = char(inputinsym);
verstring = char(version);
if verstring(1) =='7' || verstring(1) == '8'
    char2 = strrep(char1,'matrix([','');
else
    char2 = strrep(char1,'array([','');
end;
outputinchar = strrep(char2,'])','');
if outputinchar(1)~='['
    outputinchar = ['[',outputinchar,']'];
end;


if and(ssub==1, tsub==1)
    neuron = neuron_full;
    Y = double(data.Y(:, :, sframe+(1:num2read)-1));
    [d1s,d2s, T] = size(Y);
    fprintf('\nThe data has been loaded into RAM. It has %d X %d pixels X %d frames. \nLoading all data requires %.2f GB RAM\n\n', d1s, d2s, T, d1s*d2s*T*8/(2^30));
else
    if exist(nam_mat, 'file')
        [Y, neuron_ds] = neuron_full.load_data(nam_mat, sframe, num2read);
        [d1s,d2s, T] = size(Y);
        fprintf('\nThe data has been downsampled and loaded into RAM. It has %d X %d pixels X %d frames. \nLoading all data requires %.2f GB RAM\n\n', d1s, d2s, T, d1s*d2s*T*8/(2^30));
        neuron = neuron_ds.copy();
    else
        [Y, neuron_ds] = neuron_full.load_data(nam, sframe, num2read);
        [d1s,d2s, T] = size(Y);
        fprintf('\nThe data has been downsampled and loaded into RAM. It has %d X %d pixels X %d frames. \nLoading all data requires %.2f GB RAM\n\n', d1s, d2s, T, d1s*d2s*T*8/(2^30));
        neuron = neuron_ds.copy();
    end
end


function c = minus(a,b)
	checkinputs(a,b);
	c = uint64minus(uint64(a),uint64(b));
end


function y = spdiag(x)
y = sparse(1:numel(x),1:numel(x),x);
end


classdef UniformGraph < AbstractGraph
%UNIFORMGRAPH is a class which generates graphs with seeds and unaries
% which are not dependent on image information (for instance unaries are
% only based on superpixel size). This class is derived from AbstractGraph.
% To undestand how unaries are generated, its worth seeing how
% AbstractGraph.prepare_graphs() calls create_unaries() in this class to
% compute unary values.
%
% @authors:     Ahmad Humayun
% @contact:     ahumayun@cc.gatech.edu
% @affiliation: Georgia Institute of Technology
% @date:        Fall 2013 - Summer 2014

    properties
    end

    methods
        function obj = UniformGraph(seg_obj, segm_index)
            obj.init(seg_obj, segm_index);
        end

        function create_unaries(obj, graph_sub_method, seed_sets)
            switch graph_sub_method
                case 'internal'
                    obj.generate_uniform_unaries('internal', seed_sets);
                case 'external'
                    obj.generate_uniform_unaries('external', seed_sets);
                case 'subframe'
                    error('UniformGraph:compute_graph', ...
                          '''subframe'' not implemented yet');
                otherwise
                    error('UniformGraph:compute_graph', ...
                          '''%s'' is an invalid graph method', ...
                          graph_sub_method);
            end
        end

        function generate_uniform_unaries(obj, internal_external, ...
                                          seed_sets)
            inside_frame = ~obj.seg_obj.sp_frame_set;

            funcs = create_unary_aux_funcs(obj, internal_external);

            % find the offset according to the number of unary graphs
            % already added to graph_unaries_all
            ofst = size(obj.graph_unaries_all.nonlambda_s,2);

            % initialize the matrices for holding all the unaries (see the
            % comment for this structure in AbstractGraph.prepare_graphs())
            obj.graph_unaries_all.nonlambda_s = ...
                [obj.graph_unaries_all.nonlambda_s, zeros(size(seed_sets))];
            obj.graph_unaries_all.nonlambda_t = ...
                [obj.graph_unaries_all.nonlambda_t, zeros(size(seed_sets))];
            obj.graph_unaries_all.lambda_s = ...
                [obj.graph_unaries_all.lambda_s, zeros(size(seed_sets))];
            obj.graph_unaries_all.lambda_t = ...
                [obj.graph_unaries_all.lambda_t, zeros(size(seed_sets))];

            % iterate over all seed locations
            for i = 1:size(seed_sets, 2)
                if strcmp(internal_external, 'internal')
                    [nonlambda_s, lambda_t] = internal_uniform(obj, ...
                                                     seed_sets(:,i), ...
                                                     funcs.parametric_func);

                    obj.graph_unaries_all.nonlambda_s(:,ofst+i) = ...
                                                               nonlambda_s;
                    obj.graph_unaries_all.lambda_t(:,ofst+i) = lambda_t;
                else
                    [nonlambda_s, nonlambda_t, lambda_s, lambda_t] = ...
                        external_uniform(obj, seed_sets(:,i), ...
                                         inside_frame, ...
                                         funcs.parametric_func, ...
                                         funcs.frame_cost_func);

                    obj.graph_unaries_all.nonlambda_s(:,ofst+i) = ...
                                                               nonlambda_s;
                    obj.graph_unaries_all.nonlambda_t(:,ofst+i) = ...
                                                               nonlambda_t;
                    obj.graph_unaries_all.lambda_s(:,ofst+i) = lambda_s;
                    obj.graph_unaries_all.lambda_t(:,ofst+i) = lambda_t;
                end
            end
        end

        function [nonlambda_s, lambda_t] = internal_uniform(obj, ...
                                         the_rectangle, parametric_func)
            % see the comment for these output matrices in
            % AbstractGraph.prepare_graphs()
            nonlambda_s = zeros(length(the_rectangle),1);
            lambda_t = zeros(length(the_rectangle),1);

            bground_pixels = ~the_rectangle;
            nonlambda_s(the_rectangle) = inf;
            lambda_t(bground_pixels) = parametric_func(bground_pixels);
        end

        function [nonlambda_s, nonlambda_t, lambda_s, lambda_t] = ...
                external_uniform(obj, the_rectangle, inside_frame, ...
                                 parametric_func, frame_cost_func)
            % see the comment for these output matrices in
            % AbstractGraph.prepare_graphs()
            nonlambda_s = zeros(length(the_rectangle),1);
            nonlambda_t = zeros(length(the_rectangle),1);
            lambda_s = zeros(length(the_rectangle),1);
            lambda_t = zeros(length(the_rectangle),1);

            inside_frame_but_rect = inside_frame & ~the_rectangle;
            lambda_weights = parametric_func(inside_frame_but_rect);
            bground_pixels = ~(inside_frame | obj.seg_obj.sp_frame_set);

            nonlambda_s(the_rectangle) = inf;
            nonlambda_t(bground_pixels) = inf;
            lambda_s(inside_frame_but_rect) = lambda_weights;

            frame_cost = frame_cost_func(the_rectangle);

            nonlambda_t(obj.seg_obj.sp_frame_set) = ...
                frame_cost * obj.graph_seed_frame_weight;
            %hyp_conns{1,5} = {inside_frame_but_rect, obj.Background, 0, 1};
            lambda_t(inside_frame_but_rect) = lambda_weights;
        end
    end
end


function batchTestAllReconstructionFunctions(modelFolder,testResultsFolder,inputDataFolder,reconVersion, numWorkers)
% Part of the DEMETER pipeline. This function performs all quality
% control/quality assurance tests on a batch of reconstructions and saves
% the results for each reconstruction in the input folder.
%
% USAGE:
%
%   batchTestAllReconstructionFunctions(modelFolder,testResultsFolder,inputDataFolder,reconVersion, numWorkers)
%
% INPUTS
% modelFolder           Folder with COBRA models (draft or refined
%                       reconstructions) to analyze
% testResultsFolder     Folder where the test results should be saved
% inputDataFolder       Folder with experimental data and database files
%                       to load
% reconVersion          Name of the refined reconstruction resource
% numWorkers            Number of workers in parallel pool
%
% .. Author:
%   - Almut Heinken, 09/2020

% set a solver if not done yet
global CBT_LP_SOLVER
solver = CBT_LP_SOLVER;
if isempty(solver)
    initCobraToolbox(false); %Don't update the toolbox automatically
end

% initialize parallel pool
if numWorkers>0 && ~isempty(ver('parallel'))
    % with parallelization
    poolobj = gcp('nocreate');
    if isempty(poolobj)
        parpool(numWorkers)
    end
end
environment = getEnvironment();

% Runs through all tests
dInfo = dir(modelFolder);
modelList={dInfo.name};
modelList=modelList';
modelList(~contains(modelList(:,1),'.mat'),:)=[];

fields = {
    'Mass_imbalanced'
    'Charge_imbalanced'
    'Mets_without_formulas'
    'Leaking_metabolites'
    'ATP_from_O2'
    'Blocked_reactions'
    'RefinedReactionsCarryingFlux'
    'BlockedRefinedReactions'
    'Incorrect_Gene_Rules'
    'Incorrect_Compartments'
    'Carbon_sources_TruePositives'
    'Carbon_sources_FalseNegatives'
    'Fermentation_products_TruePositives'
    'Fermentation_products_FalseNegatives'
    'growsOnDefinedMedium'
    'growthOnKnownCarbonSources'
    'Biomass_precursor_biosynthesis_TruePositives'
    'Biomass_precursor_biosynthesis_FalseNegatives'
    'Metabolite_uptake_TruePositives'
    'Metabolite_uptake_FalseNegatives'
    'Secretion_products_TruePositives'
    'Secretion_products_FalseNegatives'
    'Bile_acid_biosynthesis_TruePositives'
    'Bile_acid_biosynthesis_FalseNegatives'
    'Drug_metabolism_TruePositives'
    'Drug_metabolism_FalseNegatives'
    'PutrefactionPathways_TruePositives'
    'PutrefactionPathways_FalseNegatives'
    };

%% load the results from existing test suite run and restart from there
Results=struct;

alreadyAnalyzedStrains={};

for i=1:length(fields)
    if isfile([testResultsFolder filesep fields{i} '_' reconVersion '.txt'])
        savedResults = readInputTableForPipeline([testResultsFolder filesep fields{i} '_' reconVersion '.txt']);
        Results.(fields{i}) = savedResults;
        if size(savedResults,2)>0
            alreadyAnalyzedStrains = Results.(fields{i})(:,1);
        end
    else
        Results.(fields{i})={};
    end
end

% propagate strains to empty fields
for i=1:length(fields)
    if isempty(Results.(fields{i}))
        Results.(fields{i})=alreadyAnalyzedStrains;
    end
end

% remove already analyzed reconstructions
if size(Results.(fields{1}),1)>0
    [C,IA]=intersect(strrep(modelList(:,1),'.mat',''),Results.(fields{1})(:,1));
    modelList(IA,:)=[];
end

% define the intervals in which the testing and regular saving will be
% performed
if length(modelList)>5000
    steps=1000;
elseif length(modelList)>1000
    steps=500;
elseif length(modelList)>200
    steps=200;
else
    steps=25;
end

%% Start the test suite
for i =1:steps:length(modelList)
    tmpData={};
    if length(modelList)>steps-1 && (length(modelList)-1)>=steps-1
        endPnt=steps-1;
    else
        endPnt=length(modelList)-i;
    end

    modelsToLoad={};
    for j=i:i+endPnt
        modelsToLoad{j}={};
        if j <= length(modelList)
            modelsToLoad{j}=[modelFolder filesep modelList{j}];
        end
    end
    parfor j=i:i+endPnt
%for j=i:i+endPnt
        if j <= length(modelList)
            restoreEnvironment(environment);
            changeCobraSolver(solver, 'LP');
            % prevent creation of log files
            changeCobraSolverParams('LP', 'logFile', 0);

            try
                model=readCbModel(modelsToLoad{j},'modelName','model');
            catch
                modelsToLoad{j}
                model=load(modelsToLoad{j});
                fieldnames(model)
                model=model.model;
            end

            microbeID=strrep(modelList{j},'.mat','');
            testResults = runTestsOnModel(model, microbeID, inputDataFolder);
            tmpData{j}=testResults;
        end
    end
    for k=1:length(fields)
        for j=i:i+endPnt
            if j <= length(modelList)
                res=tmpData{j};

                if strcmp(fields{k},'Blocked_reactions') && length(modelList) + length(alreadyAnalyzedStrains) > 10000
                    % do not save for very large-scale resources-file would be
                    % enormous
                    Results.(fields{k}){size(Results.(fields{k}),1)+1,1} = res.(fields{k}){1,1};
                    Results.(fields{k}){size(Results.(fields{k}),1),2} = size(res.(fields{k}),2)-1;
                else
                    Results.(fields{k})(size(Results.(fields{k}),1)+1,1:size(res.(fields{k}),2)) = res.(fields{k})(1,1:end);
                end
            end
        end
    end

    %% print the results regularly to avoid having to repeat simulations
    % only if there were any findings that need to be reported
    for j=1:length(fields)
        if size(Results.(fields{j}),2)>1 || any(contains(fields{j},{'TruePositives','FalseNegatives','growsOnDefinedMedium'}))
            table2print=cell2table(Results.(fields{j}));
            writetable(table2print,[testResultsFolder filesep fields{j} '_' reconVersion],'FileType','text','WriteVariableNames',false,'Delimiter','tab');
        end
    end
end

end


function yaw=yaw_angle(sat,type,opt,beta,mu) %#ok

yaw=yaw_nominal(beta,mu);

return


function [candidates, score] = run_bing(im, num_candidates)
  bing_path = '/path/to/bing.sh';
  model_prefix = '/path/to/BING-Objectness/VOC2007/Results/ObjNessB2W8MAXBGR';

  [ret_code, tmp_dir] = system('mktemp -d');
  assert(ret_code == 0);
  tmp_dir = strtrim(tmp_dir);
  fprintf('created %s\n', tmp_dir);

  img_filename = fullfile(tmp_dir, 'foo.png');
  imwrite(im, img_filename);

  candidates_file = fullfile(tmp_dir, 'candidates.txt');

  cmd = sprintf('%s -i %s -o %s -m %s -d %d', ...
    bing_path, img_filename, candidates_file, model_prefix, num_candidates);
  [ret_code] = system(cmd);
  assert(ret_code == 0);

  [score, x1, y1, x2, y2] = textread(candidates_file, '%f %d %d %d %d', 'headerlines', 1);
  candidates = [x1 y1 x2 y2];

  system(sprintf('rm -rf "%s"', tmp_dir));
end


function  p = adjustMaxTime(p,maxtime,elapsed)

% Allow the solver at-least 1 second
remaining = maxtime-elapsed;
budgetForSolver = max(1,ceil(remaining));

% TODO: Support more solvers
p.options.cplex.timelimit = budgetForSolver;
p.options.mosek.MSK_DPAR_MIO_MAX_TIME = budgetForSolver;
p.options.gurobi.TimeLimit = budgetForSolver;


function varargout=rotmc2qc(varargin)
%
% For calling details please see v_rotmc2qc.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_rotmc2qc.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: rotmc2qc.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_rotmc2qc(varargin{:});
else
    v_rotmc2qc(varargin{:});
end


function [which] = mne_find_channel(info,name)
%
% [which] = mne_find_channel(info,name)
%
% Find a channel by name employing the info structure
% output by mne_raw2mat or mne_epochs2mat
%
% epoch - The data structure containing the channel information
% name  - name of the channel to look for
%
% Returns index of the channel in the data
% If the channel is not found, returns -1
%

%
%
%   Author : Matti Hamalainen, MGH Martinos Center
%   License : BSD 3-clause
%
%
%     $Id: mne_find_channel.m 8776 2013-11-14 09:04:48Z roboos $
%
%     Revision 1.4  2006/04/23 15:29:40  msh
%     Added MGH to the copyright
%
%     Revision 1.3  2006/04/14 15:49:49  msh
%     Improved the channel selection code and added ch_names to measurement info.
%
%     Revision 1.2  2006/04/10 23:26:54  msh
%     Added fiff reading routines
%
%     Revision 1.1  2006/02/20 15:45:05  msh
%     Added mne_find_channel.m and mne_read_epoch.m
%
%
me='MNE:mne_find_channel';
if(nargin ~= 2)
   error(me,'Usage : [which] = mne_find_channel(info,which)');
end

which = strmatch(name,info.ch_names,'exact');

return;


% Get matlab type corresponding to each nrrd type
% Date: November 2017
% Author: Gaetan Rensonnet
function matlabdatatype = nrrd_getMatlabDataType(metaType)

% Determine the datatype
switch (metaType)
    case {'signed char', 'int8', 'int8_t'}
        matlabdatatype = 'int8';

    case {'uchar', 'unsigned char', 'uint8', 'uint8_t'}
        matlabdatatype = 'uint8';

    case {'short', 'short int', 'signed short', 'signed short int', ...
            'int16', 'int16_t'}
        matlabdatatype = 'int16';

    case {'ushort', 'unsigned short', 'unsigned short int', 'uint16', ...
            'uint16_t'}
        matlabdatatype = 'uint16';

    case {'int', 'signed int', 'int32', 'int32_t'}
        matlabdatatype = 'int32';

    case {'uint', 'unsigned int', 'uint32', 'uint32_t'}
        matlabdatatype = 'uint32';

    case {'longlong', 'long long', 'long long int', 'signed long long', ...
            'signed long long int', 'int64', 'int64_t'}
        matlabdatatype = 'int64';

    case {'ulonglong', 'unsigned long long', 'unsigned long long int', ...
            'uint64', 'uint64_t'}
        matlabdatatype = 'uint64';

    case {'float'}
        matlabdatatype = 'single';

    case {'double'}
        matlabdatatype = 'double';

    case {'block'}
        error('Data type ''block'' is currently not supported.\n');

    otherwise
        assert(false, 'Unknown datatype')
end
end


% This small example illustrates how to use the remote API
% synchronous mode. The synchronous mode needs to be
% pre-enabled on the server side. You would do this by
% starting the server (e.g. in a child script) with:
%
% simRemoteApi.start(19999,1300,false,true)
%
% But in this example we try to connect on port
% 19997 where there should be a continuous remote API
% server service already running and pre-enabled for
% synchronous mode.
%
% IMPORTANT: for each successful call to simxStart, there
% should be a corresponding call to simxFinish at the end!

function kuka_kart_robot()
    % init basic data. Robots and number of collision objects.
    coppelia = [];
    n_joints = 10;
    coppelia.n_collision_objects = 0;
    coppelia.robots{1}.n_joints = n_joints;

    coppelia = coppelia_init(coppelia);

    q = 0.1*ones(n_joints, 1);
    dq = 0.1*q;
    % Draw robot 1: R1, which possesses joints R1_q1, R1_q2...
    for i=1:40
       q = q + dq;
       drawrobotcoppelia(coppelia, 1, q)
       pause(0.01)
    end

    coppelia_end(coppelia);
end


function res = bf_write_spmeeg(BF, S)
% Writes out beamformer results as M/EEG dataset
% Copyright (C) 2013 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: bf_write_spmeeg.m 7703 2019-11-22 12:06:29Z guillaume $

%--------------------------------------------------------------------------
if nargin == 0
    mode         = cfg_menu;
    mode.tag     = 'mode';
    mode.name    = 'Writing mode';
    mode.help    = {'How to generate the output'};
    mode.labels  = {
        'Write new'
        'Online montage original data'
        'Copy + online montage'
        }';
    mode.values  = {
        'write'
        'online'
        'onlinecopy'
        }';
    mode.val = {'write'};

    modality         = cfg_menu;
    modality.tag     = 'modality';
    modality.name    = 'Modality';
    modality.help    = {'What modality to output'};
    modality.labels  = {
        'MEG'
        'MEGPLANAR'
        'EEG'
        }';
    modality.values  = {
        'MEG'
        'MEGPLANAR'
        'EEG'
        }';
    modality.val = {'MEG'};

    none = cfg_const;
    none.tag = 'none';
    none.name = 'None';
    none.val  = {0};

    addchannels      = cfg_choice;
    addchannels.tag  = 'addchannels';
    addchannels.name = 'Extra channels to add';
    addchannels.values  = {none, spm_cfg_eeg_channel_selector};
    addchannels.val  = {none};

    prefix         = cfg_entry;
    prefix.tag     = 'prefix';
    prefix.name    = 'Filename Prefix';
    prefix.help    = {'Specify the string to be prepended to the output (if relevant).'};
    prefix.strtype = 's';
    prefix.num     = [1 Inf];
    prefix.val     = {'B'};

    spmeeg      = cfg_branch;
    spmeeg.tag  = 'spmeeg';
    spmeeg.name = 'SPM M/EEG dataset';
    spmeeg.val  = {mode, modality, addchannels, prefix};

    res = spmeeg;

    return
elseif nargin < 2
    error('Two input arguments are required');
end

D = BF.data.D;

if isfield(S.addchannels, 'channels')
    addchannels = D.chanlabels(D.selectchannels(spm_cfg_eeg_channel_selector(S.addchannels.channels)));
else
    addchannels = {};
end

usemontage = 0;

if isfield(BF.output, 'montage')

    usemontage = 1;

    montage = BF.output.montage.(S.modality);

    [sel1, sel2] = spm_match_str(montage.labelorg, addchannels);
    for i = 1:length(sel1)
        montage.labelnew(end+1) = addchannels(sel2(i));
        montage.tra(end+1, sel1(i)) = 1;

        montage.chantypenew(end+1) = chantype(D, D.indchannel(addchannels(sel2(i))))';
        montage.chanunitnew(end+1) = units(D, D.indchannel(addchannels(sel2(i))))';

    end
    addchannels(sel2) = [];

    if ~isempty(addchannels)
        montage.labelorg = [montage.labelorg(:); addchannels(:)];
        montage.labelnew = [montage.labelnew(:); addchannels(:)];

        montage.chantypenew = [montage.chantypenew(:); chantype(D, D.indchannel(addchannels))'];
        montage.chanunitnew = [montage.chanunitnew(:); units(D, D.indchannel(addchannels))'];

        na = numel(addchannels);
        montage.tra((end+1):(end+na), (end+1):(end+na)) = eye(na);
    end

    montage.chantypeold = chantype(D, D.indchannel(montage.labelorg))';
    montage.chanunitold = units(D, D.indchannel(montage.labelorg))';
elseif isfield(BF.output, 'sourcedata')
    ftdata = BF.output.sourcedata.(S.modality).ftdata;

    if ~isempty(addchannels)
        addind = D.indchannel(addchannels);
        ftdata.label = [ftdata.label;D.chanlabels(addind)'];
        if numel(ftdata.trial) == length(BF.features.trials)
            for i = 1:numel(ftdata.trial)
                ftdata.trial{i} = [ftdata.trial{i};D(addind, D.indsample(ftdata.time{i}(1)):D.indsample(ftdata.time{i}(end)), BF.features.trials(i))];
            end
        else
            error('Cannot match trials for adding extra channels.')
        end
    end

    Ds = spm_eeg_ft2spm(ftdata, [S.prefix D.fname]);
    Ds = trialonset(Ds, ':', D.trialonset);

    if isfield(BF.output.sourcedata.(S.modality), 'events')
        for i = 1:Ds.ntrials
            evold = events(D, BF.features.trials(i));
            if iscell(evold)
                evold = evold{1};
            end

            evnew = BF.output.sourcedata.(S.modality).events;
            if iscell(evnew)
                evnew = evnew{i};
            end

            ev = spm_cat_struct(evold, evnew);

            Ds = events(Ds, i, ev);
        end
    else
        if ~isempty(D.events)
            Ds = events(Ds, ':', D.events);
        end
    end

    if isfield(BF.sources, 'voi')
        Ds = chantype(Ds, ':', 'LFP');
    else
        Ds = chantype(Ds, ':', 'SRC');
    end

    if ~isempty(addchannels)
         Ds = chantype(Ds, (Ds.nchannels-length(addind)+1):Ds.nchannels, D.chantype(addind));
    end

    save(Ds);

    D = Ds;
else
    error('Unsupported option');
end

if usemontage
    if D.montage('getindex')
        vmontage = rmfield(D.montage('getmontage'), 'channels');
        montage  =  ft_apply_montage(vmontage, montage);
    end

    S1 = [];
    S1.montage = montage;
    S1.prefix  = S.prefix; % ignored for online
    S1.keepsensors = false;
    S1.keepothers  = false;

    switch S.mode
        case 'write'
            S1.mode    = 'write';
        case 'online'
            S1.mode = 'switch';
        case 'onlinecopy'
            S1.mode    = 'switch';
            D = copy(D, [S.prefix D.fname]);
    end

    S1.D = D;
    D = spm_eeg_montage(S1);
end

res.files = {fullfile(D)};


function epo= proc_selectEpochs(epo, idx, varargin)
%PROC_SELECTEPOCHS - Select specified epochs within epoch structure
%
%Synopsis:
%  EPO= proc_selectEpochs(EPO, IDX, <OPT>)
%  EPO= proc_selectEpochs(EPO, 'not', IDX, <OPT>)
%
%Arguments:
%  EPO: STRUCT - Epoch structure
% selects the epochs with specified indices. void classes are removed.
%
% the structure 'epo' may contain a field 'indexedByEpochs' being a
% cell array of field names of epo. in this case subarrays of those
% fields are selected. here it is assumed that the last dimension
% is indexed by epochs.
%
% IN  epo  - structure of epoched data
%     idx  - indices of epochs that are to be selected [or are to be
%            excluded if the 'not' form is used].
%            if this argument is omitted, all non-rejected epochs are
%            selected, i.e., epochs with any(epo.y).
%
% OUT epo  - updated data structure

% Benjamin Blankertz
props= {'RemoveVoidClasses',   1,   'BOOL'};

if nargin==0,
  epo= props; return
end

misc_checkType(epo, 'STRUCT(x clab)');
epo= misc_history(epo);

if isequal(idx, 'not'),
  idx= setdiff(1:size(epo.y,2), varargin{1},'legacy');
  varargin= varargin(2:end);
end

opt= opt_proplistToStruct(varargin{:});
opt= opt_setDefaults(opt, props);

if ~exist('idx','var'),
  %% select accepted epochs
  idx= find(any(epo.y==1,1));
end

subidx= cat(2, repmat({':'}, 1, ndims(epo.x)-1), {idx});
epo.x= epo.x(subidx{:});

if isfield(epo, 'y'),
  epo.y= epo.y(:,idx);

  nonvoidClasses= find(any(epo.y==1,2));
  if length(nonvoidClasses)<size(epo.y,1) && opt.RemoveVoidClasses
    msg= sprintf('void classes removed, %d classes remaining', ...
                 length(nonvoidClasses));
    warning(msg, 'selection', mfilename);
    epo.y= epo.y(nonvoidClasses,:);
    if isfield(epo, 'className'),
      epo.className= {epo.className{nonvoidClasses}};
    end
  end
end

if isfield(epo, 'event'),
  for Fld= fieldnames(epo.event)',
    fld= Fld{1};
    tmp= getfield(epo.event, fld);
    % the first dimension must be indexed by epochs
    subidx= repmat({':'}, 1, ndims(tmp));
    subidx{1}= idx;
    epo.event= setfield(epo.event, fld, tmp(subidx{:}));
  end
end


function varargout = loadxml(filename,varargin)
%LOADXML Load workspace variables from disk (XML file).
%  LOADXML FILENAME retrieves all variables from a file given a full
%  pathname or a MATLABPATH relative partial pathname (see PARTIALPATH).
%  If FILENAME has no extension LOAD looks for FILENAME and FILENAME.xml
%  and treats it as an XML file.
%
%  LOAD, by itself, uses the XML file named 'matlab.xml'. It is an error
%  if 'matlab.xml' is not found.
%
%  LOAD FILENAME X loads only X.
%  LOAD FILENAME X Y Z ... loads just the specified variables.  The
%  wildcard '*' loads variables that match a pattern.
%  Requested variables from FILENAME are created in the workspace.
%
%  S = LOAD(...) returns the contents of FILENAME in variable S. S is
%  a struct containing fields matching the variables retrieved.
%
%  Use the functional form of LOAD, such as LOAD('filename'), when the
%  file name is stored in a string, when an output argument is requested,
%  or if FILENAME contains spaces.
%
%  See also LOAD, XML2MAT, XMLTREE.

%  Copyright 2003 Guillaume Flandin.
%  $Revision: 6530 $  $Date: 2003/07/10 13:50 $

%  $Id: loadxml.m 6530 2015-08-21 14:43:52Z guillaume $

if nargin == 0
    filename = 'matlab.xml';
    fprintf('\nLoading from: %s\n\n',filename);
end

if ~ischar(filename)
    error('[LOADXML] Argument must contain a string.');
end

if ~exist(filename,'file')
    filename = [filename '.xml'];
    if ~exist(filename,'file')
        error(sprintf(...
        '[LOADXML] Unable to read file %s: file does not exist',filename));
    end
end

if nargout > 1,
    error('[LOADXML] Too many output arguments.');
end

t = xmltree(filename);

uid = children(t,root(t));

if nargout == 1
    % varargout{1} = struct([]); % Matlab 6.0 and above
end

flagfirstvar = 1;
for i=1:length(uid)
    if strcmp(get(t,uid(i),'type'),'element')
        vname = get(t,uid(i),'name');
        % TODO % No need to parse the whole tree
        if isempty(varargin) | ismember(varargin,vname)
            v = xml_create_var(t,uid(i));
            if nargout == 1
                if flagfirstvar
                    varargout{1} = struct(vname,v);
                    flagfirstvar = 0;
                else
                    varargout{1} = setfield(varargout{1},vname,v);
                end
            else
                assignin('caller',vname,v);
            end
        end
    end
end

%=======================================================================
function v = xml_create_var(t,uid)
    type = attributes(t,'get',uid,'type');
    sz   = str2num(attributes(t,'get',uid,'size'));

    switch type
        case 'double'
            v = str2num(get(t,children(t,uid),'value'));
            if ~isempty(sz)
                v = reshape(v,sz);
            end
        case 'sparse'
            u = children(t,uid);
            for k=1:length(u)
                if strcmp(get(t,u(k),'name'),'row')
                    i = str2num(get(t,children(t,u(k)),'value'));
                elseif strcmp(get(t,u(k),'name'),'col')
                    j = str2num(get(t,children(t,u(k)),'value'));
                elseif strcmp(get(t,u(k),'name'),'val')
                    s = str2num(get(t,children(t,u(k)),'value'));
                end
            end
           v = sparse(i,j,s,sz(1),sz(2));
        case 'struct'
            u = children(t,uid);
            v = []; % works with Matlab < 6.0
            for i=1:length(u)
                s(1).type = '()';
                s(1).subs = {str2num(attributes(t,'get',u(i),'index'))};
                s(2).type = '.';
                s(2).subs = get(t,u(i),'name');
                v = subsasgn(v,s,xml_create_var(t,u(i)));
            end
            if isempty(u),
                v = struct([]); % Need Matlab 6.0 and above
            end
        case 'cell'
            v = cell(sz);
            u = children(t,uid);
            for i=1:length(u)
                v{str2num(attributes(t,'get',u(i),'index'))} = ...
                    xml_create_var(t,u(i));
            end
        case 'char'
            if isempty(children(t,uid))
                v = '';
            else
                v = get(t,children(t,uid),'value');
            end
            try % this can fail if blank spaces are lost or entity escaping
                if ~isempty(sz)
                    if sz(1) > 1
                        v = reshape(v,fliplr(sz))'; % row-wise order
                    else
                        v = reshape(v,sz);
                    end
                end
            end
        case  {'int8','uint8','int16','uint16','int32','uint32'}
            % TODO % Handle integer formats
            warning(sprintf('%s matrices not handled.',type));
            v = 0;
        otherwise
            try,
                v = feval(class(v),get(t,uid,'value'));
            catch,
                warning(sprintf(...
                '[LOADXML] Cannot convert from XML to %s.',type));
            end
    end


function this = smooth(this)
% Smoothes all images in the time series
%
%   MrSeries = smooth(MrSeries)
%
% This is a method of class MrSeries.
%
% IN
%   parameters.smooth.fwhmMillimeter
%
% OUT
%
% EXAMPLE
%   smooth
%
%   See also MrSeries

% Author:   Saskia Klein & Lars Kasper
% Created:  2014-07-02
% Copyright (C) 2014 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public Licence (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

fwhm = this.parameters.smooth.fwhmMillimeters;

this.init_processing_step('smooth');
this.data = this.data.smooth('fwhm', fwhm);
this.finish_processing_step('smooth', this.data);


%--- help for setup_restrictions ---
%
%  INTERNAL FUNCTION: sets up linear, nonlinear and general restrictions
%
%  ::
%
% 	obj=setup_general_restrictions(obj)
%
%  Args:
%
%     obj (rise | dsge | rfvar | svar): RISE object
%
%  Returns:
%     :
%
%     - **obj** [rise|dsge|rfvar|svar]: RISE object
%
%  See also:
%     - rise_generic.setup_linear_restrictions,
%     - rise_generic.setup_nonlinear_restrictions,
%     - rise_generic.setup_general_restrictions
%
%