function install(varargin)
% INSTALL   Install script for Fast ICA Toolbox.
%    INSTALL creates the Fast ICA Toolbox folder and (optionally) 
%    the needed entries in the startup.m file.
% 
%    INSTALL PATH creates the Fast ICA Toolbox folder 
%    in the specified PATH.
%    
%    This installation script was generated by using 
%    the MAKEINSTALL tool. For further information
%    visit http://matlab.pucicu.de

% Copyright (c) 2001-2006 by AMRON
% Norbert Marwan, Potsdam University, Germany
% http://www.agnld.uni-potsdam.de
%
% THIS IS A GENERATED INSTALL-FILE, DO NOT EDIT!
% Generation date: 14-Jun-2007 16:28:54
% $Date: 2006/11/07 07:55:43 $
% $Revision: 3.16 $

install_file='';install_path='';installfile_info.date='';installfile_info.bytes=[];
time_stamp='';checksum='';checksum_file=''; instpaths = '';
errcode=0;

try
  warning('off')
  if nargin
    install_path = varargin{1};
  end

  if exist('install.log','file') == 2, delete('install.log'), end
  %rehash
  disp('---------------------------------')
  disp('  INSTALLATION Fast ICA Toolbox');
  disp('---------------------------------')
  install_file=[mfilename,'.m'];
  currentpath=pwd; time_stamp='time_stamp not yet obtained'; checksum='checksum not yet obtained';
  
%%%%%%% read the archive
%%%%%%% and look for checksum and date in archive
  errcode=90;
  disp('  Reading the archiv ')
  fid=fopen(install_file,'r'); 
  fseek(fid,0,'eof'); eofbyte=ftell(fid);
  fseek(fid,23335,'bof'); % location where the container starts
  while 1
     temp=fgetl(fid);
     startbyte=ftell(fid);
     if length(temp)>1
       if strcmpi(temp,'%<-- Header begins here -->')
          errcode=90.1;
          checksum=fgetl(fid);
          temp1=fgetl(fid);
          temp2=fgetl(fid);
       end
       if strcmpi(temp,'%<-- Header ends here -->')
          startbyte=ftell(fid);
          break
       end
     end
  end
  checksum(1:2)=[];
  fseek(fid,startbyte,'bof');
  errcode=90.2;
  A=fread(fid,eofbyte);
  errcode=90.3;
  checksum_file=dec2hex(sum((1:length(A))'.*A));
  if ~strcmpi(checksum_file,checksum)
    error(['The installation file is corrupt!',10,'Ensure that the archive container was ',...
           'not modified (check FTP/ ',10,'proxy/ firewall settings, anti-virus scanner for emails etc.)!'])
  else
    disp(['  Checksum test passed (', checksum,')'])
  end
  fclose(fid);

  disp(['  Fast ICA Toolbox version ', temp2(3:end),''])
  time_stamp=temp1(3:end); disp(['  Fast ICA Toolbox time stamp ', time_stamp,'']); 
  
  errcode=91;
  if isunix
    toolboxpath='FastICA';
  else
    toolboxpath='fastica';
  end
  
  
%%%%%%% check for older versions
  
  p=path; i1=0;
  rem_old = '';
  
  while any([findstr([lower(toolboxpath),'demo'],lower(p)) findstr(lower(toolboxpath),lower(p)) findstr('',lower(p))]>i1) & ~strcmpi('N',rem_old)
    errcode=92;
    i1=[findstr([lower(toolboxpath),'demo'],lower(p)) findstr(lower(toolboxpath),lower(p)) findstr('',lower(p))];
    if ~isempty(i1)
      i1=i1(1);
      if isunix, i2=findstr(':',p); else i2=findstr(';',p); end
      i3=i2(i2>i1);                 % last index pathname
      if ~isempty(i3), i3=i3(1)-1; else i3=length(p); end
      i4=i2(i2<i1);                 % first index pathname
      if ~isempty(i4), i4=i4(end)+1; else i4=1; end
      oldtoolboxpath=p(i4:i3);
      if isempty(rem_old)
          disp(['  Old Fast ICA Toolbox found in ', oldtoolboxpath,''])
          rem_old = input('> Delete old toolbox? Y/N [Y]: ','s');
      end
      if isempty(rem_old), rem_old = 'Y'; end
      if strcmpi('Y',rem_old)
%%%%%%% removing old entries in startup-file
        errcode=94;
        rmpath(oldtoolboxpath)
        if i4>1, p(i4-1:i3)=''; else p(i4:i3)=''; end
        startup_exist = exist('startup','var');
        if startup_exist
             startupfile=which('startup');
             startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
             errcode=94.1;
             if ~isunix
               toolboxroot=fullfile(matlabroot,'toolbox');
               curr_pwd = pwd; home_pwd = matlabroot; 
             else
               toolboxroot=startuppath;
               curr_pwd = pwd; cd ('~'); home_pwd = pwd; cd(curr_pwd);
             end
             instpaths=textread(startupfile,'%[^\n]');
             k=1;
             while k <= length(instpaths)
               if findstr(oldtoolboxpath,strrep(instpaths{k},'~',home_pwd))
                 errcode=94.2;
                 instpaths(k)=[];
               else
                 k=k+1;
               end
             end
             fid=fopen(startupfile,'w');
             errcode=94.3;
             if fid < 0
               disp(['  ** Warning: Could not get access to ',startupfile,'.']);
               disp('  ** Could not remove toolbox from the startup.m file.');
               disp('  ** Ensure that you have write access!');
             else
               for i2=1:length(instpaths), 
                 fprintf(fid,'%s\n', char(instpaths{i2})); 
               end
               fclose(fid);
             end
        end
%%%%%%% removing old paths
        errcode=93;
        if exist(oldtoolboxpath,'dir') == 7
           disp(['  Change to ',oldtoolboxpath,''])
           cd(oldtoolboxpath)
           dirnames='';filenames='';
           temp='.:';
           while ~isempty(temp)
             [temp1 temp]=strtok(temp,':');
             if ~isempty(temp1)
               dirnames=[dirnames; {temp1}];
               x2=dir(temp1);
               for i=1:length(x2)
                 if ~x2(i).isdir, filenames=[filenames; {[temp1,'/', x2(i).name]}]; end
         	   if x2(i).isdir & ~strcmp(x2(i).name,'.') & ~strcmp(x2(i).name,'..'), temp=[temp,temp1,filesep,x2(i).name,':']; end
               end
             end
           end
           dirnames=strrep(dirnames,['.',filesep],'');
           for i=1:length(dirnames),l(i)=length(dirnames{i}); end
           [i i4]=sort(l);
           dirnames=dirnames(fliplr(i4));
           for i=1:length(dirnames)
              delete([dirnames{i}, filesep,'*']),
              if exist('rmdir') == 5 & exist(dirnames{i}) == 7, rmdir(dirnames{i},'s'), else, delete(dirnames{i}), end
              disp(['  Removing files in ',char(dirnames{i}),''])
           end
           cd(currentpath)
           if exist('rmdir') == 5 & exist(oldtoolboxpath) == 7, rmdir(oldtoolboxpath,'s'), else, delete(oldtoolboxpath), end
           disp(['  Removing ',oldtoolboxpath,''])
        end
%%%%%%%
      end
    end
    p = path; i1 = 0;
  end
  clear p i i1 i2 i3 i4 temp* x2
  
%%%%%%% add entry into startpath in startup.m
  i=findstr(toolboxpath,path);
  startupPos = 0;
  if exist('startup','file')
        errcode=95.1;
        startupfile=which('startup');
        startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
  
        if ~isunix
           errcode=95.11;
           toolboxroot=fullfile(matlabroot,'toolbox');
        else
           errcode=95.12;
           toolboxroot=startuppath;
        end
        instpaths=textread(startupfile,'%[^\n]');
  end
  if isempty(i)
     errcode=95;
     if exist('startup','file')
        errcode=95.1;
     else
        errcode=95.2;
        if ~isunix
           errcode=95.21;
           startupfile=fullfile(matlabroot,'toolbox','local','startup.m');
  	   toolboxroot=fullfile(matlabroot,'toolbox');
  	   instpaths={''};
        else
           errcode=95.22;
           cd ~
           if exist('matlab','file') ~= 7, mkdir matlab, end
           cd matlab
   	   startuppath=[pwd,filesep];
  	   startupfile=[startuppath,'startup.m'];
  	   toolboxroot=startuppath;
  	   instpaths={''};
        end
     end
    
        errcode=95.21;
        if ~isempty(install_path)
           switch ( exist(install_path,'dir') )
              case 0
                in = input(['> Create ', install_path, '? Y/N [Y]: '],'s');
                if isempty(in), in = 'Y'; end
                if strcmpi('Y',in)
                   err = mkdir(install_path);
                   if ~err
                     disp(['  ** Could not create ', install_path, '! Using ',startuppath,' as installation path.'])
                   else                
                     toolboxroot = install_path;
                   end                
                else 
                   disp(['  ** Do not create ', install_path, '! Using ',startuppath,' as installation path.'])
                end
              case 2
                disp(['  ** ', install_path, ' is not a directory! Using ',startuppath,' as installation path.'])
              case 7
                toolboxroot = install_path;
           end
        end

     errcode=95.3;
     TBfullpath=fullfile(toolboxroot,toolboxpath);
     if ~exist(TBfullpath,'dir'), mkdir(toolboxroot,toolboxpath); end

%%%%%%% resolve relative path (starting with ./ and ../) to absolute path

     isrelpath = findstr('./',TBfullpath);
     isrelpathDos = findstr('.\',TBfullpath);
     if ( ~isempty(isrelpath) & isrelpath == 1 ) | ( ~isempty(isrelpathDos) & isrelpathDos == 1 )
         TBfullpath = fullfile(pwd, TBfullpath(3:end));
     end

     isrelpath = findstr('../',TBfullpath);
     isrelpathDos = findstr('..\',TBfullpath);
     if ( ~isempty(isrelpath) & isrelpath == 1 ) | ( ~isempty(isrelpathDos) & isrelpathDos == 1 )
         TBfullpath = fullfile(pwd, TBfullpath(4:end));
     end
     

%%%%%%% ask where to add entry in startup file

     disp(['> In order to get permanent access, the toolbox should be added',10,'> to the top (default) or end (E) of your startup path.'])
     in = input('> Add toolbox permanently into your startup path (highly recommended)? Y/E/N [Y]: ','s');
     if isempty(in), in = 'Y'; end
     if strcmpi('Y',in)
       startupPos = '-begin';
       disp('  Adding Toolbox at the end of the startup.m file')
     elseif strcmpi('E',in)
       startupPos = '-end';
       disp('  Adding Toolbox at the top of the startup.m file')
     end

     if startupPos
         errcode=95.4;
         loc = ['addpath ''',TBfullpath,''' ', startupPos];
         if ~ismember(loc, instpaths)
             instpaths{end+1,1} = loc;
         end
     end

  else
     errcode=96;
     startupfile=which('startup');
     startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
     if ~isunix
        toolboxroot=fullfile(matlabroot,'toolbox');
     else
        toolboxroot=startuppath;
     end
    
        errcode=96.21;
        if ~isempty(install_path)
           switch ( exist(install_path,'dir') )
              case 0
                disp(['> Create ', install_path, '?'])
                in = input('> Create ', install_path, '? Y/N [Y]: ','s');
                if isempty(in), in = 'Y'; end
                if strcmpi('Y',in)
                   err = mkdir(install_path);
                   if ~err
                     disp(['  ** Could not create ', install_path, '! Using ',startuppath,' as installation path.'])
                   else                
                     toolboxroot = install_path;
                   end                
                else 
                   disp(['  ** Do not create ', install_path, '! Using ',startuppath,' as installation path.'])
                end
              case 2
                disp(['  ** ', install_path, ' is not a directory! Using ',startuppath,' as installation path.'])
              case 7
                toolboxroot = install_path;
           end
        end
        TBfullpath=fullfile(toolboxroot,toolboxpath);
        if ~exist(TBfullpath,'dir'), mkdir(toolboxroot,toolboxpath); end
  end
  
  
%%%%%%% read the archive
  errcode=97;
  fprintf('  Importing the archiv ')
  cd(currentpath)
  max_sc=30;
  scale=[sprintf('%3.0f',0),'% |',repmat(' ',1,max_sc),'|'];
  fprintf('%s',scale)
  b=''; c.file=''; c.data=''; bfile=''; folder=''; i2=0;
    
    % read ASCII
    errcode=97.1;
    i1=findstr(char(A'),'%<-- ASCII begins here');
    i2=findstr(char(A'),'%<-- ASCII ends here -->');
    
    for k=1:length(i1),
      wb=round(i1(k)*max_sc/eofbyte);
      errcode=97.11;
      scale=[sprintf('%3.0f',100*wb/max_sc),'% |',repmat('*',1,wb),repmat(' ',1,max_sc-wb),'|'];
      fprintf([repmat('\b',1,max_sc+7),'%s'],scale)
      B=A(i1(k):i2(k)-2);
     
      i4=find(B == 10);
      i3=[0;i4(1:end-1)]+1;
      filename=strrep(...
                strrep(char(B(i3(1):i4(1)-1)'),'%<-- ASCII begins here: __',''),...
  	      '__ -->','');
      errcode=['97.1',reshape(dec2hex(double(filename))',1,length(filename)*2)];
      filename = strrep(filename, '/', filesep);
      i6=findstr(filename, filesep);
      if i6>0
         folder=[folder; {filename(1:i6(end)-1)}];
      end
      c(k).file={filename};
      c(k).data=strrep(char(B(i4(1)+3:end)'),[char(10),'%@'],char(10));
    end
  
    % read binary
    errcode=97.2;
    i1=findstr(char(A'),'%<-- Binary begins here');
    i2=findstr(char(A'),'%<-- Binary ends here -->');
    for k=1:length(i1),
      wb=round(i1(k)*max_sc/eofbyte);
      errcode=97.21;
      scale=[sprintf('%3.0f',100*wb/max_sc),'% |',repmat('*',1,wb),repmat(' ',1,max_sc-wb),'|'];
      fprintf([repmat('\b',1,max_sc+7),'%s'],scale)
      B=A(i1(k):i2(k));
  
      i4=find(B == 10);
      i3=[0;i4(1:end-1)]+1;
      i5=findstr(char(B(i3(1):i4(1))'),'__');
      filename=char(B(i5(1)+2:i5(2)-1)');
      errcode=['97.2',reshape(dec2hex(double(filename))',1,length(filename)*2)];
      filename = strrep(filename, '/', filesep);
      i6=findstr(filename, filesep);
      if i6>0
      folder=[folder; {filename(1:i6(end)-1)}];
      end
      bfile=[bfile; {filename}];
      nbytes=str2double(char(B(i5(3)+2:i5(4)-1)'));
      if nbytes>=2
        temp=reshape(B(i4(1)+1:i4(1)+nbytes),2,nbytes/2);
        b=[b;{temp(2,:)}];
      else
        b=[b;{''}];
      end
  
    end
    wb=max_sc;
    scale=[sprintf('%3.0f',100*wb/max_sc),'% |',repmat('*',1,wb),repmat(' ',1,max_sc-wb),'|'];
    fprintf([repmat('\b',1,max_sc+7),'%s'],scale)
  fprintf('\n')
  clear temp* i i1 i2 i3 i4 i5 i6 A B
  
  errcode='97.3';
  cd(TBfullpath)
  disp(['  Toolbox folder is ',TBfullpath,''])
  
%%%%%%% make sub-directories
  errcode='97.4';
  for i=1:length(folder);
     i1=folder{i}; i2='.'; olddir=pwd;
     if exist([TBfullpath, filesep, i1],'file') ~= 7
        while ~isempty(i2) & ~isempty(i1)
          cd(i2)
          [i2 i1]=strtok(i1,'/');
          if exist([pwd, filesep, i2],'file') ~= 7 & exist([pwd, filesep, i2],'file')
             disp(['  ** Warning: Found ', i2, ' will be overwritten.'])
             errcode=['97.5',reshape(dec2hex(double(i2))',1,length(i2)*2)];
             delete(i2)
          end
          if ~exist([pwd, filesep, i2],'file')
            disp(['  Make directory ',pwd, filesep, i2,''])
            errcode=['97.6',reshape(dec2hex(double(i2))',1,length(i2)*2)];
            mkdir(i2)
            errcode=97.7;
            if ~strcmpi(i2,'private') & i2 ~= '@'
                 if isempty(startupPos) startupPos = '-end'; end
                 loc = ['addpath ''',pwd, filesep, i2,''' ', startupPos];
                 eval(loc);
                 if ~ismember(loc, instpaths)
                     instpaths{end+1,1} = loc;
                 end
            end
          end
        end
        cd(olddir)
     end
  end
  
%%%%%%% make toolbox accessible in the current matlab session
  if ~startupPos, startupPos = '-end'; end
  addpath(TBfullpath,startupPos);


%%%%%%% write startup file
  if startupPos
    errcode=95.4;
    fid=fopen(startupfile,'w');
    if fid < 0
      disp(['  ** Warning: Could not get access to ',startupfile,'.']);
      disp('  ** Could not add toolbox into the startup.m file.');
      disp('  ** Ensure that you have write access!');
    else
      for i2=1:length(instpaths), fprintf(fid,'%s\n', char(instpaths{i2})); end
      fclose(fid);
    end
  end


%%%%%%% write the programme files
  errcode=98;
  num_errors=0;
  for i=1:length(c),
    disp(['  Creating ',char(c(i).file),''])
    fid=fopen(char(c(i).file),'w');
    if fid < 0
       disp('  ** Warning: Could not get access to ',char(c(i).file),'.');
       disp('  ** Ensure that you have write access in this filesystem!');
       num_errors=num_errors+1;
       if num_errors == 2; 
         disp('Abort!')
         disp('Too much errors due to write access failure in this filesystem.')
         cd(currentpath), return
       end
    else
      if strcmpi(c(i).file,'info.xml')
        v=version;
        release=str2double(v(findstr(v,'(R')+2:findstr(v,')')-1));
        if release>12, area='toolbox'; icon_path='$toolbox/matlab/icons'; else area='matlab'; icon_path='$toolbox/matlab/general'; end
        i3=findstr(c(i).data,'<matlabrelease>'); i4=findstr(c(i).data,'</matlabrelease>');
        if ~isempty(i3) & i4>i3;
          c(i).data=strrep(c(i).data,c(i).data(i3:i4-1),['<matlabrelease>',num2str(release)]);
        end
        i3=findstr(c(i).data,'<area>'); i4=findstr(c(i).data,'</area>');
        if ~isempty(i3) & i4>i3;
          c(i).data=strrep(c(i).data,c(i).data(i3:i4-1),['<area>',area]);
        end
        c(i).data=strrep(c(i).data,'<icon>$toolbox/matlab/general',['<icon>',icon_path]);
        c(i).data=strrep(c(i).data,'<icon>$toolbox/matlab/icons',['<icon>',icon_path]);
      end
      fprintf(fid,'%s',char(c(i).data));
      fclose(fid);
    end
  end

%%%%%%% pcode the programme files
  for i=1:length(c),
    try
      [tPath tFile tExt]=fileparts(char(c(i).file));
      if strcmpi(tExt,'.m') & ~strcmpi(tFile,'Readme') & ~strcmpi(tFile,'Contents')
        if mislocked(char(c(i).file)), munlock(char(c(i).file)); clear(char(c(i).file)); end
        disp(['  Pcode ',char(c(i).file),''])
        if sum(c(i).file == '.') < 2
           pcode(char(c(i).file),'-inplace')
        end  
      end  
    catch
    end
  end

%%%%%%% write the binary files
  num_errors=0;
  for i=1:length(b),
    disp(['  Creating ',char(bfile(i)),''])
    fid=fopen(char(bfile(i)),'w');
    if fid < 0
       disp(['  ** Warning: Could not get access to ',char(bfile(i)),'.']);
       disp('  ** Ensure that you have write access in this filesystem!');
       num_errors=num_errors+1;
       if num_errors == 2; 
         disp('Abort!')
         disp('Too much errors due to write access failure in this filesystem.')
         cd(currentpath), return
       end
    else
      fwrite(fid,b{i}); 
      fclose(fid);
    end
  end
  tx=version; tx=strtok(tx,'.'); 
  if str2double(tx)>=5 & exist('rehash','builtin'), rehash, end
  if str2double(tx)>=6 & exist('rehash','builtin'), eval('rehash toolboxcache'), end
  
%%%%%%% removing installation file
  errcode=99;
  cd(currentpath)
  i = input('> Delete installation file? Y/N [Y]: ','s');
  if isempty(i), i = 'Y'; end
  
  if strcmpi('Y',i)
    disp('  Removing installation file')
    delete(install_file)
  end
  
  disp('  Installation finished!')
  
  if ~exist('rehash','builtin')
    disp('  ** Warning: Could not rehash your Matlab system.')
    disp('  ** Probably a restart of Matlab will be necessary in order')
    disp('  ** to get access to the installed toolbox.')
  end
  
  disp('---------------------------------')
  disp('Original source is http://www.cis.hut.fi/projects/ica/fastica')
  disp('For an overview type:')
  disp(['helpwin ',toolboxpath])
  warning('on')
  
  
%%%%%%% error handling

catch
  z2=whos;x_lasterr=lasterr;y_lastwarn=lastwarn;
  if ~strcmpi(x_lasterr,'Interrupt')
    if fid>-1, 
      try, z_ferror=ferror(fid); catch, z_ferror='No error in the installation I/O process.'; end
    else
      z_ferror='File not found.'; 
    end
    installfile_info=dir([currentpath,filesep,install_file]);
    fid=fopen(fullfile(currentpath,'install.log'),'w');
    checksum_test=findstr(x_lasterr,'The installation file is corrupt!');
    if isempty(checksum_test),checksum_test=0; end
    if ~checksum_test
      fprintf(fid,'%s\n','This script is under development and your assistance is');
      fprintf(fid,'%s\n','urgently welcome. Please inform the distributor of the');
      fprintf(fid,'%s\n','toolbox, where the error occured and send us the following');
      fprintf(fid,'%s\n','error report and the informations about the toolbox (distributor,');
      fprintf(fid,'%s\n','name etc.). Provide a brief description of what you were');
      fprintf(fid,'%s\n','doing when this problem occurred.');
      fprintf(fid,'%s\n','E-mail or FAX this information to us at:');
      fprintf(fid,'%s\n','    E-mail:  marwan@agnld.uni-potsdam.de');
      fprintf(fid,'%s\n','       Fax:  ++49 +331 977 1142');
      fprintf(fid,'%s\n\n\n','Thank you for your assistance.');
      fprintf(fid,'%s\n',repmat('-',50,1));
      fprintf(fid,'%s\n',datestr(now,0));
      fprintf(fid,'%s\n',['Matlab ',char(version),' on ',computer]);
      fprintf(fid,'%s\n',repmat('-',50,1));
      fprintf(fid,'%s\n','Makeinstall Version ==> 3.16 ');
      fprintf(fid,'%s\n',['Install File ==> ',install_file,'/',installfile_info.date,'/',num2str(installfile_info.bytes)]);
      fprintf(fid,'%s\n',['Container ==> ',time_stamp,'/',checksum]);
      fprintf(fid,'%s\n\n',repmat('-',50,1));
      fprintf(fid,'%s\n',x_lasterr);
      fprintf(fid,'%s\n',y_lastwarn);
      fprintf(fid,'%s\n',z_ferror);
      fprintf(fid,'%s\n',[' errorcode ==> ',num2str(errcode)]);
      fprintf(fid,'%s\n',' workspace dump ==>');
      if ~isempty(z2), 
        fprintf(fid,'%s\n',['Name',char(9),'Size',char(9),'Bytes',char(9),'Class']);
        for j=1:length(z2);
          fprintf(fid,'%s',[z2(j).name,char(9),num2str(z2(j).size),char(9),num2str(z2(j).bytes),char(9),z2(j).class]);
          if ~strcmp(z2(j).class,'cell') & ~strcmp(z2(j).class,'struct')
            content=eval(z2(j).name);
            content=mat2str(content(1:min([size(content,1),500]),1:min([size(content,2),500])));
            fprintf(fid,'\t%s',content(1:min([length(content),500])));
          elseif strcmp(z2(j).class,'cell')
            content=eval(z2(j).name);
            fprintf(fid,'\t');
            for j2=1:min([length(content),500])
              if isnumeric(content{j2})
                fprintf(fid,'{%s} ',content{j2}(1:end));
              elseif iscell(content{j2})
                fprintf(fid,'{%s} ',content{j2}{1:end});
              end
            end
          elseif strcmp(z2(j).class,'struct')
            content=fieldnames(eval(z2(j).name));
            content=char(content); content(:,end+1)=' '; content=content';
            fprintf(fid,'\t%s',content(:)');
          end
          fprintf(fid,'%s\n','');
        end
      end
    else
      fprintf(fid,'%s\n','Installation aborted due to a failed checksum test!');
      fprintf(fid,'%s\n',['Checksum should be:     ', checksum]);
      fprintf(fid,'%s\n\n',['Checksum of archive is: ', checksum_file]);
      fprintf(fid,'%s\n','Ensure that the installation file was not modified by any');
      fprintf(fid,'%s\n','other programme, as an anti-virus scanner for emails, a');
      fprintf(fid,'%s\n','mis-configured HTTP proxy or FTP programme.');
    end
    fclose(fid);
    disp('----------------------------');
    disp('       ERROR OCCURED ');
    disp('    during installation');
    disp('----------------------------');
    disp(x_lasterr);
    if ~checksum_test
      disp(z_ferror);
      disp(['   errorcode is ',num2str(errcode)]);
      disp('----------------------------');
      disp('   This script is under development and your assistance is ')
      disp('   urgently welcome. Please inform the distributor of the')
      disp('   toolbox, where the error occured and send us the error')
      disp('   report and the informations about the toolbox (distributor,')
      disp('   name etc.). For your convenience, this information has been')
      disp('   recorded in: ')
      disp(['   ',fullfile(currentpath,'install.log')]), disp(' ')
      disp('   Provide a brief description of what you were doing when ')
      disp('   this problem occurred.'), disp(' ')
      disp('   E-mail or FAX this information to us at:')
      disp('       E-mail:  marwan@agnld.uni-potsdam.de')
      disp('          Fax:  ++49 +331 977 1142'), disp(' ')
      disp('   Thank you for your assistance.')
    end
  end
  warning('on')
  cd(currentpath)
end
% -------------------------------------------
% GENERATED ENTRIES - DO NOT MODIFY ANYTHING!
%<-- Header begins here -->
%@12A8F88D803
%@14-Jun-2007 16:28:54
%@2.3 
%<-- Header ends here -->
%<-- ASCII begins here: __Contents.m__ -->
%@% FastICA for Matlab 6.x
%@% Version 2.3 14-Jun-2007
%@% Copyright (c) Jarmo Hurri, Hugo Gävert, Jaakko Särelä, and Aapo Hyvärinen.
%@%
%@% Type fasticag to launch the graphical user interface
%@%
%@% Please refer to your Matlab documentation on how to add FastICA to your
%@% Matlab search path. (One place to start is the path-command)
%@%
%@% FastICA programs:
%@%   FASTICAG  - Graphical user interface for FastICA
%@%   FASTICA   - command line version of FastICA
%@%
%@% Separate functions used by FastICA programs.
%@%   FPICA     - main algorithm for calculating ICA
%@%   WHITENV   - function for whitening data
%@%   PCAMAT    - calculates the PCA for data
%@%   REMMEAN   - function for removing mean
%@%
%@%   GUI_CB    - needed by fasticag
%@%   GUI_ADV   - needed by fasticag
%@%   GUI_ADVC  - needed by fasticag
%@%   GUI_L     - needed by fasticag
%@%   GUI_LC    - needed by fasticag
%@%   GUI_S     - needed by fasticag
%@%   GUI_SC    - needed by fasticag
%@%   GUI_CG    - needed by fasticag
%@%   GUI_HELP  - needed by fasticag
%@%
%@%   ICAPLOT   - for plotting the signals
%@%               (also used by fastica and fasticag)
%@%
%@% Misc.
%@%   DEMOSIG   - generates some test signals
%@%
%@% Deprecated
%@%   dispsig   - plots the data vectors
%@%               replaced by icaplot
%@
%@% @(#)$Id: Contents.m,v 1.5 2004/07/27 11:46:46 jarmo Exp $
%@% Modified at 14-Jun-2007 16:28:54 by MAKEINSTALL
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __cleanfastica.m__ -->
%@function cleanfastica
%@%CLEANFASTICA   Removes Fast ICA Toolbox.
%@%    CLEANFASTICA removes all files of Fast ICA Toolbox from
%@%    the filesystem and its entry from the Matlab
%@%    startup file.
%@%    
%@%    This installation script was generated by using 
%@%    the MAKEINSTALL tool. For further information
%@%    visit http://matlab.pucicu.de
%@
%@% Copyright (c) 2002-2006 by AMRON
%@% Norbert Marwan, Potsdam University, Germany
%@% http://www.agnld.uni-potsdam.de
%@%
%@% Generation date: 14-Jun-2007 16:28:54
%@% $Date: 2006/11/07 07:55:43 $
%@% $Revision: 3.16 $
%@
%@error(nargchk(0,0,nargin));
%@
%@try
%@  warning('off')
%@  disp('---------------------------------')
%@  disp('    REMOVING Fast ICA Toolbox    ')
%@  disp('---------------------------------')
%@  currentpath=pwd;
%@  oldtoolboxpath = fileparts(which(mfilename));
%@
%@  disp(['  Fast ICA Toolbox found in ', oldtoolboxpath,''])
%@  i = input('> Delete Fast ICA Toolbox? Y/N [Y]: ','s');
%@  if isempty(i), i = 'Y'; end
%@
%@  if strcmpi('Y',i)
%@%%%%%%% check for entries in startup
%@  
%@        p=path; i1=0; i = '';
%@  
%@        while findstr(upper('fastica'),upper(p)) > i1
%@           i1=findstr(upper('fastica'),upper(p));
%@           if ~isempty(i1)
%@               i1=i1(end);
%@               if isunix, i2=findstr(':',p); else, i2=findstr(';',p); end
%@               i3=i2(i2>i1);                 % last index pathname
%@               if ~isempty(i3), i3=i3(1)-1; else, i3=length(p); end
%@               i4=i2(i2<i1);                 % first index pathname
%@               if ~isempty(i4), i4=i4(end)+1; else, i4=1; end
%@               rmtoolboxpath=p(i4:i3);
%@%%%%%%% removing entry in startup-file
%@               rmpath(rmtoolboxpath)
%@               if i4>1, p(i4-1:i3)=''; else, p(i4:i3)=''; end
%@               startup_exist = exist('startup','file');
%@               if startup_exist
%@                    startupfile=which('startup');
%@                    startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
%@                    instpaths=textread(startupfile,'%[^\n]');
%@                    k=1;
%@                    while k <= length(instpaths)
%@                        if ~isempty(findstr(rmtoolboxpath,instpaths{k}))
%@                            disp(['  Removing startup entry ', instpaths{k}])
%@                            instpaths(k)=[];
%@                        end
%@                        k=k+1;
%@                    end
%@                    fid=fopen(startupfile,'w');
%@                    for i2=1:length(instpaths), 
%@                        fprintf(fid,'%s\n', char(instpaths(i2,:))); 
%@                    end
%@                    fclose(fid);
%@               end
%@           end
%@           p = path; i1 = 0;
%@       end
%@%%%%%%% removing old paths
%@        if exist(oldtoolboxpath,'dir') == 7
%@           disp(['  Removing files in ',oldtoolboxpath,''])
%@           cd(oldtoolboxpath)
%@           dirnames='';filenames='';
%@           temp='.:';
%@           while ~isempty(temp)
%@               [temp1 temp]=strtok(temp,':');
%@               if ~isempty(temp1)
%@                   dirnames=[dirnames; {temp1}];
%@                   x2=dir(temp1);
%@                   for i=1:length(x2)
%@                       if ~x2(i).isdir, filenames=[filenames; {[temp1,'/', x2(i).name]}]; end
%@         	             if x2(i).isdir & ~strcmp(x2(i).name,'.') & ~strcmp(x2(i).name,'..'), temp=[temp,temp1,filesep,x2(i).name,':']; end
%@                   end
%@               end
%@           end
%@           dirnames = strrep(dirnames,['.',filesep],'');
%@           dirnames(strcmpi('.',dirnames)) = [];
%@           l = zeros(length(dirnames),1); for i=1:length(dirnames),l(i)=length(dirnames{i}); end
%@           [i i4]=sort(l); i4 = i4(:);
%@           dirnames=dirnames(flipud(i4));
%@           for i=1:length(dirnames)
%@              delete([dirnames{i}, filesep,'*'])
%@              if exist('rmdir') == 5 & exist(dirnames{i}) == 7, rmdir(dirnames{i},'s'), else, delete(dirnames{i}), end
%@              disp(['  Removing files in ',char(dirnames{i}),''])
%@           end
%@           if exist(currentpath), cd(currentpath), else, cd .., end
%@           if strcmpi(currentpath,oldtoolboxpath), cd .., end
%@           if exist('rmdir') == 5 & exist(oldtoolboxpath) == 7, rmdir(oldtoolboxpath,'s'), else, delete(oldtoolboxpath), end
%@           disp(['  Removing folder ',oldtoolboxpath,''])
%@        end
%@       disp(['  Fast ICA Toolbox now removed.'])
%@  else
%@       disp(['  Nothing happened. Keep smiling.'])
%@  end
%@  tx=version; tx=strtok(tx,'.'); if str2double(tx)>=6 & exist('rehash','builtin'), rehash, end
%@  warning on
%@  if exist(currentpath,'dir') ~= 7, cd(fileparts(currentpath)), else, cd(currentpath), end
%@  
%@%%%%%%% error handling
%@
%@catch
%@  x=lasterr;y=lastwarn;
%@  if ~strcmpi(lasterr,'Interrupt')
%@    if fid>-1, 
%@      try, z=ferror(fid); catch, z='No error in the installation I/O process.'; end
%@    else
%@      z='File not found.'; 
%@    end
%@    fid=fopen('deinstall.log','w');
%@    fprintf(fid,'%s\n','This script is under development and your assistance is');
%@    fprintf(fid,'%s\n','urgently welcome. Please inform the distributor of the');
%@    fprintf(fid,'%s\n','toolbox, where the error occured and send us the following');
%@    fprintf(fid,'%s\n','error report and the informations about the toolbox (distributor,');
%@    fprintf(fid,'%s\n','name etc.). Provide a brief description of what you were');
%@    fprintf(fid,'%s\n','doing when this problem occurred.');
%@    fprintf(fid,'%s\n','E-mail or FAX this information to us at:');
%@    fprintf(fid,'%s\n','    E-mail:  marwan@agnld.uni-potsdam.de');
%@    fprintf(fid,'%s\n','       Fax:  ++49 +331 977 1142');
%@    fprintf(fid,'%s\n\n\n','Thank you for your assistance.');
%@    fprintf(fid,'%s\n',repmat('-',50,1));
%@    fprintf(fid,'%s\n',datestr(now,0));
%@    fprintf(fid,'%s\n',['Matlab ',char(version),' on ',computer]);
%@    fprintf(fid,'%s\n',repmat('-',50,1));
%@    fprintf(fid,'%s\n','Fast ICA Toolbox');
%@    fprintf(fid,'%s\n',x);
%@    fprintf(fid,'%s\n',y);
%@    fprintf(fid,'%s\n',z);
%@    fclose(fid);
%@    disp('----------------------------');
%@    disp('       ERROR OCCURED ');
%@    disp('   during deinstallation');
%@    disp('----------------------------');
%@    disp(x);
%@    disp(z);
%@    disp('----------------------------');
%@    disp('   This script is under development and your assistance is ')
%@    disp('   urgently welcome. Please inform the distributor of the')
%@    disp('   toolbox, where the error occured and send us the error')
%@    disp('   report and the informations about the toolbox (distributor,')
%@    disp('   name etc.). For your convenience, this information has been')
%@    disp('   recorded in: ')
%@    disp(['   ',fullfile(pwd,'deinstall.log')]), disp(' ')
%@    disp('   Provide a brief description of what you were doing when ')
%@    disp('   this problem occurred.'), disp(' ')
%@    disp('   E-mail or FAX this information to us at:')
%@    disp('       E-mail:  marwan@agnld.uni-potsdam.de')
%@    disp('          Fax:  ++49 +331 977 1142'), disp(' ')
%@    disp('   Thank you for your assistance.')
%@  end
%@  warning('on')
%@  if exist(currentpath,'dir') == 7, cd(fileparts(currentpath)), else, cd(currentpath), end
%@end
%@
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __demosig.m__ -->
%@function [sig,mixedsig]=demosig();
%@%
%@% function [sig,mixedsig]=demosig();
%@% 
%@% Returns artificially generated test signals, sig, and mixed
%@% signals, mixedsig. Signals are row vectors of
%@% matrices. Input mixedsig to FastICA to see how it works.
%@
%@% @(#)$Id: demosig.m,v 1.2 2003/04/05 14:23:57 jarmo Exp $
%@
%@%create source signals (independent components)
%@N=500; %data size
%@
%@v=[0:N-1];
%@sig=[];
%@sig(1,:)=sin(v/2); %sinusoid
%@sig(2,:)=((rem(v,23)-11)/9).^5; %funny curve
%@sig(3,:)=((rem(v,27)-13)/9); %saw-tooth
%@sig(4,:)=((rand(1,N)<.5)*2-1).*log(rand(1,N)); %impulsive noise
%@
%@for t=1:4
%@sig(t,:)=sig(t,:)/std(sig(t,:));
%@end
%@
%@%remove mean (not really necessary)
%@
%@[sig mean]=remmean(sig);
%@
%@%create mixtures
%@
%@Aorig=rand(size(sig,1));
%@mixedsig=(Aorig*sig);
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __dispsig.m__ -->
%@function dispsig(signalMatrix, range, titlestr);
%@%DISPSIG - deprecated!
%@%
%@% Please use icaplot instead.
%@%
%@%   See also ICAPLOT
%@
%@% @(#)$Id: dispsig.m,v 1.2 2003/04/05 14:23:57 jarmo Exp $
%@
%@fprintf('\nNote: DISPSIG is now deprecated! Please use ICAPLOT.\n');
%@
%@if nargin < 3, titlestr = ''; end
%@if nargin < 2, range = 1:size(signalMatrix, 1); end
%@
%@icaplot('dispsig',signalMatrix',0,range,range,titlestr);
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __fastica.m__ -->
%@function [Out1, Out2, Out3] = fastica(mixedsig, varargin)
%@%FASTICA - Fast Independent Component Analysis
%@%
%@% FastICA for Matlab 6.x
%@% Version: 2.3
%@% July 27 2004
%@% Copyright (c) Jarmo Hurri, Hugo Gävert, Jaakko Särelä, and Aapo Hyvärinen.
%@%
%@% FASTICA(mixedsig) estimates the independent components from given
%@% multidimensional signals. Each row of matrix mixedsig is one
%@% observed signal.  FASTICA uses Hyvarinen's fixed-point algorithm,
%@% see http://www.cis.hut.fi/projects/ica/fastica/. Output from the
%@% function depends on the number output arguments:
%@%
%@% [icasig] = FASTICA (mixedsig); the rows of icasig contain the
%@% estimated independent components.
%@%
%@% [icasig, A, W] = FASTICA (mixedsig); outputs the estimated separating
%@% matrix W and the corresponding mixing matrix A.
%@%
%@% [A, W] = FASTICA (mixedsig); gives only the estimated mixing matrix
%@% A and the separating matrix W.
%@%
%@% Some optional arguments induce other output formats, see below.
%@%
%@% A graphical user interface for FASTICA can be launched by the
%@% command FASTICAG
%@%
%@% FASTICA can be called with numerous optional arguments. Optional
%@% arguments are given in parameter pairs, so that first argument is
%@% the name of the parameter and the next argument is the value for
%@% that parameter. Optional parameter pairs can be given in any order.
%@%
%@% OPTIONAL PARAMETERS:
%@%
%@% Parameter name        Values and description
%@%
%@%======================================================================
%@% --Basic parameters in fixed-point algorithm:
%@%
%@% 'approach'            (string) The decorrelation approach used. Can be
%@%                       symmetric ('symm'), i.e. estimate all the
%@%                       independent component in parallel, or
%@%                       deflation ('defl'), i.e. estimate independent
%@%                       component one-by-one like in projection pursuit.
%@%                       Default is 'defl'.
%@%
%@% 'numOfIC'             (integer) Number of independent components to
%@%                       be estimated. Default equals the dimension of data.
%@%
%@%======================================================================
%@% --Choosing the nonlinearity:
%@%
%@% 'g'                   (string) Chooses the nonlinearity g used in 
%@%                       the fixed-point algorithm. Possible values:
%@%
%@%                       Value of 'g':      Nonlinearity used:
%@%                       'pow3' (default)   g(u)=u^3
%@%                       'tanh'             g(u)=tanh(a1*u)
%@%                       'gauss             g(u)=u*exp(-a2*u^2/2)
%@%                       'skew'             g(u)=u^2
%@% 
%@% 'finetune'		(string) Chooses the nonlinearity g used when 
%@%                       fine-tuning. In addition to same values
%@%                       as for 'g', the possible value 'finetune' is:
%@%                       'off'              fine-tuning is disabled.
%@%
%@% 'a1'                  (number) Parameter a1 used when g='tanh'.
%@%                       Default is 1.
%@% 'a2'                  (number) Parameter a2 used when g='gaus'.
%@%                       Default is 1.
%@%
%@% 'mu'			(number) Step size. Default is 1.
%@%                       If the value of mu is other than 1, then the
%@%                       program will use the stabilized version of the
%@%                       algorithm (see also parameter 'stabilization').
%@%
%@%
%@% 'stabilization'       (string) Values 'on' or 'off'. Default 'off'. 
%@%                       This parameter controls wether the program uses
%@%                       the stabilized version of the algorithm or
%@%                       not. If the stabilization is on, then the value
%@%                       of mu can momentarily be halved if the program
%@%                       senses that the algorithm is stuck between two
%@%                       points (this is called a stroke). Also if there
%@%                       is no convergence before half of the maximum
%@%                       number of iterations has been reached then mu
%@%                       will be halved for the rest of the rounds.
%@% 
%@%======================================================================
%@% --Controlling convergence:
%@%
%@% 'epsilon'             (number) Stopping criterion. Default is 0.0001.
%@%
%@% 'maxNumIterations'    (integer) Maximum number of iterations.
%@%                       Default is 1000.
%@%
%@% 'maxFinetune'         (integer) Maximum number of iterations in 
%@%                       fine-tuning. Default 100.
%@%
%@% 'sampleSize'          (number) [0 - 1] Percentage of samples used in
%@%                       one iteration. Samples are chosen in random.
%@%                       Default is 1 (all samples).
%@%
%@% 'initGuess'           (matrix) Initial guess for A. Default is random.
%@%                       You can now do a "one more" like this: 
%@%                       [ica, A, W] = fastica(mix, 'numOfIC',3);
%@%                       [ica2, A2, W2] = fastica(mix, 'initGuess', A, 'numOfIC', 4);
%@%
%@%======================================================================
%@% --Graphics and text output:
%@%
%@% 'verbose'             (string) Either 'on' or 'off'. Default is
%@%                       'on': report progress of algorithm in text format.
%@%
%@% 'displayMode'         (string) Plot running estimates of independent
%@%                       components: 'signals', 'basis', 'filters' or
%@%                       'off'. Default is 'off'.
%@%
%@% 'displayInterval'     Number of iterations between plots.
%@%                       Default is 1 (plot after every iteration).
%@%
%@%======================================================================
%@% --Controlling reduction of dimension and whitening:
%@%
%@% Reduction of dimension is controlled by 'firstEig' and 'lastEig', or
%@% alternatively by 'interactivePCA'. 
%@%
%@% 'firstEig'            (integer) This and 'lastEig' specify the range for
%@%                       eigenvalues that are retained, 'firstEig' is
%@%                       the index of largest eigenvalue to be
%@%                       retained. Default is 1.
%@%
%@% 'lastEig'             (integer) This is the index of the last (smallest)
%@%                       eigenvalue to be retained. Default equals the
%@%                       dimension of data.
%@%
%@% 'interactivePCA'      (string) Either 'on' or 'off'. When set 'on', the
%@%                       eigenvalues are shown to the user and the
%@%                       range can be specified interactively. Default
%@%                       is 'off'. Can also be set to 'gui'. Then the user
%@%                       can use the same GUI that's in FASTICAG.
%@%
%@% If you already know the eigenvalue decomposition of the covariance
%@% matrix, you can avoid computing it again by giving it with the
%@% following options:
%@%
%@% 'pcaE'                (matrix) Eigenvectors
%@% 'pcaD'                (matrix) Eigenvalues
%@%
%@% If you already know the whitened data, you can give it directly to
%@% the algorithm using the following options:
%@%
%@% 'whiteSig'            (matrix) Whitened signal
%@% 'whiteMat'            (matrix) Whitening matrix
%@% 'dewhiteMat'          (matrix) dewhitening matrix
%@%
%@% If values for all the 'whiteSig', 'whiteSig' and 'dewhiteMat' are
%@% suplied, they will be used in computing the ICA. PCA and whitening
%@% are not performed. Though 'mixedsig' is not used in the main
%@% algorithm it still must be entered - some values are still
%@% calculated from it.
%@%
%@% Performing preprocessing only is possible by the option:
%@%
%@% 'only'                (string) Compute only PCA i.e. reduction of
%@%                       dimension ('pca') or only PCA plus whitening
%@%                       ('white'). Default is 'all': do ICA estimation
%@%                       as well.  This option changes the output
%@%                       format accordingly. For example: 
%@%
%@%                       [whitesig, WM, DWM] = FASTICA(mixedsig, 
%@%                       'only', 'white') 
%@%                       returns the whitened signals, the whitening matrix
%@%                       (WM) and the dewhitening matrix (DWM). (See also
%@%                       WHITENV.) In FastICA the whitening matrix performs
%@%                       whitening and the reduction of dimension. Dewhitening
%@%                       matrix is the pseudoinverse of whitening matrix.
%@%                        
%@%                       [E, D] = FASTICA(mixedsig, 'only', 'pca') 
%@%                       returns the eigenvector (E) and diagonal 
%@%                       eigenvalue (D) matrices  containing the 
%@%                       selected subspaces. 
%@%
%@%======================================================================
%@% EXAMPLES
%@%
%@%       [icasig] = FASTICA (mixedsig, 'approach', 'symm', 'g', 'tanh');
%@%               Do ICA with tanh nonlinearity and in parallel (like
%@%               maximum likelihood estimation for supergaussian data).
%@%
%@%       [icasig] = FASTICA (mixedsig, 'lastEig', 10, 'numOfIC', 3);
%@%               Reduce dimension to 10, and estimate only 3
%@%               independent components.
%@%
%@%       [icasig] = FASTICA (mixedsig, 'verbose', 'off', 'displayMode', 'off');
%@%               Don't output convergence reports and don't plot
%@%               independent components.
%@%
%@%
%@% A graphical user interface for FASTICA can be launched by the
%@% command FASTICAG
%@%
%@%   See also FASTICAG
%@
%@% @(#)$Id: fastica.m,v 1.11 2004/07/27 11:46:46 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Check some basic requirements of the data
%@if nargin == 0,
%@  error ('You must supply the mixed data as input argument.');
%@end
%@
%@if length (size (mixedsig)) > 2,
%@  error ('Input data can not have more than two dimensions.');
%@end
%@
%@if any (any (isnan (mixedsig))),
%@  error ('Input data contains NaN''s.');
%@end
%@
%@if ~isa (mixedsig, 'double')
%@  fprintf ('Warning: converting input data into regular (double) precision.\n');
%@  mixedsig = double (mixedsig);
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Remove the mean and check the data
%@
%@mixedsig = mixedsig';
%@
%@[mixedsig, mixedmean] = remmean(mixedsig);
%@
%@[Dim, NumOfSampl] = size(mixedsig);
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Default values for optional parameters
%@
%@% All
%@verbose           = 'on';
%@
%@% Default values for 'pcamat' parameters
%@firstEig          = 1;
%@lastEig           = Dim;
%@interactivePCA    = 'off';
%@
%@% Default values for 'fpica' parameters
%@approach          = 'defl';
%@numOfIC           = Dim;
%@g                 = 'pow3';
%@finetune          = 'off';
%@a1                = 1;
%@a2                = 1;
%@myy               = 1;
%@stabilization     = 'off';
%@epsilon           = 0.0001;
%@maxNumIterations  = 1000;
%@maxFinetune       = 5;
%@initState         = 'rand';
%@guess             = 0;
%@sampleSize        = 1;
%@displayMode       = 'off';
%@displayInterval   = 1;
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Parameters for fastICA - i.e. this file
%@
%@b_verbose = 1;
%@jumpPCA = 0;
%@jumpWhitening = 0;
%@only = 3;
%@userNumOfIC = 0;
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Read the optional parameters
%@
%@if (rem(length(varargin),2)==1)
%@  error('Optional parameters should always go by pairs');
%@else
%@  for i=1:2:(length(varargin)-1)
%@    if ~ischar (varargin{i}),
%@      error (['Unknown type of optional parameter name (parameter' ...
%@	      ' names must be strings).']);
%@    end
%@    % change the value of parameter
%@    switch lower (varargin{i})
%@     case 'stabilization'
%@      stabilization = lower (varargin{i+1});
%@     case 'maxfinetune'
%@      maxFinetune = varargin{i+1};
%@     case 'samplesize'
%@      sampleSize = varargin{i+1};
%@     case 'verbose'
%@      verbose = lower (varargin{i+1});
%@      % silence this program also
%@      if strcmp (verbose, 'off'), b_verbose = 0; end
%@     case 'firsteig'
%@      firstEig = varargin{i+1};
%@     case 'lasteig'
%@      lastEig = varargin{i+1};
%@     case 'interactivepca'
%@      interactivePCA = lower (varargin{i+1});
%@     case 'approach'
%@      approach = lower (varargin{i+1});
%@     case 'numofic'
%@      numOfIC = varargin{i+1};
%@      % User has suplied new value for numOfIC.
%@      % We'll use this information later on...
%@      userNumOfIC = 1;
%@     case 'g'
%@      g = lower (varargin{i+1});
%@     case 'finetune'
%@      finetune = lower (varargin{i+1});
%@     case 'a1'
%@      a1 = varargin{i+1};
%@     case 'a2'
%@      a2 = varargin{i+1};
%@     case {'mu', 'myy'}
%@      myy = varargin{i+1};
%@     case 'epsilon'
%@      epsilon = varargin{i+1};
%@     case 'maxnumiterations'
%@      maxNumIterations = varargin{i+1};
%@     case 'initguess'
%@      % no use setting 'guess' if the 'initState' is not set
%@      initState = 'guess';
%@      guess = varargin{i+1};
%@     case 'displaymode'
%@      displayMode = lower (varargin{i+1});
%@     case 'displayinterval'
%@      displayInterval = varargin{i+1};
%@     case 'pcae'
%@      % calculate if there are enought parameters to skip PCA
%@      jumpPCA = jumpPCA + 1;
%@      E = varargin{i+1};
%@     case 'pcad'
%@      % calculate if there are enought parameters to skip PCA
%@      jumpPCA = jumpPCA + 1;
%@      D = varargin{i+1};
%@     case 'whitesig'
%@      % calculate if there are enought parameters to skip PCA and whitening
%@      jumpWhitening = jumpWhitening + 1;
%@      whitesig = varargin{i+1};
%@     case 'whitemat'
%@      % calculate if there are enought parameters to skip PCA and whitening
%@      jumpWhitening = jumpWhitening + 1;
%@      whiteningMatrix = varargin{i+1};
%@     case 'dewhitemat'
%@      % calculate if there are enought parameters to skip PCA and whitening
%@      jumpWhitening = jumpWhitening + 1;
%@      dewhiteningMatrix = varargin{i+1};
%@     case 'only'
%@      % if the user only wants to calculate PCA or...
%@      switch lower (varargin{i+1})
%@       case 'pca'
%@	only = 1;
%@       case 'white'
%@	only = 2;
%@       case 'all'
%@	only = 3;
%@      end
%@      
%@     otherwise
%@      % Hmmm, something wrong with the parameter string
%@      error(['Unrecognized parameter: ''' varargin{i} '''']);
%@    end;
%@  end;
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% print information about data
%@if b_verbose
%@  fprintf('Number of signals: %d\n', Dim);
%@  fprintf('Number of samples: %d\n', NumOfSampl);
%@end
%@
%@% Check if the data has been entered the wrong way,
%@% but warn only... it may be on purpose
%@
%@if Dim > NumOfSampl
%@  if b_verbose
%@    fprintf('Warning: ');
%@    fprintf('The signal matrix may be oriented in the wrong way.\n');
%@    fprintf('In that case transpose the matrix.\n\n');
%@  end
%@end
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Calculating PCA
%@
%@% We need the results of PCA for whitening, but if we don't
%@% need to do whitening... then we dont need PCA...
%@if jumpWhitening == 3
%@  if b_verbose,
%@    fprintf ('Whitened signal and corresponding matrises suplied.\n');
%@    fprintf ('PCA calculations not needed.\n');
%@  end;
%@else
%@  
%@  % OK, so first we need to calculate PCA
%@  % Check to see if we already have the PCA data
%@  if jumpPCA == 2,
%@    if b_verbose,
%@      fprintf ('Values for PCA calculations suplied.\n');
%@      fprintf ('PCA calculations not needed.\n');
%@    end;
%@  else
%@    % display notice if the user entered one, but not both, of E and D.
%@    if (jumpPCA > 0) & (b_verbose),
%@      fprintf ('You must suply all of these in order to jump PCA:\n');
%@      fprintf ('''pcaE'', ''pcaD''.\n');
%@    end;
%@    
%@    % Calculate PCA
%@    [E, D]=pcamat(mixedsig, firstEig, lastEig, interactivePCA, verbose);
%@  end
%@end
%@
%@% skip the rest if user only wanted PCA
%@if only > 1
%@  
%@  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@  % Whitening the data
%@  
%@  % Check to see if the whitening is needed...
%@  if jumpWhitening == 3,
%@    if b_verbose,
%@      fprintf ('Whitening not needed.\n');
%@    end;
%@  else
%@    
%@    % Whitening is needed
%@    % display notice if the user entered some of the whitening info, but not all.
%@    if (jumpWhitening > 0) & (b_verbose),
%@      fprintf ('You must suply all of these in order to jump whitening:\n');
%@      fprintf ('''whiteSig'', ''whiteMat'', ''dewhiteMat''.\n');
%@    end;
%@    
%@    % Calculate the whitening
%@    [whitesig, whiteningMatrix, dewhiteningMatrix] = whitenv ...
%@						     (mixedsig, E, D, verbose);
%@  end
%@  
%@end % if only > 1
%@
%@% skip the rest if user only wanted PCA and whitening
%@if only > 2
%@  
%@  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@  % Calculating the ICA
%@  
%@  % Check some parameters
%@  % The dimension of the data may have been reduced during PCA calculations.
%@  % The original dimension is calculated from the data by default, and the
%@  % number of IC is by default set to equal that dimension.
%@  
%@  Dim = size(whitesig, 1);
%@  
%@  % The number of IC's must be less or equal to the dimension of data
%@  if numOfIC > Dim
%@    numOfIC = Dim;
%@    % Show warning only if verbose = 'on' and user suplied a value for 'numOfIC'
%@    if (b_verbose & userNumOfIC)
%@      fprintf('Warning: estimating only %d independent components\n', numOfIC);
%@      fprintf('(Can''t estimate more independent components than dimension of data)\n');
%@    end
%@  end
%@  
%@  % Calculate the ICA with fixed point algorithm.
%@  [A, W] = fpica (whitesig,  whiteningMatrix, dewhiteningMatrix, approach, ...
%@		  numOfIC, g, finetune, a1, a2, myy, stabilization, epsilon, ...
%@		  maxNumIterations, maxFinetune, initState, guess, sampleSize, ...
%@		  displayMode, displayInterval, verbose);
%@  
%@  % Check for valid return
%@  if ~isempty(W)
%@    % Add the mean back in.
%@    if b_verbose
%@      fprintf('Adding the mean back to the data.\n');
%@    end
%@    icasig = W * mixedsig + (W * mixedmean) * ones(1, NumOfSampl);
%@    %icasig = W * mixedsig;
%@    if b_verbose & ...
%@	  (max(abs(W * mixedmean)) > 1e-9) & ...
%@	  (strcmp(displayMode,'signals') | strcmp(displayMode,'on'))
%@      fprintf('Note that the plots don''t have the mean added.\n');
%@    end
%@  else
%@    icasig = [];
%@  end
%@
%@end % if only > 2
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% The output depends on the number of output parameters
%@% and the 'only' parameter.
%@
%@if only == 1    % only PCA
%@  Out1 = E;
%@  Out2 = D;
%@elseif only == 2  % only PCA & whitening
%@  if nargout == 2
%@    Out1 = whiteningMatrix;
%@    Out2 = dewhiteningMatrix;
%@  else
%@    Out1 = whitesig;
%@    Out2 = whiteningMatrix;
%@    Out3 = dewhiteningMatrix;
%@  end
%@else      % ICA
%@  if nargout == 2
%@    Out1 = A;
%@    Out2 = W;
%@  else
%@    Out1 = icasig;
%@    Out2 = A;
%@    Out3 = W;
%@  end
%@end
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __fasticag.m__ -->
%@function fasticag(mixedsig, InitialGuess)
%@%FASTICAG - Fast Independent Component Analysis, the Graphical User Interface
%@%
%@% FASTICAG gives a graphical user interface for performing independent
%@% component analysis by the FastICA package. No arguments are
%@% necessary in the function call.
%@%
%@% Optional arguments can be given in the form:
%@% FASTICAG(mixedsig, initialGuess) where the matrix mixedsig contains the
%@% multidimensional signals as row vectors, and initialGuess gives the
%@% initial value for the mixing matrix used in the algorithm.
%@%
%@% FASTICA uses the fixed-point algorithm developed by Aapo Hyvarinen,
%@% see http://www.cis.hut.fi/projects/ica/fastica/. The Matlab package was
%@% programmed by Jarmo Hurri, Hugo Gavert, Jaakko Sarela, and Aapo
%@% Hyvarinen.
%@%
%@%
%@%   See also FASTICA
%@
%@% @(#)$Id: fasticag.m,v 1.4 2004/07/27 11:35:29 jarmo Exp $
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global values
%@
%@% Handle to this main figure
%@global hf_FastICA_MAIN;
%@
%@% Check to see if GUI is already running
%@% Can't have more than one copy - otherwise the global
%@% variables and handles can get mixed up.
%@if ~isempty(hf_FastICA_MAIN)
%@  error('FastICA GUI already running!');
%@end
%@
%@
%@% Handles to other controls in this main window
%@global ht_FastICA_mixedStatus;
%@global ht_FastICA_dim;
%@global ht_FastICA_numOfSamp;
%@global ht_FastICA_newDim;
%@global ht_FastICA_whiteStatus;
%@global ht_FastICA_icaStatus;
%@global hpm_FastICA_approach;
%@global he_FastICA_numOfIC;
%@global hpm_FastICA_g;
%@global hpm_FastICA_stabilization;
%@
%@% These global variables are used to store all the values
%@% I used to use the 'UserData' field of components, but
%@% that got too complex, so I decided to put everything
%@% in global variables
%@global g_FastICA_mixedsig;
%@global g_FastICA_pca_D;
%@global g_FastICA_pca_E;
%@global g_FastICA_white_sig;
%@global g_FastICA_white_wm;
%@global g_FastICA_white_dwm;
%@global g_FastICA_ica_sig;
%@global g_FastICA_ica_A;
%@global g_FastICA_ica_W;
%@global g_FastICA_initGuess;
%@global g_FastICA_approach;
%@global g_FastICA_numOfIC;
%@global g_FastICA_g;
%@global g_FastICA_finetune;
%@global g_FastICA_a1;
%@global g_FastICA_a2;
%@global g_FastICA_myy;
%@global g_FastICA_stabilization;
%@global g_FastICA_epsilon;
%@global g_FastICA_maxNumIte;
%@global g_FastICA_maxFinetune;
%@global g_FastICA_sampleSize;
%@global g_FastICA_initState;
%@global g_FastICA_displayMo;
%@global g_FastICA_displayIn;
%@global g_FastICA_verbose;
%@
%@% initial values for them:
%@% All the initial values are set here - even for
%@% variables that are not used in this file
%@
%@if nargin < 2
%@  g_FastICA_initGuess = 1;
%@  % The user didn't enter initial guess so we default
%@  % back to random initial state.
%@  g_FastICA_initState = 1;  % see below for string values
%@else
%@  g_FastICA_initGuess = InitialGuess;
%@  % If initial guess was entered, then the user probably
%@  % wan't to use it, eh?
%@  g_FastICA_initState = 2;  % see below for string values
%@end
%@
%@if nargin < 1
%@  g_FastICA_mixedsig = [];
%@else
%@  g_FastICA_mixedsig = mixedsig; % We'll remove mean
%@end                              % the first time we
%@                                 % use this.
%@
%@% Global variable for stopping the ICA calculations
%@global g_FastICA_interrupt;
%@
%@g_FastICA_pca_D = [];
%@g_FastICA_pca_E = [];
%@g_FastICA_white_sig = [];
%@g_FastICA_white_wm = [];
%@g_FastICA_white_dwm = [];
%@g_FastICA_ica_sig = [];
%@g_FastICA_ica_A = [];
%@g_FastICA_ica_W = [];
%@g_FastICA_approach = 1;   % see below for string values
%@g_FastICA_numOfIC = 0;
%@g_FastICA_g = 1;          % see below for string values
%@g_FastICA_finetune = 5;   % see below for string values
%@g_FastICA_a1 = 1;
%@g_FastICA_a2 = 1;
%@g_FastICA_myy = 1;
%@g_FastICA_stabilization = 2; % see below for string values
%@g_FastICA_epsilon = 0.0001;
%@g_FastICA_maxNumIte = 1000;
%@g_FastICA_maxFinetune = 100;
%@g_FastICA_sampleSize = 1;
%@g_FastICA_displayMo = 1;  % see below for string values
%@g_FastICA_displayIn = 1;
%@g_FastICA_verbose = 1;    % see below for string values
%@
%@% These are regarded as constants and are used to store
%@% the strings for the popup menus the current value is
%@% seen in the variables above
%@% D - refers to strings that are displayed
%@% V - refers to string values that are used in FPICA
%@global c_FastICA_appr_strD;
%@global c_FastICA_appr_strV;
%@global c_FastICA_g1_strD;
%@global c_FastICA_g1_strV;
%@global c_FastICA_g2_strD;
%@global c_FastICA_g2_strV;
%@global c_FastICA_finetune_strD;
%@global c_FastICA_finetune_strV;
%@global c_FastICA_stabili_strD;
%@global c_FastICA_stabili_strV;
%@global c_FastICA_iSta_strD;
%@global c_FastICA_iSta_strV;
%@global c_FastICA_dMod_strD;
%@global c_FastICA_dMod_strV;
%@global c_FastICA_verb_strD;
%@global c_FastICA_verb_strV;
%@
%@% All the values for these are set here - even for
%@% variables that are not used in this file
%@
%@c_FastICA_appr_strD = 'deflation|symmetric';
%@c_FastICA_appr_strV = ['defl';'symm'];
%@% The 'g1' and 'g2' below correspond to the values of approach (1 or 2)
%@% Deflation and Symmetric used to have a bit different selection
%@% of available nonlinearities.
%@c_FastICA_g1_strD = 'pow3|tanh|gauss|skew';
%@c_FastICA_g1_strV = ['pow3';'tanh';'gaus';'skew'];
%@c_FastICA_g2_strD = 'pow3|tanh|gauss|skew';
%@c_FastICA_g2_strV = ['pow3';'tanh';'gaus';'skew'];
%@c_FastICA_finetune_strD = 'pow3|tanh|gauss|skew|off';
%@c_FastICA_finetune_strV = ['pow3';'tanh';'gaus';'skew';'off '];
%@c_FastICA_stabili_strD = 'on|off';
%@c_FastICA_stabili_strV = ['on ';'off'];
%@c_FastICA_iSta_strD = 'random|guess';
%@c_FastICA_iSta_strV = ['rand ';'guess'];
%@c_FastICA_dMod_strD = 'signals|basis|filters|off';
%@c_FastICA_dMod_strV = ['signals';'basis  ';'filters';'off    '];
%@c_FastICA_verb_strD = 'on|off';
%@c_FastICA_verb_strV = ['on ';'off'];
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Configuration options
%@FIGURENAME = 'FastICA';
%@FIGURETAG = 'f_FastICA';
%@SCREENSIZE = get(0,'ScreenSize');
%@FIGURESIZE = [round(0.1*SCREENSIZE(3)) (SCREENSIZE(4)-round(0.1*SCREENSIZE(4))-370) 530 370];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the figure
%@a = figure('Color',[0.8 0.8 0.8], ...
%@	   'PaperType','a4letter', ...
%@	   'Name', FIGURENAME, ...
%@	   'NumberTitle', 'off', ...
%@	   'Tag', FIGURETAG, ...
%@	   'Position', FIGURESIZE, ...
%@	   'MenuBar', 'none');
%@% Resizing has to be denied after the window has been created -
%@% otherwise the window shows only as a tiny window in Windows XP.
%@set (a, 'Resize', 'off');
%@
%@hf_FastICA_MAIN = a;
%@
%@set(hf_FastICA_MAIN, 'HandleVisibility', 'callback');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% From here on it get's ugly as I have not had time to clean it up
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the frames
%@pos_l=2;
%@pos_w=FIGURESIZE(3)-4;
%@pos_h=FIGURESIZE(4)-4;
%@pos_t=FIGURESIZE(4)-2-pos_h;
%@h_f_background = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_background');
%@
%@pos_l=4;
%@pos_w=400;
%@pos_h=106;
%@pos_t=FIGURESIZE(4)-4-pos_h;
%@h_f_mixed = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_mixed');
%@
%@pos_h=90;
%@pos_t=FIGURESIZE(4)-(106+4+2)-pos_h;
%@h_f_white = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_white');
%@
%@pos_h=pos_t - 4 - 2;
%@pos_t=4;
%@h_f_ica = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_ica');
%@
%@pos_w=120;
%@pos_l=FIGURESIZE(3)-(pos_w+2+2);
%@pos_h=FIGURESIZE(4)-2*4;
%@pos_t=FIGURESIZE(4)-(4)-pos_h;
%@h_f_side = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.5 0.5 0.5], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_side');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_mixed
%@bgc = get(h_f_mixed, 'BackgroundColor');
%@
%@pos_vspace = 6;
%@pos_hspace = 6;
%@
%@pos_frame=get(h_f_mixed, 'Position');
%@pos_l = pos_frame(1) + 6;
%@pos_h = 16;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - 6;
%@pos_w = 150;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Mixed signals:', ...
%@  'FontWeight', 'bold', ...
%@  'Style','text', ...
%@  'Tag','t_mixed');
%@
%@pos_l = pos_l + pos_w;
%@pos_w = 120;
%@ht_FastICA_mixedStatus = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Not loaded yet', ...
%@  'Style','text', ...
%@  'Tag','t_mixedstatus');
%@
%@% Vähän väliä
%@pos_t = pos_t - 8;
%@
%@pos_l = pos_frame(1) + 6;
%@pos_t = pos_t - pos_h;
%@pos_w = 150;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Number of signals:', ...
%@  'Style','text', ...
%@  'Tag','t_2');
%@
%@pos_l = pos_l + pos_w;
%@pos_w = 50;
%@ht_FastICA_dim = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','', ...
%@  'Style','text', ...
%@  'Tag','t_dim');
%@
%@pos_l = pos_frame(1) + 6;
%@pos_t = pos_t - pos_h;
%@pos_w = 150;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Number of samples:', ...
%@  'Style','text', ...
%@  'Tag','t_3');
%@
%@pos_l = pos_l + pos_w;
%@pos_w = 50;
%@ht_FastICA_numOfSamp = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','', ...
%@  'Style','text', ...
%@  'Tag','t_numOfSamp');
%@
%@
%@% Buttons
%@pos_l = pos_frame(1) + pos_hspace;
%@pos_w = 110;
%@pos_h = 30;
%@pos_t = pos_frame(2) + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb Transpose', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Transpose', ...
%@  'Tag','b_Transpose');
%@
%@pos_w = 130;
%@pos_l = pos_frame(1) + pos_frame(3) - pos_hspace - pos_w;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb ShowMixed', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Plot data', ...
%@  'Tag','b_ShowMixed');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_white
%@pos_frame=get(h_f_white, 'Position');
%@pos_l = pos_frame(1) + 6;
%@pos_h = 16;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - 6;
%@pos_w = 150;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Dimension control:', ...
%@  'FontWeight', 'bold', ...
%@  'Style','text', ...
%@  'Tag','t_white');
%@
%@pos_l = pos_l + pos_w;
%@pos_w = 120;
%@ht_FastICA_whiteStatus = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','', ...
%@  'Style','text', ...
%@  'Tag','t_whiteStatus');
%@
%@% Vähän väliä
%@pos_t = pos_t - 8;
%@
%@pos_l = pos_frame(1) + 6;
%@pos_t = pos_t - pos_h;
%@pos_w = 150;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Reduced dimension:', ...
%@  'Style','text', ...
%@  'Tag','t_4');
%@
%@pos_l = pos_l + pos_w;
%@pos_w = 50;
%@ht_FastICA_newDim = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','', ...
%@  'Style','text', ...
%@  'Tag','t_newDim');
%@
%@
%@% buttons
%@
%@pos_l = pos_frame(1) + pos_hspace;
%@pos_w = 110;
%@pos_h = 30;
%@pos_t = pos_frame(2) + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb DoPCA', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Reduce dim.', ...
%@  'Tag','b_DoPCA');
%@
%@pos_l = pos_l + pos_w + pos_hspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb OrigDim', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Original dim.', ...
%@  'Tag','b_OrigDim');
%@
%@pos_w = 130;
%@pos_h = 30;
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w;
%@pos_t = pos_frame(2) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb ShowWhite', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Plot whitened', ...
%@  'Tag','b_ShowWhite');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_ica
%@pos_frame=get(h_f_ica, 'Position');
%@pos_l = pos_frame(1) + 6;
%@pos_h = 20;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - 6;
%@pos_w = 150;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Fixed point ICA:', ...
%@  'FontWeight', 'bold', ...
%@  'Style','text', ...
%@  'Tag','t_white');
%@
%@pos_l = pos_l + pos_w;
%@pos_w = 120;
%@ht_FastICA_icaStatus = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Not yet done', ...
%@  'Style','text', ...
%@  'Tag','t_icaStatus');
%@
%@% Vähän väliä
%@pos_t = pos_t - 8;
%@
%@%pos_l = pos_frame(1) + 6;
%@pos_l = pos_frame(1) + 6 + 150;
%@pos_t = pos_t - pos_h;
%@%pos_w = 260;
%@pos_w = 120;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Approach:', ...
%@  'Style','text', ...
%@  'Tag','t_5');
%@
%@pos_w = 100;
%@%pos_t = pos_t - 4;
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w;
%@hpm_FastICA_approach = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Callback','gui_cb ChangeApproach', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',c_FastICA_appr_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_approach', ...
%@  'Value',g_FastICA_approach);
%@
%@%pos_t = pos_t - 4;
%@%pos_l = pos_frame(1) + 6;
%@pos_l = pos_frame(1) + 6 + 150;
%@pos_t = pos_t - pos_h;
%@%pos_w = 260;
%@pos_w = 120;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Number of ICs:', ...
%@  'Style','text', ...
%@  'Tag','t_6');
%@
%@pos_w = 100;
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w;
%@he_FastICA_numOfIC = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'Callback','gui_cb ChangeNumOfIC', ...
%@  'HorizontalAlignment','right', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','0', ...
%@  'Style','edit', ...
%@  'Tag','e_numOfIC');
%@
%@%pos_t = pos_t - 4;
%@%pos_l = pos_frame(1) + 6;
%@pos_l = pos_frame(1) + 6 + 150;
%@pos_t = pos_t - pos_h;
%@%pos_w = 260;
%@pos_w = 120;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Nonlinearity (g):', ...
%@  'Style','text', ...
%@  'Tag','t_71');
%@
%@%pos_t = pos_t - 4;
%@pos_w = 100;
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w;
%@hpm_FastICA_g = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Callback','gui_cb ChangeG', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',c_FastICA_g1_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_g', ...
%@  'Value',g_FastICA_g);
%@
%@%pos_t = pos_t - 4;
%@%pos_l = pos_frame(1) + 6;
%@pos_l = pos_frame(1) + 6 + 150;
%@pos_t = pos_t - pos_h;
%@%pos_w = 260;
%@pos_w = 120;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Stabilization:', ...
%@  'Style','text', ...
%@  'Tag','t_71a');
%@
%@%pos_t = pos_t - 4;
%@pos_w = 100;
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w;
%@hpm_FastICA_stabilization = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Callback','gui_cb ChangeStab', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',c_FastICA_stabili_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_stab', ...
%@  'Value',g_FastICA_stabilization);
%@
%@
%@
%@pos_l = pos_frame(1) + pos_vspace;
%@pos_w = 110;
%@pos_h = 30;
%@pos_t = pos_frame(2) + pos_hspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb AdvOpt', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Adv. options >>', ...
%@  'Tag','b_advOpt');
%@
%@pos_w = 130;
%@pos_h = 30;
%@pos_l = pos_frame(1) + pos_frame(3) - pos_vspace - pos_w;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb ShowICASig', ...
%@  'Interruptible', 'on', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Plot ICs', ...
%@  'Tag','b_ShowICASig');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_side
%@pos_vspace = 6;
%@pos_hspace = 10;
%@pos_temp=get(h_f_side, 'Position');
%@pos_l=pos_temp(1)+pos_hspace;
%@pos_w=100;
%@pos_h=30;
%@pos_t=pos_temp(2)+pos_temp(4)-pos_vspace-pos_h;
%@
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb LoadData', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Load data', ...
%@  'Tag','b_LoadData');
%@
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb DoFPICA', ...
%@  'Interruptible', 'on', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Do ICA', ...
%@  'Tag','b_DoFPICA');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb SaveData', ...
%@  'Interruptible', 'off', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Save results', ...
%@  'Tag','b_SaveData');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb Quit', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Quit', ...
%@  'Tag','b_Quit');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb Interrupt', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Interrupt', ...
%@  'Visible','off', ...
%@  'Tag','b_Interrupt');
%@
%@pos_t = pos_frame(2) + pos_vspace + pos_h + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb About', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','About...', ...
%@  'Tag','b_About');
%@
%@pos_t = pos_frame(2) + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_cb Help', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Help', ...
%@  'Tag','b_Help');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Do rest of the initialization...
%@  gui_cb InitAll;
%@
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __fpica.m__ -->
%@function [A, W] = fpica(X, whiteningMatrix, dewhiteningMatrix, approach, ...
%@			numOfIC, g, finetune, a1, a2, myy, stabilization, ...
%@			epsilon, maxNumIterations, maxFinetune, initState, ...
%@			guess, sampleSize, displayMode, displayInterval, ...
%@			s_verbose);
%@%FPICA - Fixed point ICA. Main algorithm of FASTICA.
%@%
%@% [A, W] = fpica(whitesig, whiteningMatrix, dewhiteningMatrix, approach,
%@%        numOfIC, g, finetune, a1, a2, mu, stabilization, epsilon, 
%@%        maxNumIterations, maxFinetune, initState, guess, sampleSize,
%@%        displayMode, displayInterval, verbose);
%@% 
%@% Perform independent component analysis using Hyvarinen's fixed point
%@% algorithm. Outputs an estimate of the mixing matrix A and its inverse W.
%@%
%@% whitesig                              :the whitened data as row vectors
%@% whiteningMatrix                       :can be obtained with function whitenv
%@% dewhiteningMatrix                     :can be obtained with function whitenv
%@% approach      [ 'symm' | 'defl' ]     :the approach used (deflation or symmetric)
%@% numOfIC       [ 0 - Dim of whitesig ] :number of independent components estimated
%@% g             [ 'pow3' | 'tanh' |     :the nonlinearity used
%@%                 'gaus' | 'skew' ]     
%@% finetune      [same as g + 'off']     :the nonlinearity used in finetuning.
%@% a1                                    :parameter for tuning 'tanh'
%@% a2                                    :parameter for tuning 'gaus'
%@% mu                                    :step size in stabilized algorithm
%@% stabilization [ 'on' | 'off' ]        :if mu < 1 then automatically on
%@% epsilon                               :stopping criterion
%@% maxNumIterations                      :maximum number of iterations 
%@% maxFinetune                           :maximum number of iteretions for finetuning
%@% initState     [ 'rand' | 'guess' ]    :initial guess or random initial state. See below
%@% guess                                 :initial guess for A. Ignored if initState = 'rand'
%@% sampleSize    [ 0 - 1 ]               :percentage of the samples used in one iteration
%@% displayMode   [ 'signals' | 'basis' | :plot running estimate
%@%                 'filters' | 'off' ]
%@% displayInterval                       :number of iterations we take between plots
%@% verbose       [ 'on' | 'off' ]        :report progress in text format
%@%
%@% EXAMPLE
%@%       [E, D] = pcamat(vectors);
%@%       [nv, wm, dwm] = whitenv(vectors, E, D);
%@%       [A, W] = fpica(nv, wm, dwm);
%@%
%@%
%@% This function is needed by FASTICA and FASTICAG
%@%
%@%   See also FASTICA, FASTICAG, WHITENV, PCAMAT
%@
%@% @(#)$Id: fpica.m,v 1.6 2004/07/27 11:37:17 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variable for stopping the ICA calculations from the GUI
%@global g_FastICA_interrupt;
%@if isempty(g_FastICA_interrupt)
%@  clear global g_FastICA_interrupt;
%@  interruptible = 0;
%@else
%@  interruptible = 1;
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Default values
%@
%@if nargin < 3, error('Not enough arguments!'); end
%@[vectorSize, numSamples] = size(X);
%@if nargin < 20, s_verbose = 'on'; end
%@if nargin < 19, displayInterval = 1; end
%@if nargin < 18, displayMode = 'on'; end
%@if nargin < 17, sampleSize = 1; end
%@if nargin < 16, guess = 1; end
%@if nargin < 15, initState = 'rand'; end
%@if nargin < 14, maxFinetune = 100; end
%@if nargin < 13, maxNumIterations = 1000; end
%@if nargin < 12, epsilon = 0.0001; end
%@if nargin < 11, stabilization = 'on'; end
%@if nargin < 10, myy = 1; end
%@if nargin < 9, a2 = 1; end
%@if nargin < 8, a1 = 1; end
%@if nargin < 7, finetune = 'off'; end
%@if nargin < 6, g = 'pow3'; end
%@if nargin < 5, numOfIC = vectorSize; end     % vectorSize = Dim
%@if nargin < 4, approach = 'defl'; end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the data
%@
%@if ~isreal(X)
%@  error('Input has an imaginary part.');
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the value for verbose
%@
%@switch lower(s_verbose)
%@ case 'on'
%@  b_verbose = 1;
%@ case 'off'
%@  b_verbose = 0;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the value for approach
%@
%@switch lower(approach)
%@ case 'symm'
%@  approachMode = 1;
%@ case 'defl'
%@  approachMode = 2;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''approach''\n', approach));
%@end
%@if b_verbose, fprintf('Used approach [ %s ].\n', approach); end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the value for numOfIC
%@
%@if vectorSize < numOfIC
%@  error('Must have numOfIC <= Dimension!');
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the sampleSize
%@if sampleSize > 1
%@  sampleSize = 1;
%@  if b_verbose
%@    fprintf('Warning: Setting ''sampleSize'' to 1.\n');
%@  end  
%@elseif sampleSize < 1
%@  if (sampleSize * numSamples) < 1000
%@    sampleSize = min(1000/numSamples, 1);
%@    if b_verbose
%@      fprintf('Warning: Setting ''sampleSize'' to %0.3f (%d samples).\n', ...
%@	      sampleSize, floor(sampleSize * numSamples));
%@    end  
%@  end
%@end
%@if b_verbose
%@  if  b_verbose & (sampleSize < 1)
%@    fprintf('Using about %0.0f%% of the samples in random order in every step.\n',sampleSize*100);
%@  end
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the value for nonlinearity.
%@
%@switch lower(g)
%@ case 'pow3'
%@  gOrig = 10;
%@ case 'tanh'
%@  gOrig = 20;
%@ case {'gaus', 'gauss'}
%@  gOrig = 30;
%@ case 'skew'
%@  gOrig = 40;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''g''\n', g));
%@end
%@if sampleSize ~= 1
%@  gOrig = gOrig + 2;
%@end
%@if myy ~= 1
%@  gOrig = gOrig + 1;
%@end
%@
%@if b_verbose,
%@  fprintf('Used nonlinearity [ %s ].\n', g);
%@end
%@
%@finetuningEnabled = 1;
%@switch lower(finetune)
%@ case 'pow3'
%@  gFine = 10 + 1;
%@ case 'tanh'
%@  gFine = 20 + 1;
%@ case {'gaus', 'gauss'}
%@  gFine = 30 + 1;
%@ case 'skew'
%@  gFine = 40 + 1;
%@ case 'off'
%@  if myy ~= 1
%@    gFine = gOrig;
%@  else 
%@    gFine = gOrig + 1;
%@  end
%@  finetuningEnabled = 0;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''finetune''\n', ...
%@		finetune));
%@end
%@
%@if b_verbose & finetuningEnabled
%@  fprintf('Finetuning enabled (nonlinearity: [ %s ]).\n', finetune);
%@end
%@
%@switch lower(stabilization)
%@ case 'on'
%@  stabilizationEnabled = 1;
%@ case 'off'
%@  if myy ~= 1
%@    stabilizationEnabled = 1;
%@  else
%@    stabilizationEnabled = 0;
%@  end
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''stabilization''\n', ...
%@		stabilization)); 
%@end
%@
%@if b_verbose & stabilizationEnabled
%@  fprintf('Using stabilized algorithm.\n');
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Some other parameters
%@myyOrig = myy;
%@% When we start fine-tuning we'll set myy = myyK * myy
%@myyK = 0.01;
%@% How many times do we try for convergence until we give up.
%@failureLimit = 5;
%@
%@
%@usedNlinearity = gOrig;
%@stroke = 0;
%@notFine = 1;
%@long = 0;
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the value for initial state.
%@
%@switch lower(initState)
%@ case 'rand'
%@  initialStateMode = 0;
%@ case 'guess'
%@  if size(guess,1) ~= size(whiteningMatrix,2)
%@    initialStateMode = 0;
%@    if b_verbose
%@      fprintf('Warning: size of initial guess is incorrect. Using random initial guess.\n');
%@    end
%@  else
%@    initialStateMode = 1;
%@    if size(guess,2) < numOfIC
%@      if b_verbose
%@	fprintf('Warning: initial guess only for first %d components. Using random initial guess for others.\n', size(guess,2)); 
%@      end
%@      guess(:, size(guess, 2) + 1:numOfIC) = ...
%@					     rand(vectorSize,numOfIC-size(guess,2))-.5;
%@    elseif size(guess,2)>numOfIC
%@      guess=guess(:,1:numOfIC);
%@      fprintf('Warning: Initial guess too large. The excess column are dropped.\n');
%@    end
%@    if b_verbose, fprintf('Using initial guess.\n'); end
%@  end
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''initState''\n', initState));
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Checking the value for display mode.
%@
%@switch lower(displayMode)
%@ case {'off', 'none'}
%@  usedDisplay = 0;
%@ case {'on', 'signals'}
%@  usedDisplay = 1;
%@  if (b_verbose & (numSamples > 10000))
%@    fprintf('Warning: Data vectors are very long. Plotting may take long time.\n');
%@  end
%@  if (b_verbose & (numOfIC > 25))
%@    fprintf('Warning: There are too many signals to plot. Plot may not look good.\n');
%@  end
%@ case 'basis'
%@  usedDisplay = 2;
%@  if (b_verbose & (numOfIC > 25))
%@    fprintf('Warning: There are too many signals to plot. Plot may not look good.\n');
%@  end
%@ case 'filters'
%@  usedDisplay = 3;
%@  if (b_verbose & (vectorSize > 25))
%@    fprintf('Warning: There are too many signals to plot. Plot may not look good.\n');
%@  end
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''displayMode''\n', displayMode));
%@end
%@
%@% The displayInterval can't be less than 1...
%@if displayInterval < 1
%@  displayInterval = 1;
%@end
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@if b_verbose, fprintf('Starting ICA calculation...\n'); end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% SYMMETRIC APPROACH
%@if approachMode == 1,
%@
%@  % set some parameters more...
%@  usedNlinearity = gOrig;
%@  stroke = 0;
%@  notFine = 1;
%@  long = 0;
%@  
%@  A = zeros(vectorSize, numOfIC);  % Dewhitened basis vectors.
%@  if initialStateMode == 0
%@    % Take random orthonormal initial vectors.
%@    B = orth(rand(vectorSize, numOfIC) - .5);
%@  elseif initialStateMode == 1
%@    % Use the given initial vector as the initial state
%@    B = whiteningMatrix * guess;
%@  end
%@  
%@  BOld = zeros(size(B));
%@  BOld2 = zeros(size(B));
%@  
%@  % This is the actual fixed-point iteration loop.
%@  for round = 1:maxNumIterations + 1,
%@    if round == maxNumIterations + 1,
%@      fprintf('No convergence after %d steps\n', maxNumIterations);
%@      fprintf('Note that the plots are probably wrong.\n');
%@      if ~isempty(B)
%@	W = B' * whiteningMatrix;
%@	A = dewhiteningMatrix * B;
%@      else
%@	W = [];
%@	A = [];
%@      end
%@      return;
%@    end
%@    
%@    if (interruptible & g_FastICA_interrupt)
%@      if b_verbose 
%@        fprintf('\n\nCalculation interrupted by the user\n');
%@      end
%@      if ~isempty(B)
%@	W = B' * whiteningMatrix;
%@	A = dewhiteningMatrix * B;
%@      else
%@	W = [];
%@	A = [];
%@      end
%@      return;
%@    end
%@    
%@    
%@    % Symmetric orthogonalization.
%@    B = B * real(inv(B' * B)^(1/2));
%@    
%@    % Test for termination condition. Note that we consider opposite
%@    % directions here as well.
%@    minAbsCos = min(abs(diag(B' * BOld)));
%@    minAbsCos2 = min(abs(diag(B' * BOld2)));
%@    
%@    if (1 - minAbsCos < epsilon)
%@      if finetuningEnabled & notFine
%@        if b_verbose, fprintf('Initial convergence, fine-tuning: \n'); end;
%@        notFine = 0;
%@        usedNlinearity = gFine;
%@        myy = myyK * myyOrig;
%@        BOld = zeros(size(B));
%@        BOld2 = zeros(size(B));
%@	
%@      else
%@        if b_verbose, fprintf('Convergence after %d steps\n', round); end
%@	
%@        % Calculate the de-whitened vectors.
%@        A = dewhiteningMatrix * B;
%@        break;
%@      end
%@    elseif stabilizationEnabled
%@      if (~stroke) & (1 - minAbsCos2 < epsilon)
%@	if b_verbose, fprintf('Stroke!\n'); end;
%@	stroke = myy;
%@	myy = .5*myy;
%@	if mod(usedNlinearity,2) == 0
%@	  usedNlinearity = usedNlinearity + 1;
%@	end
%@      elseif stroke
%@	myy = stroke;
%@	stroke = 0;
%@	if (myy == 1) & (mod(usedNlinearity,2) ~= 0)
%@	  usedNlinearity = usedNlinearity - 1;
%@	end
%@      elseif (~long) & (round>maxNumIterations/2)
%@	if b_verbose, fprintf('Taking long (reducing step size)\n'); end;
%@	long = 1;
%@	myy = .5*myy;
%@	if mod(usedNlinearity,2) == 0
%@	  usedNlinearity = usedNlinearity + 1;
%@	end
%@      end
%@    end
%@    
%@    BOld2 = BOld;
%@    BOld = B;
%@    
%@    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@    % Show the progress...
%@    if b_verbose
%@      if round == 1
%@        fprintf('Step no. %d\n', round);
%@      else
%@        fprintf('Step no. %d, change in value of estimate: %.3g \n', round, 1 - minAbsCos);
%@      end
%@    end
%@    
%@    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@    % Also plot the current state...
%@    switch usedDisplay
%@     case 1
%@      if rem(round, displayInterval) == 0,
%@	% There was and may still be other displaymodes...
%@	% 1D signals
%@	icaplot('dispsig',(X'*B)');
%@	drawnow;
%@      end
%@     case 2
%@      if rem(round, displayInterval) == 0,
%@	% ... and now there are :-)
%@	% 1D basis
%@	A = dewhiteningMatrix * B;
%@	icaplot('dispsig',A');
%@	drawnow;
%@      end
%@     case 3
%@      if rem(round, displayInterval) == 0,
%@	% ... and now there are :-)
%@	% 1D filters
%@	W = B' * whiteningMatrix;
%@	icaplot('dispsig',W);
%@	drawnow;
%@      end
%@     otherwise
%@    end
%@B
%@    switch usedNlinearity
%@      % pow3
%@     case 10
%@      B = (X * (( X' * B) .^ 3)) / numSamples - 3 * B;
%@     case 11
%@      % optimoitu - epsilonin kokoisia eroja
%@      % tämä on optimoitu koodi, katso vanha koodi esim.
%@      % aikaisemmista versioista kuten 2.0 beta3
%@      Y = X' * B;
%@      Gpow3 = Y .^ 3;
%@      Beta = sum(Y .* Gpow3);
%@      D = diag(1 ./ (Beta - 3 * numSamples));
%@      B = B + myy * B * (Y' * Gpow3 - diag(Beta)) * D;
%@     case 12
%@      Xsub=X(:, getSamples(numSamples, sampleSize));
%@      B = (Xsub * (( Xsub' * B) .^ 3)) / size(Xsub,2) - 3 * B;
%@     case 13
%@      % Optimoitu
%@      Ysub=X(:, getSamples(numSamples, sampleSize))' * B;
%@      Gpow3 = Ysub .^ 3;
%@      Beta = sum(Ysub .* Gpow3);
%@      D = diag(1 ./ (Beta - 3 * size(Ysub', 2)));
%@      B = B + myy * B * (Ysub' * Gpow3 - diag(Beta)) * D;
%@      
%@      % tanh
%@     case 20
%@      hypTan = tanh(a1 * X' * B);
%@      B = X * hypTan / numSamples - ...
%@	  ones(size(B,1),1) * sum(1 - hypTan .^ 2) .* B / numSamples * ...
%@	  a1;
%@     case 21
%@      % optimoitu - epsilonin kokoisia 
%@      Y = X' * B;
%@      hypTan = tanh(a1 * Y);
%@      Beta = sum(Y .* hypTan);
%@      D = diag(1 ./ (Beta - a1 * sum(1 - hypTan .^ 2)));
%@      B = B + myy * B * (Y' * hypTan - diag(Beta)) * D;
%@     case 22
%@      Xsub=X(:, getSamples(numSamples, sampleSize));
%@      hypTan = tanh(a1 * Xsub' * B);
%@      B = Xsub * hypTan / size(Xsub, 2) - ...
%@	  ones(size(B,1),1) * sum(1 - hypTan .^ 2) .* B / size(Xsub, 2) * a1;
%@     case 23
%@      % Optimoitu
%@      Y = X(:, getSamples(numSamples, sampleSize))' * B;
%@      hypTan = tanh(a1 * Y);
%@      Beta = sum(Y .* hypTan);
%@      D = diag(1 ./ (Beta - a1 * sum(1 - hypTan .^ 2)));
%@      B = B + myy * B * (Y' * hypTan - diag(Beta)) * D;
%@      
%@      % gauss
%@     case 30
%@      U = X' * B;
%@      Usquared=U .^ 2;
%@      ex = exp(-a2 * Usquared / 2);
%@      gauss =  U .* ex;
%@      dGauss = (1 - a2 * Usquared) .*ex;
%@      B = X * gauss / numSamples - ...
%@	  ones(size(B,1),1) * sum(dGauss)...
%@	  .* B / numSamples ;
%@     case 31
%@      % optimoitu
%@      Y = X' * B;
%@      ex = exp(-a2 * (Y .^ 2) / 2);
%@      gauss = Y .* ex;
%@      Beta = sum(Y .* gauss);
%@      D = diag(1 ./ (Beta - sum((1 - a2 * (Y .^ 2)) .* ex)));
%@      B = B + myy * B * (Y' * gauss - diag(Beta)) * D;
%@     case 32
%@      Xsub=X(:, getSamples(numSamples, sampleSize));
%@      U = Xsub' * B;
%@      Usquared=U .^ 2;
%@      ex = exp(-a2 * Usquared / 2);
%@      gauss =  U .* ex;
%@      dGauss = (1 - a2 * Usquared) .*ex;
%@      B = Xsub * gauss / size(Xsub,2) - ...
%@	  ones(size(B,1),1) * sum(dGauss)...
%@	  .* B / size(Xsub,2) ;
%@     case 33
%@      % Optimoitu
%@      Y = X(:, getSamples(numSamples, sampleSize))' * B;
%@      ex = exp(-a2 * (Y .^ 2) / 2);
%@      gauss = Y .* ex;
%@      Beta = sum(Y .* gauss);
%@      D = diag(1 ./ (Beta - sum((1 - a2 * (Y .^ 2)) .* ex)));
%@      B = B + myy * B * (Y' * gauss - diag(Beta)) * D;
%@      
%@      % skew
%@     case 40
%@      B = (X * ((X' * B) .^ 2)) / numSamples;
%@     case 41
%@      % Optimoitu
%@      Y = X' * B;
%@      Gskew = Y .^ 2;
%@      Beta = sum(Y .* Gskew);
%@      D = diag(1 ./ (Beta));
%@      B = B + myy * B * (Y' * Gskew - diag(Beta)) * D;
%@     case 42
%@      Xsub=X(:, getSamples(numSamples, sampleSize));
%@      B = (Xsub * ((Xsub' * B) .^ 2)) / size(Xsub,2);
%@     case 43
%@      % Uusi optimoitu
%@      Y = X(:, getSamples(numSamples, sampleSize))' * B;
%@      Gskew = Y .^ 2;
%@      Beta = sum(Y .* Gskew);
%@      D = diag(1 ./ (Beta));
%@      B = B + myy * B * (Y' * Gskew - diag(Beta)) * D;
%@
%@     otherwise
%@      error('Code for desired nonlinearity not found!');
%@    end
%@  end
%@
%@  
%@  % Calculate ICA filters.
%@  W = B' * whiteningMatrix;
%@  
%@  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@  % Also plot the last one...
%@  switch usedDisplay
%@   case 1 
%@    % There was and may still be other displaymodes...
%@    % 1D signals
%@    icaplot('dispsig',(X'*B)');
%@    drawnow;
%@   case 2
%@    % ... and now there are :-)
%@    % 1D basis
%@    icaplot('dispsig',A');
%@    drawnow;
%@   case 3
%@    % ... and now there are :-)
%@    % 1D filters
%@    icaplot('dispsig',W);
%@    drawnow;
%@   otherwise
%@  end
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% DEFLATION APPROACH
%@if approachMode == 2
%@  
%@  B = zeros(vectorSize);
%@  
%@  % The search for a basis vector is repeated numOfIC times.
%@  round = 1;
%@  
%@  numFailures = 0;
%@  
%@  while round <= numOfIC,
%@    myy = myyOrig;
%@    usedNlinearity = gOrig;
%@    stroke = 0;
%@    notFine = 1;
%@    long = 0;
%@    endFinetuning = 0;
%@    
%@    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@    % Show the progress...
%@    if b_verbose, fprintf('IC %d ', round); end
%@    
%@    % Take a random initial vector of lenght 1 and orthogonalize it
%@    % with respect to the other vectors.
%@    if initialStateMode == 0
%@      w = rand(vectorSize, 1) - .5;
%@    elseif initialStateMode == 1
%@      w=whiteningMatrix*guess(:,round);
%@    end
%@    w = w - B * B' * w;
%@    w = w / norm(w);
%@    
%@    wOld = zeros(size(w));
%@    wOld2 = zeros(size(w));
%@    
%@    % This is the actual fixed-point iteration loop.
%@    %    for i = 1 : maxNumIterations + 1
%@    i = 1;
%@    gabba = 1;
%@    while i <= maxNumIterations + gabba
%@      if (usedDisplay > 0)
%@	drawnow;
%@      end
%@      if (interruptible & g_FastICA_interrupt)
%@        if b_verbose 
%@          fprintf('\n\nCalculation interrupted by the user\n');
%@        end
%@        return;
%@      end
%@      
%@      % Project the vector into the space orthogonal to the space
%@      % spanned by the earlier found basis vectors. Note that we can do
%@      % the projection with matrix B, since the zero entries do not
%@      % contribute to the projection.
%@      w = w - B * B' * w;
%@      w = w / norm(w);
%@      
%@      if notFine
%@	if i == maxNumIterations + 1
%@	  if b_verbose
%@	    fprintf('\nComponent number %d did not converge in %d iterations.\n', round, maxNumIterations);
%@	  end
%@	  round = round - 1;
%@	  numFailures = numFailures + 1;
%@	  if numFailures > failureLimit
%@	    if b_verbose
%@	      fprintf('Too many failures to converge (%d). Giving up.\n', numFailures);
%@	    end
%@	    if round == 0
%@	      A=[];
%@	      W=[];
%@	    end
%@	    return;
%@	  end
%@	  % numFailures > failurelimit
%@	  break;
%@	end
%@	% i == maxNumIterations + 1
%@      else
%@	% if notFine
%@	if i >= endFinetuning
%@	  wOld = w; % So the algorithm will stop on the next test...
%@	end
%@      end
%@      % if notFine
%@      
%@      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@      % Show the progress...
%@      if b_verbose, fprintf('.'); end;
%@      
%@      
%@      % Test for termination condition. Note that the algorithm has
%@      % converged if the direction of w and wOld is the same, this
%@      % is why we test the two cases.
%@      if norm(w - wOld) < epsilon | norm(w + wOld) < epsilon
%@        if finetuningEnabled & notFine
%@          if b_verbose, fprintf('Initial convergence, fine-tuning: '); end;
%@          notFine = 0;
%@	  gabba = maxFinetune;
%@          wOld = zeros(size(w));
%@          wOld2 = zeros(size(w));
%@          usedNlinearity = gFine;
%@          myy = myyK * myyOrig;
%@	  
%@	  endFinetuning = maxFinetune + i;
%@	  
%@        else
%@          numFailures = 0;
%@          % Save the vector
%@          B(:, round) = w;
%@	  
%@          % Calculate the de-whitened vector.
%@          A(:,round) = dewhiteningMatrix * w;
%@          % Calculate ICA filter.
%@          W(round,:) = w' * whiteningMatrix;
%@	  
%@          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@          % Show the progress...
%@          if b_verbose, fprintf('computed ( %d steps ) \n', i); end
%@	  
%@          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@          % Also plot the current state...
%@          switch usedDisplay
%@	   case 1
%@	    if rem(round, displayInterval) == 0,
%@	      % There was and may still be other displaymodes...   
%@	      % 1D signals
%@	      temp = X'*B;
%@	      icaplot('dispsig',temp(:,1:numOfIC)');
%@	      drawnow;
%@	    end
%@	   case 2
%@	    if rem(round, displayInterval) == 0,
%@	      % ... and now there are :-) 
%@	      % 1D basis
%@	      icaplot('dispsig',A');
%@	      drawnow;
%@	    end
%@	   case 3
%@	    if rem(round, displayInterval) == 0,
%@	      % ... and now there are :-) 
%@	      % 1D filters
%@	      icaplot('dispsig',W);
%@	      drawnow;
%@	    end
%@          end
%@	  % switch usedDisplay
%@	  break; % IC ready - next...
%@        end
%@	%if finetuningEnabled & notFine
%@      elseif stabilizationEnabled
%@	if (~stroke) & (norm(w - wOld2) < epsilon | norm(w + wOld2) < ...
%@			epsilon)
%@	  stroke = myy;
%@	  if b_verbose, fprintf('Stroke!'); end;
%@	  myy = .5*myy;
%@	  if mod(usedNlinearity,2) == 0
%@	    usedNlinearity = usedNlinearity + 1;
%@	  end
%@	elseif stroke
%@	  myy = stroke;
%@	  stroke = 0;
%@	  if (myy == 1) & (mod(usedNlinearity,2) ~= 0)
%@	    usedNlinearity = usedNlinearity - 1;
%@	  end
%@	elseif (notFine) & (~long) & (i > maxNumIterations / 2)
%@	  if b_verbose, fprintf('Taking long (reducing step size) '); end;
%@	  long = 1;
%@	  myy = .5*myy;
%@	  if mod(usedNlinearity,2) == 0
%@	    usedNlinearity = usedNlinearity + 1;
%@	  end
%@	end
%@      end
%@      
%@      wOld2 = wOld;
%@      wOld = w;
%@      
%@      switch usedNlinearity
%@	% pow3
%@       case 10
%@	w = (X * ((X' * w) .^ 3)) / numSamples - 3 * w;
%@       case 11
%@	EXGpow3 = (X * ((X' * w) .^ 3)) / numSamples;
%@	Beta = w' * EXGpow3;
%@	w = w - myy * (EXGpow3 - Beta * w) / (3 - Beta);
%@       case 12
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	w = (Xsub * ((Xsub' * w) .^ 3)) / size(Xsub, 2) - 3 * w;
%@       case 13
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	EXGpow3 = (Xsub * ((Xsub' * w) .^ 3)) / size(Xsub, 2);
%@	Beta = w' * EXGpow3;
%@	w = w - myy * (EXGpow3 - Beta * w) / (3 - Beta);
%@	% tanh
%@       case 20
%@	hypTan = tanh(a1 * X' * w);
%@	w = (X * hypTan - a1 * sum(1 - hypTan .^ 2)' * w) / numSamples;
%@       case 21
%@	hypTan = tanh(a1 * X' * w);
%@	Beta = w' * X * hypTan;
%@	w = w - myy * ((X * hypTan - Beta * w) / ...
%@		       (a1 * sum((1-hypTan .^2)') - Beta));
%@       case 22
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	hypTan = tanh(a1 * Xsub' * w);
%@	w = (Xsub * hypTan - a1 * sum(1 - hypTan .^ 2)' * w) / size(Xsub, 2);
%@       case 23
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	hypTan = tanh(a1 * Xsub' * w);
%@	Beta = w' * Xsub * hypTan;
%@	w = w - myy * ((Xsub * hypTan - Beta * w) / ...
%@		       (a1 * sum((1-hypTan .^2)') - Beta));
%@	% gauss
%@       case 30
%@	% This has been split for performance reasons.
%@	u = X' * w;
%@	u2=u.^2;
%@	ex=exp(-a2 * u2/2);
%@	gauss =  u.*ex;
%@	dGauss = (1 - a2 * u2) .*ex;
%@	w = (X * gauss - sum(dGauss)' * w) / numSamples;
%@       case 31
%@	u = X' * w;
%@	u2=u.^2;
%@	ex=exp(-a2 * u2/2);
%@	gauss =  u.*ex;
%@	dGauss = (1 - a2 * u2) .*ex;
%@	Beta = w' * X * gauss;
%@	w = w - myy * ((X * gauss - Beta * w) / ...
%@		       (sum(dGauss)' - Beta));
%@       case 32
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	u = Xsub' * w;
%@	u2=u.^2;
%@	ex=exp(-a2 * u2/2);
%@	gauss =  u.*ex;
%@	dGauss = (1 - a2 * u2) .*ex;
%@	w = (Xsub * gauss - sum(dGauss)' * w) / size(Xsub, 2);
%@       case 33
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	u = Xsub' * w;
%@	u2=u.^2;
%@	ex=exp(-a2 * u2/2);
%@	gauss =  u.*ex;
%@	dGauss = (1 - a2 * u2) .*ex;
%@	Beta = w' * Xsub * gauss;
%@	w = w - myy * ((Xsub * gauss - Beta * w) / ...
%@		       (sum(dGauss)' - Beta));
%@	% skew
%@       case 40
%@	w = (X * ((X' * w) .^ 2)) / numSamples;
%@       case 41
%@	EXGskew = (X * ((X' * w) .^ 2)) / numSamples;
%@	Beta = w' * EXGskew;
%@	w = w - myy * (EXGskew - Beta*w)/(-Beta);
%@       case 42
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	w = (Xsub * ((Xsub' * w) .^ 2)) / size(Xsub, 2);
%@       case 43
%@	Xsub=X(:,getSamples(numSamples, sampleSize));
%@	EXGskew = (Xsub * ((Xsub' * w) .^ 2)) / size(Xsub, 2);
%@	Beta = w' * EXGskew;
%@	w = w - myy * (EXGskew - Beta*w)/(-Beta);
%@	
%@       otherwise
%@	error('Code for desired nonlinearity not found!');
%@      end
%@      
%@      % Normalize the new w.
%@      w = w / norm(w);
%@      i = i + 1;
%@    end
%@    round = round + 1;
%@  end
%@  if b_verbose, fprintf('Done.\n'); end
%@  
%@  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@  % Also plot the ones that may not have been plotted.
%@  if (usedDisplay > 0) & (rem(round-1, displayInterval) ~= 0)
%@    switch usedDisplay
%@     case 1
%@      % There was and may still be other displaymodes...
%@      % 1D signals
%@      temp = X'*B;
%@      icaplot('dispsig',temp(:,1:numOfIC)');
%@      drawnow;
%@     case 2
%@      % ... and now there are :-)
%@      % 1D basis
%@      icaplot('dispsig',A');
%@      drawnow;
%@     case 3
%@      % ... and now there are :-)
%@      % 1D filters
%@      icaplot('dispsig',W);
%@      drawnow;
%@     otherwise
%@    end
%@  end
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% In the end let's check the data for some security
%@if ~isreal(A)
%@  if b_verbose, fprintf('Warning: removing the imaginary part from the result.\n'); end
%@  A = real(A);
%@  W = real(W);
%@end
%@
%@
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Subfunction
%@% Calculates tanh simplier and faster than Matlab tanh.
%@function y=tanh(x)
%@y = 1 - 2 ./ (exp(2 * x) + 1);
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function Samples = getSamples(max, percentage)
%@Samples = find(rand(1, max) < percentage);
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_adv.m__ -->
%@function gui_adv(x, y)
%@%
%@% This file is needed by FASTICAG
%@
%@% This is the advanced options -dialog
%@
%@% @(#)$Id: gui_adv.m,v 1.4 2004/07/27 13:09:26 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the window
%@global hf_FastICA_AdvOpt;
%@
%@% Handles to some of the controls in window
%@global hpm_FastICA_finetune;
%@global he_FastICA_a1;
%@global he_FastICA_a2;
%@global he_FastICA_myy;
%@global he_FastICA_epsilon;
%@global he_FastICA_maxIterations;
%@global he_FastICA_maxFinetune;
%@global he_FastICA_sampleSize
%@global hpm_FastICA_initState;
%@global hb_FastICA_initGuess;
%@global ht_FastICA_initGuess;
%@global hpm_FastICA_displayMode;
%@global he_FastICA_displayInterval;
%@global hpm_FastICA_verbose;
%@
%@% Some of the main variables needed
%@global g_FastICA_initGuess;
%@global g_FastICA_finetune;
%@global g_FastICA_a1;
%@global g_FastICA_a2;
%@global g_FastICA_myy;
%@global g_FastICA_epsilon;
%@global g_FastICA_maxNumIte;
%@global g_FastICA_maxFinetune;
%@global g_FastICA_initState;
%@global g_FastICA_sampleSize;
%@global g_FastICA_displayMo;
%@global g_FastICA_displayIn;
%@global g_FastICA_verbose;
%@
%@global c_FastICA_appr_strD;
%@global c_FastICA_appr_strV;
%@global c_FastICA_finetune_strD;
%@global c_FastICA_finetune_strV;
%@global c_FastICA_iSta_strD;
%@global c_FastICA_iSta_strV;
%@global c_FastICA_dMod_strD;
%@global c_FastICA_dMod_strV;
%@global c_FastICA_verb_strD;
%@global c_FastICA_verb_strV;
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Configuration options
%@FIGURENAME = 'FastICA: advanced options';
%@FIGURETAG = 'f_FastICAAdvOpt';
%@FIGURESIZE = [x y 450 280];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Check to see if this figure is already open - it should not!
%@% Can't have more than one copy - otherwise the global
%@% variables and handles can get mixed up.
%@if ~isempty(findobj('Tag',FIGURETAG))
%@  error('Error: advanced options dialog already open!');
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Initialize some of the controls' values
%@
%@% Did we already load some initial guess
%@pm_initState_Value = g_FastICA_initState;
%@if isempty(g_FastICA_initGuess) | (g_FastICA_initGuess == 1)
%@  t_initGuess_String = 'Not loaded';
%@else
%@  t_initGuess_String = 'Loaded';
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the figure
%@a = figure('Color',[0.8 0.8 0.8], ...
%@	   'PaperType','a4letter', ...
%@	   'Name', FIGURENAME, ...
%@	   'NumberTitle', 'off', ...
%@	   'Tag', FIGURETAG, ...
%@	   'Position', FIGURESIZE, ...
%@	   'MenuBar', 'none');
%@set (a, 'Resize', 'off');
%@
%@hf_FastICA_AdvOpt = a;
%@
%@set(hf_FastICA_AdvOpt, 'HandleVisibility', 'callback');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% From here on it get's ugly as I have not had time to clean it up
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the frames
%@pos_l=2;
%@pos_w=FIGURESIZE(3)-4;
%@pos_h=FIGURESIZE(4)-4;
%@pos_t=2;
%@h_f_adv_background = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_adv_background');
%@
%@pos_w=120;
%@pos_l=FIGURESIZE(3)-(pos_w+2+2);
%@pos_h=FIGURESIZE(4)-2*4;
%@pos_t=4;
%@h_f_adv_side = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_adv_side');
%@
%@pos_l=4;
%@pos_w=FIGURESIZE(3)-8-pos_w-2;
%@pos_h=FIGURESIZE(4)-8;
%@pos_t=4;
%@h_f_advopt = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_advopt');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_advopt
%@bgc = get(h_f_advopt, 'BackgroundColor');
%@
%@pos_w1=230;
%@pos_w2=70;
%@
%@pos_frame=get(h_f_advopt, 'Position');
%@pos_h = 20;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - 6;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Fine-tune (g)', ...
%@  'Style','text', ...
%@  'Tag','t_727');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@hpm_FastICA_finetune = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',c_FastICA_finetune_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_finetune', ...
%@  'Value',g_FastICA_finetune);
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Parameter a1 (g = ''tanh'')', ...
%@  'Style','text', ...
%@  'Tag','t_22');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_a1 = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Callback','gui_advc Checka1', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_a1), ...
%@  'Style','edit', ...
%@  'Tag','e_a1');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Parameter a2 (g = ''gauss'')', ...
%@  'Style','text', ...
%@  'Tag','t_222');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_a2 = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Callback','gui_advc Checka2', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_a2), ...
%@  'Style','edit', ...
%@  'Tag','e_a2');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','mu (step size)', ...
%@  'Style','text', ...
%@  'Tag','t_223');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_myy = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Callback','gui_advc CheckMyy', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_myy), ...
%@  'Style','edit', ...
%@  'Tag','e_myy');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','epsilon (stopping criterion)', ...
%@  'Style','text', ...
%@  'Tag','t_23');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_epsilon = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_epsilon), ...
%@  'Style','edit', ...
%@  'Tag','e_epsilon');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Maximum number of iterations', ...
%@  'Style','text', ...
%@  'Tag','t_24');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_maxIterations = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_maxNumIte), ...
%@  'Style','edit', ...
%@  'Tag','e_maxIterations');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Maximum iterations in fine-tuning', ...
%@  'Style','text', ...
%@  'Tag','t_2412');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_maxFinetune = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_maxFinetune), ...
%@  'Style','edit', ...
%@  'Tag','e_maxFinetune');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Sample size (proportion)', ...
%@  'Style','text', ...
%@  'Tag','t_224');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_sampleSize = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Callback','gui_advc CheckSampleSize', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_sampleSize), ...
%@  'Style','edit', ...
%@  'Tag','e_sampleSize');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Initial state', ...
%@  'Style','text', ...
%@  'Tag','t_25');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@hpm_FastICA_initState = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',c_FastICA_iSta_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_initState', ...
%@  'Value',pm_initState_Value);
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@hb_FastICA_initGuess = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_advc loadGuess', ...
%@  'Position',[pos_l pos_t (pos_w1-60) pos_h], ...
%@  'String','Load initial guess', ...
%@  'UserData', g_FastICA_initGuess, ...
%@  'Tag','b_LoadGuess');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@ht_FastICA_initGuess = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[(pos_l) pos_t (pos_w2) pos_h], ...
%@  'String',t_initGuess_String, ...
%@  'Style','text', ...
%@  'Tag','t_initGuess');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Display mode', ...
%@  'Style','text', ...
%@  'Tag','t_27');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@hpm_FastICA_displayMode = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',c_FastICA_dMod_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_displayMode', ...
%@  'Value',g_FastICA_displayMo);
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Iterations between displays', ...
%@  'Style','text', ...
%@  'Tag','t_28');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@he_FastICA_displayInterval = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','right', ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',num2str(g_FastICA_displayIn), ...
%@  'Style','edit', ...
%@  'Tag','e_displayInterval');
%@
%@pos_t = pos_t - pos_h;
%@pos_l = pos_frame(1) + 6;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w1 pos_h], ...
%@  'String','Verbose', ...
%@  'Style','text', ...
%@  'Tag','t_29');
%@
%@pos_l = pos_frame(1) + pos_frame(3) - 6 - pos_w2;
%@hpm_FastICA_verbose = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'Position',[pos_l pos_t pos_w2 pos_h], ...
%@  'String',c_FastICA_verb_strD, ...
%@  'Style','popupmenu', ...
%@  'Tag','pm_verbose', ...
%@  'Value',g_FastICA_verbose);
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_adv_side
%@pos_vspace = 6;
%@pos_hspace = 10;
%@pos_frame = get(h_f_adv_side, 'Position');
%@pos_w = 100;
%@pos_h = 30;
%@pos_l = pos_frame(1) + pos_hspace;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_advc OK', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','OK', ...
%@  'Tag','b_advOK');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_advc Cancel', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Cancel', ...
%@  'Tag','b_advCancel');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_advc Default', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Default', ...
%@  'Tag','b_advDefault');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_advc Apply', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Apply', ...
%@  'Tag','b_advApply');
%@
%@pos_t = pos_frame(2) + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_advc Help', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Help', ...
%@  'Tag','b_advHelp');
%@
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_advc.m__ -->
%@function gui_advc (action)
%@%
%@% This file is needed by FASTICAG
%@
%@% This file holds the callbacks for advanced options -dialog
%@
%@% @(#)$Id: gui_advc.m,v 1.3 2003/09/08 11:28:58 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the window
%@global hf_FastICA_AdvOpt;
%@
%@% Handles to some of the controls in window
%@global hpm_FastICA_finetune;
%@global he_FastICA_a1;
%@global he_FastICA_a2;
%@global he_FastICA_myy;
%@global he_FastICA_epsilon;
%@global he_FastICA_maxIterations;
%@global he_FastICA_maxFinetune;
%@global he_FastICA_sampleSize;
%@global hpm_FastICA_initState;
%@global hb_FastICA_initGuess;
%@global ht_FastICA_initGuess;
%@global hpm_FastICA_displayMode;
%@global he_FastICA_displayInterval;
%@global hpm_FastICA_verbose;
%@
%@% Needed handles to the main window
%@global hf_FastICA_MAIN;
%@global ht_FastICA_icaStatus;
%@global ht_FastICA_numOfSamp;
%@global hpm_FastICA_stabilization;
%@
%@% Some of the main variables needed
%@global g_FastICA_initGuess;
%@global g_FastICA_numOfIC;
%@global g_FastICA_finetune;
%@global g_FastICA_a1;
%@global g_FastICA_a2;
%@global g_FastICA_myy;
%@global g_FastICA_epsilon;
%@global g_FastICA_maxNumIte;
%@global g_FastICA_maxFinetune;
%@global g_FastICA_initState;
%@global g_FastICA_sampleSize;
%@global g_FastICA_displayMo;
%@global g_FastICA_displayIn;
%@global g_FastICA_verbose;
%@
%@global c_FastICA_iSta_strV;
%@
%@% What is the load type of load dialog
%@global g_FastICA_loadType;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% This should not take long...
%@watchonInFigure = watchon;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@switch action
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Checka1'
%@
%@ e_a1_val = str2num(get(he_FastICA_a1, 'String'));
%@ if e_a1_val <= 0
%@   set(he_FastICA_a1, 'String', '0.1');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Checka2'
%@  
%@ e_a2_val = str2num(get(he_FastICA_a2, 'String'));
%@ if e_a2_val <= 0
%@   set(he_FastICA_a2, 'String', '0.1');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'CheckMyy'
%@
%@ e_myy_val = str2num(get(he_FastICA_myy, 'String'));
%@ if e_myy_val <= 0
%@   set(he_FastICA_myy, 'String', '0.1');
%@ elseif e_myy_val > 1
%@   set(he_FastICA_myy, 'String', '1');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'CheckSampleSize'
%@  
%@ e_sampleSize_val = str2num(get(he_FastICA_sampleSize, 'String'));
%@ if e_sampleSize_val > 1
%@   set(he_FastICA_sampleSize, 'String', '1');
%@ else 
%@   numOfSamp = str2num(get(ht_FastICA_numOfSamp, 'String'));
%@   if numOfSamp < 1000
%@     set(he_FastICA_sampleSize, 'String', '1');
%@     fprintf('Can''t reduce sample size. Already less than 1000 samples.\n');
%@   elseif (e_sampleSize_val * numOfSamp) < 1000
%@     fprintf('Can''t reduce sample size to less than 1000 samples.\n');
%@     set(he_FastICA_sampleSize, 'String', sprintf('%0.3f',1000/numOfSamp));
%@   end
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'loadGuess'
%@ 
%@ handle = findobj('Tag','f_FastICALoad');  % Check if the window is already
%@ if isempty(handle)                        % open. If not then open it.
%@   pos = get(hf_FastICA_MAIN, 'Position');
%@   gui_l(pos(1), pos(2));
%@ else
%@   if strcmp(g_FastICA_loadType, 'guess')  % Check if it was the same load
%@     figure(handle);                       % window. If it wasn't then
%@   else                                    % close the other window first
%@     close(handle);                        % and then open the load window
%@     fprintf('''Load data'' -dialog closed!\n');
%@     pos = get(hf_FastICA_MAIN, 'Position');
%@     gui_l(pos(1), pos(2));
%@   end
%@ end
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'OK'
%@  
%@ gui_advc Apply;
%@
%@ close(hf_FastICA_AdvOpt);
%@
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Apply'
%@
%@ newValues = 0;
%@
%@ val = g_FastICA_finetune;
%@ g_FastICA_finetune = get(hpm_FastICA_finetune, 'Value');
%@ if (g_FastICA_finetune ~= val)
%@   newValues = 1;
%@ end
%@ 
%@ val = g_FastICA_a1;
%@ g_FastICA_a1 = str2num(get(he_FastICA_a1, 'String'));
%@ if (g_FastICA_a1 ~= val)
%@   newValues = 1;
%@ end
%@
%@ val = g_FastICA_a2;
%@ g_FastICA_a2 = str2num(get(he_FastICA_a2, 'String'));
%@ if (g_FastICA_a2 ~= val)
%@   newValues = 1;
%@ end
%@
%@ val = g_FastICA_myy;
%@ g_FastICA_myy = str2num(get(he_FastICA_myy, 'String'));
%@ if (g_FastICA_myy ~= val)
%@   newValues = 1;
%@ end
%@
%@ % If myy < 1 then will use stabilazed code, and we don't care 
%@ % about the parameter stabilization :-)
%@ if (g_FastICA_myy == 1)
%@   set(hpm_FastICA_stabilization, 'Enable', 'on');
%@ else
%@   set(hpm_FastICA_stabilization, 'Enable', 'off');
%@ end
%@
%@ val = g_FastICA_epsilon;
%@ g_FastICA_epsilon = str2num(get(he_FastICA_epsilon, 'String'));
%@ if (g_FastICA_epsilon ~= val)
%@   newValues = 1;
%@ end
%@
%@ val = g_FastICA_maxNumIte;
%@ g_FastICA_maxNumIte = str2num(get(he_FastICA_maxIterations, 'String'));
%@ if (g_FastICA_maxNumIte ~= val)
%@   newValues = 1;
%@ end
%@ 
%@ val = g_FastICA_maxFinetune;
%@ g_FastICA_maxFinetune = str2num(get(he_FastICA_maxFinetune, 'String'));
%@ if (g_FastICA_maxFinetune ~= val)
%@   newValues = 1;
%@ end
%@ 
%@ val = g_FastICA_sampleSize;
%@ g_FastICA_sampleSize = str2num(get(he_FastICA_sampleSize, 'String'));
%@ if (g_FastICA_sampleSize ~= val)
%@   newValues = 1;
%@ end
%@
%@ val = g_FastICA_initState;
%@ g_FastICA_initState = get(hpm_FastICA_initState, 'Value');
%@ if (g_FastICA_initState ~= val)
%@   newValues = 1;
%@ end
%@
%@ val = g_FastICA_initGuess;
%@ g_FastICA_initGuess = get(hb_FastICA_initGuess, 'UserData');
%@ if min(size(val) == size(g_FastICA_initGuess)) == 0
%@   newValues = 1;
%@ else
%@   if (g_FastICA_initGuess ~= val)
%@     newValues = 1;
%@   end
%@ end
%@ 
%@ g_FastICA_displayMo = get(hpm_FastICA_displayMode, 'Value');
%@ g_FastICA_displayIn = str2num(get(he_FastICA_displayInterval, 'String'));
%@ g_FastICA_verbose = get(hpm_FastICA_verbose, 'Value');
%@ 
%@ if newValues == 1
%@   gui_cb NullICA;
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Cancel'
%@  
%@ close(hf_FastICA_AdvOpt);
%@
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Default'
%@  
%@ % set default values to controls
%@ set(hpm_FastICA_finetune, 'Value',5);
%@ set(he_FastICA_a1, 'String','1');
%@ set(he_FastICA_a2, 'String','1');
%@ set(he_FastICA_myy, 'String','1');
%@ set(he_FastICA_epsilon, 'String','0.0001');
%@ set(he_FastICA_maxIterations, 'String','1000');
%@ set(he_FastICA_sampleSize, 'String','1');
%@ set(hpm_FastICA_initState, 'Value',1);
%@ set(hpm_FastICA_displayMode, 'Value',1);
%@ set(he_FastICA_displayInterval, 'String','1');
%@ set(hpm_FastICA_verbose, 'Value',1);
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Help'
%@
%@ gui_help('gui_advc');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@end    % switch
%@
%@watchoff (watchonInFigure);
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_cb.m__ -->
%@function gui_cb(action)
%@%
%@% This file is used by FASTICAG
%@
%@% This file holds the callbacks to the main window
%@
%@% @(#)$Id: gui_cb.m,v 1.5 2003/09/10 10:33:41 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the main figure
%@global hf_FastICA_MAIN;
%@
%@% Handles for needed controls in main figure;
%@global ht_FastICA_mixedStatus;
%@global ht_FastICA_dim;
%@global ht_FastICA_numOfSamp;
%@global ht_FastICA_newDim;
%@global ht_FastICA_whiteStatus;
%@global ht_FastICA_icaStatus;
%@global hpm_FastICA_approach;
%@global he_FastICA_numOfIC;
%@global hpm_FastICA_g;
%@global hpm_FastICA_stabilization;
%@
%@% Main values are stored here
%@global g_FastICA_mixedsig;
%@global g_FastICA_mixedmean;
%@global g_FastICA_pca_D;
%@global g_FastICA_pca_E;
%@global g_FastICA_white_sig;
%@global g_FastICA_white_wm;
%@global g_FastICA_white_dwm;
%@global g_FastICA_ica_sig;
%@global g_FastICA_ica_A;
%@global g_FastICA_ica_W;
%@global g_FastICA_initGuess;
%@global g_FastICA_approach;
%@global g_FastICA_numOfIC;
%@global g_FastICA_g;
%@global g_FastICA_finetune;
%@global g_FastICA_a1;
%@global g_FastICA_a2;
%@global g_FastICA_myy;
%@global g_FastICA_stabilization;
%@global g_FastICA_epsilon;
%@global g_FastICA_maxNumIte;
%@global g_FastICA_maxFinetune;
%@global g_FastICA_sampleSize;
%@global g_FastICA_initState;
%@global g_FastICA_displayMo;
%@global g_FastICA_displayIn;
%@global g_FastICA_verbose;
%@
%@% String values are here
%@global c_FastICA_appr_strV;
%@global c_FastICA_g1_strD;
%@global c_FastICA_g1_strV;
%@global c_FastICA_g2_strD;
%@global c_FastICA_g2_strV;
%@global c_FastICA_finetune_strD;
%@global c_FastICA_finetune_strV;
%@global c_FastICA_stabili_strV;
%@global c_FastICA_iSta_strV;
%@global c_FastICA_dMod_strV;
%@global c_FastICA_verb_strV;
%@
%@% What is the load type of load dialog
%@global g_FastICA_loadType;
%@
%@% Global variable for stopping the ICA calculations
%@global g_FastICA_interrupt;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% What ever we do, it will take some time... not much, but some :-)
%@watchonInFigure = watchon;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@switch action
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'InitAll'
%@
%@ % If the data is already loaded, then get the information from data
%@ % and show to the user (also set g_FastICA_numOfIC)
%@ if ~isempty(g_FastICA_mixedsig)
%@   set(ht_FastICA_mixedStatus, 'String', '');
%@   [dim, numofsamp] = size(g_FastICA_mixedsig);
%@   set(ht_FastICA_dim, 'String', int2str(dim));
%@   set(ht_FastICA_numOfSamp, 'String', int2str(numofsamp));
%@   set(ht_FastICA_newDim, 'String', int2str(dim));
%@   set(he_FastICA_numOfIC, 'String', int2str(dim));
%@   g_FastICA_numOfIC = dim;
%@   g_FastICA_mixedmean = [];
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'LoadData'
%@
%@ handle = findobj('Tag','f_FastICALoad');  % Check if the window is already
%@ if isempty(handle)                        % open. If not then open it.
%@   pos = get(hf_FastICA_MAIN, 'Position');
%@   % Based on the feedback obtained from some users, it seems
%@   % that at least in some systems, pos can sometimes be empty. A
%@   % similar check is done a few lines below.
%@   if ~isempty (pos),
%@     gui_l(pos(1), pos(2));
%@   else
%@     gui_l (0, 0);
%@   end
%@ else
%@   if strcmp(g_FastICA_loadType, 'data')   % Check if it was the same load
%@     figure(handle);                       % window. If it wasn't then
%@   else                                    % close the other window first
%@     close(handle);                        % and then open the load window
%@     fprintf('''Load initial guess'' -dialog closed!\n');
%@     pos = get(hf_FastICA_MAIN, 'Position');
%@     if ~isempty (pos),
%@       gui_l(pos(1), pos(2));
%@     else
%@       gui_l (0, 0);
%@     end
%@   end
%@ end
%@ 
%@ % gui_cb NewData; - is called from the load function if not canceled...
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'NewData'
%@
%@ % New data is loaded or the old data changed. We need to find out
%@ % somethings about the new data... and do some other stuff also...
%@ [dim, numofsamp] = size(g_FastICA_mixedsig);
%@ set(ht_FastICA_dim, 'String', dim);
%@ set(ht_FastICA_newDim, 'String', dim);
%@ set(ht_FastICA_numOfSamp, 'String', numofsamp);
%@ set(he_FastICA_numOfIC, 'String', int2str(dim));
%@ 
%@ g_FastICA_numOfIC = dim;    % Default for numOfIC = the new dimension
%@			     % PCA needs to be calculated again.
%@ g_FastICA_pca_E = [];       % We use this to check if PCA is calculated
%@ gui_cb NullWhite;           % Whitening needs to be done again also
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'NullWhite'
%@
%@ % Whitening needs to done again next time it's needed
%@ g_FastICA_white_sig = [];   % We use this to check if whitening is calculated
%@ gui_cb NullICA;             % The FPICA must be calculated again
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'NullICA'
%@
%@ % If IC's are needed they have to bee calculated again
%@ g_FastICA_ica_sig = [];     % We use this to check if FPICA is calculated
%@ set(ht_FastICA_icaStatus,'String','Not yet done');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Transpose'
%@
%@ if isempty(g_FastICA_mixedmean)
%@   g_FastICA_mixedsig = g_FastICA_mixedsig';
%@ else
%@   g_FastICA_mixedsig = (g_FastICA_mixedsig + ...
%@			 g_FastICA_mixedmean * ...
%@			 ones(1,size(g_FastICA_mixedsig, 2)))';
%@   g_FastICA_mixedmean = [];
%@ end
%@ gui_cb NewData;             % Data has been changed
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'DoPCA'
%@
%@ if ~isempty(g_FastICA_mixedsig)
%@   % We'll remove mean of the data here also just in case...
%@   if isempty(g_FastICA_mixedmean)
%@     [g_FastICA_mixedsig, g_FastICA_mixedmean] = remmean(g_FastICA_mixedsig);
%@   end
%@   
%@   % Do PCA interactively: ask the user for eigenvalues
%@   [g_FastICA_pca_E, g_FastICA_pca_D] = pcamat(g_FastICA_mixedsig, ...
%@					       0, 0, 'gui', ...
%@					       deblank(c_FastICA_verb_strV(g_FastICA_verbose,:)));
%@   
%@   newdim = size(g_FastICA_pca_D, 1);
%@   set(ht_FastICA_newDim, 'String', int2str(newdim));
%@   set(he_FastICA_numOfIC, 'String', int2str(newdim));
%@   g_FastICA_numOfIC = newdim;
%@   gui_cb NullWhite;           % Whitening needs to be done again also
%@			       % but we'll do it when it's needed.
%@ else
%@   fprintf('Data not loaded yet!\n\n');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'OrigDim'
%@
%@ gui_cb NewData;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ShowMixed'
%@
%@ if ~isempty(g_FastICA_mixedsig)
%@   handle = findobj('Tag','f_FastICA_mix');  % Check if the window is already
%@   if isempty(handle)                        % open. If not then open it.
%@     figure('Tag', 'f_FastICA_mix', ...
%@	    'Name', 'FastICA: Plot data', ...
%@	    'NumberTitle', 'off');
%@   else
%@     figure(handle);
%@     clf;		% clear the figure for next plots
%@   end
%@   if isempty(g_FastICA_mixedmean)
%@     icaplot('dispsig',g_FastICA_mixedsig, 0, 0, 0, 'Mixed signals');
%@   else
%@     icaplot('dispsig',g_FastICA_mixedsig + g_FastICA_mixedmean * ...
%@	     ones(1, size(g_FastICA_mixedsig, 2)), 0, 0, 0, 'Mixed signals');
%@   end
%@ else
%@   fprintf('Data not loaded yet!\n\n');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ShowWhite'
%@
%@ if ~isempty(g_FastICA_mixedsig)
%@   if isempty(g_FastICA_white_sig)     % if whitening is not done, we need to
%@     gui_cb Whiten;                    % do it before we can display the
%@   end                                 % whitened signals
%@   
%@   handle = findobj('Tag','f_FastICA_white');  % Check if the window is already
%@   if isempty(handle)                          % open. If not then open it.
%@     figure('Tag', 'f_FastICA_white', ...
%@	    'Name', 'FastICA: Plot whitened', ...
%@	    'NumberTitle', 'off');
%@   else
%@     figure(handle);
%@     clf;		% clear the figure for next plots
%@   end
%@   icaplot('dispsig',g_FastICA_white_sig,0,0,0,'Whitened signals');
%@ else
%@   fprintf('Data not loaded yet!\n\n');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Whiten'
%@
%@ set(ht_FastICA_whiteStatus,'String','Computing...');
%@ 
%@ % If PCA is not calculated, we'll have to calculate it now,
%@ % we'll do it without guestions - we don't reduce the dimension
%@ % here - but PCAMAT might reduce the dimension automatically.
%@ if isempty(g_FastICA_pca_E)
%@   % We'll remove mean of the data here also just in case...
%@   if isempty(g_FastICA_mixedmean)
%@     [g_FastICA_mixedsig, g_FastICA_mixedmean] = remmean(g_FastICA_mixedsig);
%@   end
%@   
%@   [g_FastICA_pca_E, g_FastICA_pca_D] = pcamat(g_FastICA_mixedsig, 1, ...
%@					       size(g_FastICA_mixedsig, ...
%@						    1), 'off', ...
%@					       deblank(c_FastICA_verb_strV(g_FastICA_verbose,:)));
%@   
%@   % Check if the dimension was reduced automatically
%@   newdim = size(g_FastICA_pca_D, 1);
%@   set(ht_FastICA_newDim, 'String', int2str(newdim));
%@   % Check if the numOfIC now has illegal value entered 
%@   % We do that by telling the program that there is new value 
%@   % entered for NumOfIC.
%@   gui_cb ChangeNumOfIC;
%@ end
%@ 
%@ % And now we can calculate whitening...
%@ [g_FastICA_white_sig, g_FastICA_white_wm, g_FastICA_white_dwm] = ...
%@								  whitenv(g_FastICA_mixedsig, g_FastICA_pca_E, g_FastICA_pca_D, deblank(c_FastICA_verb_strV(g_FastICA_verbose,:)));
%@ 
%@ set (ht_FastICA_whiteStatus,'String','');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ChangeApproach'
%@
%@ % Get the old value for g
%@ eval(['g_str = c_FastICA_g' int2str(g_FastICA_approach) '_strV;']);
%@ old_g = deblank(g_str(g_FastICA_g,:));
%@ 
%@ % Get and set the new value for approach
%@ g_FastICA_approach = get(hpm_FastICA_approach, 'Value');
%@ 
%@ % The possible values for g depend on the value of approach...
%@ eval(['g_str = c_FastICA_g' int2str(g_FastICA_approach) '_strD;']);
%@ set(hpm_FastICA_g, 'String', g_str);
%@ 
%@ % Match the old g value from the new g values so that if the 
%@ % old_g can be found from the new values (anywhere), then set new g
%@ % to that value, and if it's not found then set the new value to 1.
%@ match = 0;
%@ eval(['g_str = c_FastICA_g' int2str(g_FastICA_approach) '_strV;']);
%@ for i=1:size(g_str,1)
%@   if strcmp(old_g, deblank(g_str(i,:)))
%@     match = i;
%@   end
%@ end
%@ if match == 0
%@   match = 1;   % the old g is not availabe anymore, set g = 1.
%@ end
%@ g_FastICA_g = match;
%@ set(hpm_FastICA_g, 'Value', match);
%@ 
%@ gui_cb NullICA;      % The options are changed so we must calculate ICA again
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ChangeNumOfIC'
%@
%@ % Get the new value... and store it later on after some checks
%@ numofic = str2num(get(he_FastICA_numOfIC, 'String'));
%@ 
%@ % The number of IC can't be less than 1 or more than the reduced dimension.
%@ numoficmax = str2num(get(ht_FastICA_newDim, 'String'));
%@ if numofic < 1
%@   set(he_FastICA_numOfIC, 'String', '1');
%@   g_FastICA_numOfIC = 1;
%@ elseif numofic > numoficmax
%@   set(he_FastICA_numOfIC, 'String', int2str (numoficmax));
%@   g_FastICA_numOfIC = numoficmax;
%@ else
%@   g_FastICA_numOfIC = numofic;
%@ end
%@ 
%@ gui_cb NullICA;      % The options are changed so we must calculate ICA again
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ChangeG'
%@
%@ % Get the new value for g.
%@ g_FastICA_g = get(hpm_FastICA_g, 'Value');
%@ 
%@ gui_cb NullICA;      % The options are changed so we must calculate ICA again
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ChangeStab'
%@
%@ % Get the new value for g.
%@ g_FastICA_stabilization = get(hpm_FastICA_stabilization, 'Value');
%@ 
%@ gui_cb NullICA;      % The options are changed so we must calculate ICA again
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'AdvOpt'
%@
%@ handle = findobj('Tag','f_FastICAAdvOpt');
%@ if isempty(handle)                        % Check to see if the window is
%@   pos = get(hf_FastICA_MAIN, 'Position');     % already open...
%@   if ~isempty (pos),
%@     gui_adv(pos(1), pos(2));
%@   else
%@     gui_adv(0, 0);
%@   end
%@ else
%@   figure(handle)
%@ end
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'ShowICASig'
%@
%@ if ~isempty(g_FastICA_mixedsig)
%@   % If the IC's are not already calculated, we'll do it now
%@   if isempty(g_FastICA_ica_sig)
%@     gui_cb DoFPICA;
%@   end
%@   
%@   % The signals may have been already displaued by the FPICA function
%@   % BUT the FPICA may also have shown either the basis of the filters
%@   % so the signals still need to be shown - besides the mean was added
%@   % in only later after FPICA
%@   
%@   % Also notice that in this version if there was something wrong in FPICA
%@   % Then the results are []. - We don't try to plot them!
%@   if ~isempty(g_FastICA_ica_sig')
%@     handle = findobj('Tag','f_FastICA_ica');  % Check if the window is already
%@     if isempty(handle)                        % open. If not then open it.
%@       figure('Tag', 'f_FastICA_ica', ...
%@	      'Name', 'FastICA: Plot ICs', ...
%@	      'NumberTitle', 'off');
%@     else
%@       figure(handle);
%@       clf;		% clear the figure for next plots
%@     end
%@     
%@     icaplot('dispsig', g_FastICA_ica_sig, 0, ...
%@	     0, 0, 'Independent components');
%@   end
%@ else
%@   fprintf('Data not loaded yet!\n\n');
%@ end
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'DoFPICA'
%@
%@ gui_cb DisableButtons;
%@ g_FastICA_interrupt = 0;
%@ 
%@ if ~isempty(g_FastICA_mixedsig)
%@   if isempty(g_FastICA_white_sig)     % We need the whitened signal here
%@     gui_cb Whiten;
%@   end
%@   
%@   set(ht_FastICA_icaStatus,'String','Computing...');
%@   
%@   % The possible values for g depend on approach
%@   eval(['g_str = c_FastICA_g' int2str(g_FastICA_approach) '_strV;']);
%@   
%@   % We'll contruct a command string which we'll later on evaluate...
%@   % This is where the Fixed point algorithm is used.
%@   command_str = ['[g_FastICA_ica_A,g_FastICA_ica_W]=' ...
%@		  'fpica(g_FastICA_white_sig,' ... 
%@		  'g_FastICA_white_wm,' ... 
%@		  'g_FastICA_white_dwm,' ...
%@		  '''' deblank(c_FastICA_appr_strV(g_FastICA_approach,:)) ...
%@		  ''',' ...
%@		  'g_FastICA_numOfIC,' ...
%@		  '''' deblank(g_str(g_FastICA_g,:)) ''',' ...
%@		  '''' ...
%@		  deblank(c_FastICA_finetune_strV(g_FastICA_finetune,:)) ...
%@		  ''',' ...
%@		  'g_FastICA_a1,' ...
%@		  'g_FastICA_a2,' ...
%@		  'g_FastICA_myy,' ...
%@		  '''' ...
%@		  deblank(c_FastICA_stabili_strV(g_FastICA_stabilization,:)) ...
%@		  ''',' ...
%@		  'g_FastICA_epsilon,' ...
%@		  'g_FastICA_maxNumIte,' ...
%@		  'g_FastICA_maxFinetune,' ...
%@		  '''' deblank(c_FastICA_iSta_strV(g_FastICA_initState,:)) ...
%@		  ''',' ...
%@		  'g_FastICA_initGuess,' ...
%@		  'g_FastICA_sampleSize,' ...
%@		  '''' deblank(c_FastICA_dMod_strV(g_FastICA_displayMo,:)) ...
%@		  ''',' ...
%@		  'g_FastICA_displayIn,' ...
%@		  '''' deblank(c_FastICA_verb_strV(g_FastICA_verbose,:)) ...
%@		  ''');'];
%@   
%@
%@   % If the user wants to plot while computing...
%@   % let's at least plot it to the right figure then
%@   if ~strcmp(deblank(c_FastICA_dMod_strV(g_FastICA_displayMo,:)),'off')
%@     handle = findobj('Tag','f_FastICA_ica');  % Check if the window is already
%@     if isempty(handle)                        % open. If not then open it.
%@       figure('Tag', 'f_FastICA_ica', ...
%@	      'Name', 'FastICA: Plot ICs', ...
%@	      'NumberTitle', 'off');
%@     else
%@       figure(handle);
%@       clf;		% clear the figure for next plots
%@     end
%@   end
%@   
%@   % ... and so let's do it...
%@   eval(command_str);
%@   
%@   % Also notice that in this version if there was something wrong in FPICA
%@   % Then the results are [].
%@   if ~isempty(g_FastICA_ica_W)
%@     % Add the mean back in.
%@     g_FastICA_ica_sig = g_FastICA_ica_W * g_FastICA_mixedsig ...
%@			 + (g_FastICA_ica_W * g_FastICA_mixedmean) ...
%@			 * ones(1,size(g_FastICA_mixedsig, 2));
%@     set (ht_FastICA_icaStatus,'String','Done');
%@   else
%@     gui_cb NullICA;  % set icasig=[] and do what ever needs to be done then
%@   end
%@   
%@   if ~(g_FastICA_interrupt)
%@     gui_cb EnableButtons;
%@   end
%@ else
%@   fprintf('Data not loaded yet!\n\n');
%@ end
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Interrupt'
%@ g_FastICA_interrupt = 1;
%@ set(ht_FastICA_icaStatus,'String','Interrupted');
%@ gui_cb EnableButtons;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'DisableButtons'
%@ set(findobj('Tag','b_Transpose'),'Enable','off');
%@ set(findobj('Tag','b_ShowMixed'),'Enable','off');
%@ set(findobj('Tag','b_DoPCA'),'Enable','off');
%@ set(findobj('Tag','b_OrigDim'),'Enable','off');
%@ set(findobj('Tag','b_ShowWhite'),'Enable','off');
%@ set(findobj('Tag','b_advOpt'),'Enable','off');
%@ set(findobj('Tag','b_ShowICASig'),'Enable','off');
%@ set(findobj('Tag','b_LoadData'),'Enable','off');
%@ set(findobj('Tag','b_DoFPICA'),'Enable','off');
%@ set(findobj('Tag','b_SaveData'),'Enable','off');
%@ set(findobj('Tag','b_Quit'),'Enable','off');
%@ set(findobj('Tag','b_Interrupt'),'Visible','on');
%@ drawnow;
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'EnableButtons'
%@ set(findobj('Tag','b_Transpose'),'Enable','on');
%@ set(findobj('Tag','b_ShowMixed'),'Enable','on');
%@ set(findobj('Tag','b_DoPCA'),'Enable','on');
%@ set(findobj('Tag','b_OrigDim'),'Enable','on');
%@ set(findobj('Tag','b_ShowWhite'),'Enable','on');
%@ set(findobj('Tag','b_advOpt'),'Enable','on');
%@ set(findobj('Tag','b_ShowICASig'),'Enable','on');
%@ set(findobj('Tag','b_LoadData'),'Enable','on');
%@ set(findobj('Tag','b_DoFPICA'),'Enable','on');
%@ set(findobj('Tag','b_SaveData'),'Enable','on');
%@ set(findobj('Tag','b_Quit'),'Enable','on');
%@ set(findobj('Tag','b_Interrupt'),'Visible','off');
%@ drawnow;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'SaveData'
%@
%@ handle = findobj('Tag','f_FastICASave');  % Check if the window is already
%@ if isempty(handle)                        % open. If not then open it.
%@   pos = get(hf_FastICA_MAIN, 'Position');
%@   if ~isempty (pos),
%@     gui_s(pos(1), pos(2));
%@   else
%@     gui_s(0, 0);
%@   end
%@ else
%@   figure(handle);                       % window. If it wasn't then
%@ end
%@ 
%@ 
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Quit'
%@
%@ % We'll close the other dialogs if they are open.
%@ Tags = ['f_FastICALoad  '
%@	 'f_FastICAAdvOpt'
%@	 'f_FastICASave  '
%@	 'f_FastICA_mix  '
%@	 'f_FastICA_white'
%@	 'f_FastICA_ica  '];
%@ for i=1:size(Tags,1)
%@   handle = findobj('Tag', deblank(Tags(i,:)));
%@   if ~isempty(handle)
%@     close(handle);
%@   end
%@ end
%@
%@ % Close this window
%@ close(hf_FastICA_MAIN);
%@ 
%@ % Clear the used global variables.
%@ gui_cg;
%@
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@ % ... and we're done.
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'About'
%@
%@ gui_help('gui_cb_about');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Help'
%@
%@ gui_help('gui_cb_help');
%@  
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@
%@end    % switch
%@
%@watchoff (watchonInFigure);
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_cg.m__ -->
%@function gui_cg()
%@%
%@% This function is needed by FASTICAG
%@
%@% This file just removes the global variables
%@% that are used in FASTICAG from the memory
%@
%@% @(#)$Id: gui_cg.m,v 1.2 2003/04/05 14:23:57 jarmo Exp $
%@
%@clear global c_FastICA_appr_strD;
%@clear global c_FastICA_appr_strV;
%@clear global c_FastICA_dMod_strD;
%@clear global c_FastICA_dMod_strV;
%@clear global c_FastICA_finetune_strD;
%@clear global c_FastICA_finetune_strV;
%@clear global c_FastICA_g1_strD;
%@clear global c_FastICA_g1_strV;
%@clear global c_FastICA_g2_strD;
%@clear global c_FastICA_g2_strV;
%@clear global c_FastICA_iSta_strD;
%@clear global c_FastICA_iSta_strV;
%@clear global c_FastICA_stabili_strD;
%@clear global c_FastICA_stabili_strV;
%@clear global c_FastICA_verb_strD;
%@clear global c_FastICA_verb_strV;
%@clear global g_FastICA_a1;
%@clear global g_FastICA_a2;
%@clear global g_FastICA_approach;
%@clear global g_FastICA_displayIn;
%@clear global g_FastICA_displayMo;
%@clear global g_FastICA_epsilon;
%@clear global g_FastICA_finetune;
%@clear global g_FastICA_g;
%@clear global g_FastICA_ica_A;
%@clear global g_FastICA_ica_W;
%@clear global g_FastICA_ica_sig;
%@clear global g_FastICA_initGuess;
%@clear global g_FastICA_initState;
%@clear global g_FastICA_interrupt;
%@clear global g_FastICA_loadType;
%@clear global g_FastICA_maxFinetune;
%@clear global g_FastICA_maxNumIte;
%@clear global g_FastICA_mixedmean;
%@clear global g_FastICA_mixedsig;
%@clear global g_FastICA_myy;
%@clear global g_FastICA_numOfIC;
%@clear global g_FastICA_pca_D;
%@clear global g_FastICA_pca_E;
%@clear global g_FastICA_sampleSize;
%@clear global g_FastICA_stabilization;
%@clear global g_FastICA_verbose;
%@clear global g_FastICA_white_dwm;
%@clear global g_FastICA_white_sig;
%@clear global g_FastICA_white_wm;
%@clear global hb_FastICA_initGuess;
%@clear global he_FastICA_a1;
%@clear global he_FastICA_a2;
%@clear global he_FastICA_displayInterval;
%@clear global he_FastICA_epsilon;
%@clear global he_FastICA_file;
%@clear global he_FastICA_suffix;
%@clear global he_FastICA_maxFinetune;
%@clear global he_FastICA_maxIterations;
%@clear global he_FastICA_myy;
%@clear global he_FastICA_numOfIC;
%@clear global he_FastICA_sampleSize;
%@clear global hf_FastICA_MAIN;
%@clear global hf_FastICA_AdvOpt;
%@clear global hf_FastICA_Load;
%@clear global hf_FastICA_Save;
%@clear global hpm_FastICA_approach;
%@clear global hpm_FastICA_displayMode;
%@clear global hpm_FastICA_finetune;
%@clear global hpm_FastICA_g;
%@clear global hpm_FastICA_initState;
%@clear global hpm_FastICA_stabilization;
%@clear global hpm_FastICA_verbose;
%@clear global ht_FastICA_dim;
%@clear global ht_FastICA_icaStatus;
%@clear global ht_FastICA_initGuess;
%@clear global ht_FastICA_mixedStatus;
%@clear global ht_FastICA_newDim;
%@clear global ht_FastICA_numOfSamp;
%@clear global ht_FastICA_whiteStatus;
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_help.m__ -->
%@function gui_help(which_help)
%@%
%@% Used by FASTICAG
%@
%@% All the help texts and title used by GUI are stored here. 
%@% Make changes here.
%@% Also displays the helpwindow with the selected text
%@
%@% @(#)$Id: gui_help.m,v 1.4 2004/07/27 11:46:47 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@switch which_help
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'pcamat'
%@
%@  helptitle = 'FastICA: Reduce dimension';
%@  helptext=[ ...
%@    'You may reduce the dimension of the data by selecting only the     '
%@    'subspace corresponding to certain eigenvalues of the covariance    '
%@    'matrix of the data. Give the indices of the first and last         '
%@    'eigenvalues (sorted in descending order) to be included (all       '
%@    'eigenvalues in between will be included as well).  The eigenvalues '
%@    'and their indices can be seen in the graphical plot now on the     '
%@    'screen. The heights of the bars give the eigenvalues, with indices '
%@    'below.                                                             '
%@    '                                                                   '
%@    'For example, give ''1'' and ''n'' if you want to reduce the dimension  '
%@    'to n by principal component analysis, which means discarding the   '
%@    'subspaces corresponding to the smallest eigenvalues. Such a        '
%@    'dimension reduction may reduce noise and improve the performance of'
%@    'ICA.                                                               '];
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'gui_cb_about'
%@
%@  helptitle='About FastICA';
%@  helptext =[ ...
%@    'FastICA for Matlab 6.x                                                    '
%@    'Version 2.3, July 27 2004                                              '
%@    'Copyright (c) Jarmo Hurri, Hugo Gävert, Jaakko Särelä, and Aapo Hyvärinen.'
%@    '                                                                          '
%@    'For more information please see:                                          '
%@    'http://www.cis.hut.fi/projects/ica/fastica/                               '];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'gui_cb_help'
%@
%@  helptitle='FastICA GUI';
%@  helptext = [...
%@    'Basic function:                                                            '
%@    '                                                                           '
%@    '- Click LOAD DATA and give the name of the variable that contains          '
%@    '  the data.                                                                '
%@    '                                                                           '
%@    '- Click DO ICA to perform the analysis.                                    '
%@    '                                                                           '
%@    '- Click SAVE RESULTS to store the results for future use.                  '
%@    '                                                                           '
%@    'Options:                                                                   '
%@    '                                                                           '
%@    'If the input matrix contains the signals as column vectors instead of      '
%@    'row vectors, click on TRANSPOSE to transpose the data matrix.              '
%@    '                                                                           '
%@    'Click on PLOT DATA to see the data as 1-D time signals.                    '
%@    '                                                                           '
%@    'Clicking REDUCE DIM gives you a graphical plot of the eigenvalue           '
%@    'structure of the covariance matrix of the data. You can then reduce        '
%@    'the dimension of the data by retaining only the subspaces corresponding to '
%@    'the largest (or smallest) eigenvalues (i.e. variances). To undo this       '
%@    'operation click ORIGINAL DIM. You can plot the whitened (preprocessed      '
%@    'data) by PLOT WHITENED.                                                    '
%@    '                                                                           '
%@    'Click on DO ICA to perform independent component analysis.                 '
%@    'Clicking on PLOT ICS has the same effect, except that DO ICA forces        '
%@    'recomputation of ICA.                                                      '
%@    '                                                                           '
%@    'You can choose the decorrelation approach by the ''Approach'' drop-down menu:'
%@    'deflation means that the independent components are estimated              '
%@    'one-by-one, whereas in the symmetric approach they are estimated in        '
%@    'parallel. You can now choose the number of independent components to be    '
%@    'estimated in both deflation and symmetric approaches.                      '
%@    '                                                                           '
%@    'You have a choice of three nonlinearities:                                 '
%@    '                                                                           '
%@    '''pow3'' (default) :  g(u)=u^3                                               '
%@    '''tanh''           :  g(u)=tanh(u)                                           '
%@    '''gauss''          :  g(u)=u*exp(-u^2/2)                                     '
%@    '''skew''           :  g(u)=u^2                                               '
%@    '                                                                           '
%@    'For example, you could choose approach=''symmetric'' and nonlinearity=''tanh'' '
%@    'to perform maximum likelihood ICA estimation for supergaussian data.       '
%@    '                                                                           '
%@    'If the algorithm does not seem to converge, you can use the stabilized     '
%@    'version of the fixed-point algorithm. To use the stabilized version,       '
%@    'choose ''on'' from the drop-down menu ''Stabilization''.                       '
%@    'If you have specified a value less than 1 for the parameter ''mu'' from      '
%@    'the ''Advanced Options'' menu then the ''Stabilization'' drop-down menu is     '
%@    'not active. This is because if the parameter ''mu'' is less than 1 then the  '
%@    'program will use the stabilized code. Please see the help for              '
%@    'Advanced Options for more information about stabilization.                 '
%@    '                                                                           '
%@    'The ADVANCED OPTIONS menu has its own HELP button.                         '
%@    '                                                                           '
%@    'During computations, an INTERRUPT button appears. Clicking the button      '
%@    'interrupts the computations.                                               '];
%@  
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'gui_advc'
%@
%@  helptitle='FastICA GUI: Advanced options';
%@  helptext = [...
%@    'Advanced options:                                                     '
%@    '                                                                      '
%@    'In some cases, it may be desired to improve the statistical           '
%@    'performance of the algorithm by using a fine-tuning procedure. This   '
%@    'means that after (initial) convergence, the algorithm is run          '
%@    '(possibly) with a different nonlinearity, and using a smaller step    '
%@    'size and the stabilized version of the fixed-point algorithm.         '
%@    'You can specify the nonlinearity that will then be used with the      '
%@    'parameter ''Finetune''. If you set the the finetuning to ''off'', then the'
%@    'fine-tuning won''t be done.                                            '
%@    '                                                                      '
%@    'You can also fine-tune the nonlinearities used in the fixed-point     '
%@    'algorithm.                                                            ' 
%@    'The nonlinearities tanh and gauss contain parameters a1 and a2, so    '
%@    'that the nonlinearities are in fact defined as:                       '
%@    '''tanh''           :  g(u)=tanh(a1*u)                                   '
%@    '''gauss''          :  g(u)=u*exp(-a2*u^2/2)                             '
%@    'The default values of a1 and a2 are 1, in which case they effectively '
%@    'disappear from the definitions.                                       '
%@    '                                                                      '
%@    'If the algorithm does not seem to converge, you can use the stabilized'
%@    'version of the fixed-point algorithm. There are two ways of doing     '
%@    'this. The first one is to explicitly specify the value of the step    '
%@    'size parameter ''mu''. The default value is 1. Choosing a value that    '
%@    'is smaller than 1 implies that the computations are made using the    '
%@    'stabilized fixed-point algorithm. The second way to use the stabilized'
%@    'version is simpler: choose ''on'' in the drop-down menu ''stabilization'' '
%@    '(on the main menu page). Then the value of mu will be changed         '
%@    'automatically during the ICA calculations. If the program senses that '
%@    'the algorithm is stuck between two points, it will halve the value of '
%@    'mu (.5 * mu) for duration of one round. (This is called a ''stroke.''). '
%@    'Also if there is no convergence before half of the maximum number of  '
%@    'iterations has been reached then the mu will be halved for the rest   ' 
%@    'of the rounds.                                                        '
%@    '                                                                      '
%@    'The parameter ''epsilon'' is used to decide if the algorithm has        '
%@    'converged. A larger epsilon makes the convergence test less strict.   '
%@    'Note that if you use finetuning or stabilization, epsilon may need to '
%@    'be reduced accordingly.                                               '
%@    '                                                                      '
%@    '''Maximum number of iterations'' gives the absolute maximum of          '
%@    'iterations used in the estimation procedure. In the deflation         '
%@    'approach, this is iterations per component.                           '
%@    '                                                                      '
%@    'You can input the ''Initial state'' of the algorithm, i.e. the initial  '
%@    'value for A. Choose ''guess'' in the drop-down menu ''Initial state'',    '
%@    'click on ''Load Initial guess'', and give the name of the variable in   '
%@    'Matlab workspace that contains the initial value.                     '
%@    '                                                                      '
%@    'In the drop-down menu ''Display mode'' you can choose if the results are'
%@    'plotted during computations.  You may wish to switch this off         '
%@    'especially if you have lots of data which takes a long time to plot.  '
%@    '''Iteration between displays'' tells how often the running estimates of '
%@    'the independent components are plotted: A value of 1 means after every'
%@    'iteration.                                                            '
%@    '                                                                      '
%@    'If the data vector is very long (more than 10 000 points), it may be  '
%@    'advisable to use only a part of the data at every iteration. The      '
%@    'option ''Sample size'' allows you to give the proportion (0-1) of the   '
%@    'data that is used at every step. The sample is chosen randomly at     '
%@    'every step.                                                           '
%@    '                                                                      '
%@    'Click on DEFAULT to return to default values for all advanced options.'
%@    'You can make the new values take effect without closing the window by '
%@    'clicking APPLY.                                                       '];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'gui_lc_data'
%@
%@  helptitle='FastICA GUI: Load data';
%@  helptext = [...
%@    'Input the name of the variable in Matlab workspace that contains the  '
%@    'data. The data must be in a single matrix, each row (or column) giving'
%@    'the values of one signal. If the signals are in column vectors, click '
%@    'TRANSPOSE after loading the data to transpose the data matrix.        '
%@    '                                                                      '
%@    'If the data is in a file, load it to Matlab workspace first.          '];
%@
%@case 'gui_lc_guess'
%@
%@  helptitle='FastICA GUI: Load guess';
%@  helptext = [...
%@    'Input the name of the variable in Matlab workspace that contains the'
%@    'initial value for the mixing matrix A, and click OK. If the initial '
%@    'value is in a file, load it to Matlab workspace first.              '];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'gui_sc'
%@
%@  helptitle='FastICA GUI: Save results';
%@  helptext = [...
%@    'The results will be saved as variables in Matlab workspace.            '
%@    'You give a suffix that identifies the variables. For example, if you   '
%@    'give ''_FASTICA'', the results will be stored in the following variables:'
%@    '                                                                       '
%@    'W_FASTICA   : estimate of the separating matrix                        '
%@    'A_FASTICA   : estimate of the mixing matrix                            '
%@    'IC_FASTICA  : estimated independent components (row vectors)           '
%@    '                                                                       '
%@    'Additional results related to preprocessing:                           '
%@    'D_FASTICA and E_FASTICA    : give the eigenvalue decomposition of the  '
%@    '                             covariance matrix                         '
%@    'whiteningMatrix_FASTICA    : matrix performing whitening and dimension '
%@    '                             reduction                                 '
%@    'dewhiteningMatrix_FASTICA  : the pseudoinverse of the whitening matrix '
%@    'whitesig_FASTICA           : whitened (i.e. preprocessed) signals.     '];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@
%@end
%@
%@helpwin(helptext, helptitle);
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_l.m__ -->
%@function gui_l (x, y)
%@%
%@% This file is needed by FASTICAG
%@
%@% The load dialog for loading new data
%@% and new initial guess.
%@
%@% @(#)$Id: gui_l.m,v 1.4 2004/07/27 13:09:26 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the window
%@global hf_FastICA_Load;
%@
%@% Handles to some of the controls in window
%@global he_FastICA_file;
%@
%@% What is the load type of load dialog
%@global g_FastICA_loadType;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Configuration options
%@FIGURENAME = 'FastICA: Load';
%@FIGURETAG = 'f_FastICALoad';
%@FIGURESIZE = [x y 450 150];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Check to see if this figure is already open - it should not!
%@% Can't have more than one copy - otherwise the global
%@% variables and handles can get mixed up.
%@if ~isempty(findobj('Tag',FIGURETAG))
%@  error('Error: load dialog already open!');
%@end
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Initialize some of the controls' values
%@
%@% What are we loading - who is calling?
%@caller = get(gcf, 'CurrentObject');
%@
%@switch get(caller, 'Tag')
%@ case 'b_LoadData'                             % Do we load new data...
%@  loadString = 'Load data from variable in Matlab.';
%@  g_FastICA_loadType = 'data';
%@  FIGURENAME = 'FastICA: Load data';
%@
%@ case 'b_LoadGuess'                            % ... or new initial guess?
%@  loadString = 'Load initial guess for mixing matrix A from variable in Matlab.';
%@  g_FastICA_loadType = 'guess';
%@  FIGURENAME = 'FastICA: Load initial guess';
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the figure
%@a = figure('Color',[0.8 0.8 0.8], ...
%@	   'PaperType','a4letter', ...
%@	   'Name', FIGURENAME, ...
%@	   'NumberTitle', 'off', ...
%@	   'Tag', FIGURETAG, ...
%@	   'Position', FIGURESIZE, ...
%@	   'MenuBar', 'none');
%@set (a, 'Resize', 'off');
%@
%@hf_FastICA_Load = a;
%@
%@set(hf_FastICA_Load, 'HandleVisibility', 'callback');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% From here on it get's ugly as I have not had time to clean it up
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the frames
%@pos_l=2;
%@pos_w=FIGURESIZE(3)-4;
%@pos_h=FIGURESIZE(4)-4;
%@pos_t=2;
%@h_f_load_background = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_load_background');
%@
%@pos_w=120;
%@pos_l=FIGURESIZE(3)-(pos_w+2+2);
%@pos_h=FIGURESIZE(4)-2*4;
%@pos_t=4;
%@h_f_load_side = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_load_side');
%@
%@pos_l=4;
%@pos_w=FIGURESIZE(3)-8-pos_w-2;
%@pos_h=FIGURESIZE(4)-8;
%@pos_t=4;
%@h_f_load = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_load');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_load
%@bgc = get(h_f_load, 'BackgroundColor');
%@
%@pos_w=230;
%@
%@pos_frame=get(h_f_load, 'Position');
%@pos_h = 40;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - 6;
%@pos_l = pos_frame(1) + 6;
%@
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',loadString, ...
%@  'Style','text', ...
%@  'Tag','t_93');
%@
%@pos_h = 20;
%@pos_t = pos_t - pos_h - 10;
%@pos_l = pos_frame(1) + 6;
%@
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Name of the variable:', ...
%@  'Style','text', ...
%@  'Tag','t_92');
%@
%@pos_w = 200;
%@pos_l = pos_l + 30;
%@pos_t = pos_t - pos_h;
%@he_FastICA_file = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','', ...
%@  'Style','edit', ...
%@  'Tag','e_file');
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_load_side
%@pos_vspace = 6;
%@pos_hspace = 10;
%@pos_frame = get(h_f_load_side, 'Position');
%@pos_w = 100;
%@pos_h = 30;
%@pos_l = pos_frame(1) + pos_hspace;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_lc Load', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Load', ...
%@  'Tag','b_lLoad');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_lc Cancel', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Cancel', ...
%@  'Tag','b_lCancel');
%@
%@pos_t = pos_frame(2) + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_lc Help', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Help', ...
%@  'Tag','b_lHelp');
%@
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_lc.m__ -->
%@function gui_lc (action)
%@%
%@% This file is used by FASTICAG
%@
%@% This file holds the callbacks for load-dialog
%@
%@% @(#)$Id: gui_lc.m,v 1.4 2003/09/11 12:01:19 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the window
%@global hf_FastICA_Load;
%@
%@% Handles to some of the controls in window
%@global he_FastICA_file;
%@
%@% Needed handles from the main figure
%@global ht_FastICA_mixedStatus;
%@
%@% Needed handles from the advOpt figure
%@global hb_FastICA_initGuess;
%@global ht_FastICA_initGuess;
%@global hpm_FastICA_initState;
%@
%@% The needed main variables
%@global g_FastICA_mixedsig;
%@global g_FastICA_mixedmean;
%@
%@% What is the load type of load dialog
%@global g_FastICA_loadType;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% This should not take long...
%@watchonInFigure = watchon;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@switch action
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Load'
%@ 
%@ varName = get(he_FastICA_file, 'String');      % The name of the variable to be loaded
%@ command=['evalin(''base'',''assignin(''''caller'''',''''data'''',' varName ')'')'];
%@ eval(command,'fprintf(''Variable not found in MATLAB workspace, data not loaded!\n'');data=[];');                          % Variable is copyed to 'data'
%@ if length (size (data)) > 2,
%@   fprintf (['Input data can not have more than two dimensions, data' ...
%@	     ' not loaded.\n']);
%@   data = [];
%@ end
%@
%@ if any (any (isnan (data))),
%@   fprintf ('Input data contains NaN''s, data not loaded.\n');
%@   data = [];
%@ end
%@
%@
%@ if isempty(data)  % if there was no name given...
%@   watchoff (watchonInFigure);
%@   % There used to be a 'break' statement here, but it resulted in
%@   % errors in more recent version of Matlab -- jarmo
%@   return;
%@ end
%@ switch g_FastICA_loadType
%@  case  'data'                                % New data
%@   g_FastICA_mixedsig = data;
%@   if ~isa (g_FastICA_mixedsig, 'double')
%@     fprintf ('Warning: converting input data into regular (double) precision.\n');
%@     g_FastICA_mixedsig = double (g_FastICA_mixedsig);
%@   end
%@
%@   set(ht_FastICA_mixedStatus, 'String', '');
%@   g_FastICA_mixedmean = [];                 % New data - so that means ...
%@   gui_cb NewData;                             
%@   
%@  case 'guess'                                % New initial guess
%@   set(hb_FastICA_initGuess, 'UserData', data);     % Since we loaded new initial
%@   set(ht_FastICA_initGuess, 'String', 'Loaded');   % guess, we wan't to use it too
%@   set(hpm_FastICA_initState, 'Value', 2);          % ... set initState to 'guess'
%@ end
%@
%@ close(hf_FastICA_Load);                       % close the dialog
%@
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Cancel'
%@ 
%@ close(hf_FastICA_Load);                       % do nothing just exit
%@
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Help'
%@
%@ % Which help do we show?
%@ switch g_FastICA_loadType
%@  case 'data'
%@   gui_help('gui_lc_data');
%@  case 'guess'
%@   gui_help('gui_lc_guess');
%@ end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@end    % switch
%@
%@watchoff (watchonInFigure);
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_s.m__ -->
%@function gui_s (x, y)
%@%
%@% This file is used by FASTICAG
%@
%@% The save dialog for saving the results
%@
%@% @(#)$Id: gui_s.m,v 1.4 2004/07/27 13:09:26 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the window
%@global hf_FastICA_Save;
%@
%@% Handles to some of the controls in window
%@global he_FastICA_suffix;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Configuration options
%@FIGURENAME = 'FastICA: Save results';
%@FIGURETAG = 'f_FastICASave';
%@FIGURESIZE = [x y 450 150];
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Check to see if this figure is already open - it should not!
%@% Can't have more than one copy - otherwise the global
%@% variables and handles can get mixed up.
%@if ~isempty(findobj('Tag',FIGURETAG))
%@  error('Error: load dialog already open!');
%@end
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Initialize some of the controls' values
%@
%@saveString = 'Save results as variables in MATLAB workspace.';
%@promptString = 'Suffix to identify the results:';
%@helpString = 'If you give e.g. ''_FastICA'', the variables will be called A_FastICA, W_FastICA, etc.';
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the figure
%@a = figure('Color',[0.8 0.8 0.8], ...
%@	   'PaperType','a4letter', ...
%@	   'Name', FIGURENAME, ...
%@	   'NumberTitle', 'off', ...
%@	   'Tag', FIGURETAG, ...
%@	   'Position', FIGURESIZE, ...
%@	   'MenuBar', 'none');
%@set (a, 'Resize', 'off');
%@
%@hf_FastICA_Save = a;
%@
%@set(hf_FastICA_Save, 'HandleVisibility', 'callback');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% From here on it get's ugly as I have not had time to clean it up
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Create the frames
%@pos_l=2;
%@pos_w=FIGURESIZE(3)-4;
%@pos_h=FIGURESIZE(4)-4;
%@pos_t=2;
%@h_f_save_background = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_save_background');
%@
%@pos_w=120;
%@pos_l=FIGURESIZE(3)-(pos_w+2+2);
%@pos_h=FIGURESIZE(4)-2*4;
%@pos_t=4;
%@h_f_save_side = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_save_side');
%@
%@pos_l=4;
%@pos_w=FIGURESIZE(3)-8-pos_w-2;
%@pos_h=FIGURESIZE(4)-8;
%@pos_t=4;
%@h_f_save = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'Style','frame', ...
%@  'Tag','f_save');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_save
%@bgc = get(h_f_save, 'BackgroundColor');
%@
%@pos_w=230;
%@
%@pos_frame=get(h_f_save, 'Position');
%@pos_h = 40;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - 6;
%@pos_l = pos_frame(1) + 6;
%@
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',saveString, ...
%@  'Style','text', ...
%@  'Tag','t_93');
%@
%@pos_h = 20;
%@pos_t = pos_t - pos_h - 10;
%@pos_l = pos_frame(1) + 6;
%@
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',promptString, ...
%@  'Style','text', ...
%@  'Tag','t_92');
%@
%@pos_w = 200;
%@pos_l = pos_l + 30;
%@pos_t = pos_t - pos_h;
%@he_FastICA_suffix = uicontrol('Parent',a, ...
%@  'BackgroundColor',[1 1 1], ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','', ...
%@  'Style','edit', ...
%@  'Tag','e_suffix');
%@
%@pos_w = pos_frame(3) - 12;
%@pos_h = 30;
%@pos_t = pos_frame(2) + 6;
%@pos_l = pos_frame(1) + 6;
%@
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',bgc, ...
%@  'HorizontalAlignment','left', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String',helpString, ...
%@  'Style','text', ...
%@  'Tag','t_97');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Controls in f_save_side
%@pos_vspace = 6;
%@pos_hspace = 10;
%@pos_frame = get(h_f_save_side, 'Position');
%@pos_w = 100;
%@pos_h = 30;
%@pos_l = pos_frame(1) + pos_hspace;
%@pos_t = pos_frame(2) + pos_frame(4) - pos_h - pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_sc Save', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Save', ...
%@  'Tag','b_sSave');
%@
%@pos_t=pos_t-pos_h-pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_sc Cancel', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Cancel', ...
%@  'Tag','b_sCancel');
%@
%@pos_t = pos_frame(2) + pos_vspace;
%@b = uicontrol('Parent',a, ...
%@  'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@  'Callback','gui_sc Help', ...
%@  'Position',[pos_l pos_t pos_w pos_h], ...
%@  'String','Help', ...
%@  'Tag','b_sHelp');
%@
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __gui_sc.m__ -->
%@function gui_sc (action)
%@%
%@% This file is used by FASTICAG
%@
%@% This file holds the callbacks for save-dialog
%@
%@% @(#)$Id: gui_sc.m,v 1.3 2003/09/08 11:28:59 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Global variables
%@
%@% Handle to the window
%@global hf_FastICA_Save;
%@
%@% Handles to some of the controls in window
%@global he_FastICA_suffix;
%@
%@% The needed main variables
%@global g_FastICA_ica_sig;
%@global g_FastICA_ica_A;
%@global g_FastICA_ica_W;
%@global g_FastICA_white_sig;
%@global g_FastICA_white_wm;
%@global g_FastICA_white_dwm;
%@global g_FastICA_pca_E;
%@global g_FastICA_pca_D;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% This should not take long...
%@watchonInFigure = watchon;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@switch action
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Save'
%@ 
%@ suffix = deblank(get(he_FastICA_suffix, 'String')); % The suffix for the variables
%@
%@ fprintf('Saving results in variables in Matlab workspace.\n');
%@ assignin('base',['IC' suffix],g_FastICA_ica_sig);
%@ assignin('base',['A' suffix],g_FastICA_ica_A);
%@ assignin('base',['W' suffix],g_FastICA_ica_W);
%@ assignin('base',['whitesig' suffix],g_FastICA_white_sig);
%@ assignin('base',['whiteningMatrix' suffix],g_FastICA_white_wm);
%@ assignin('base',['dewhiteningMatrix' suffix],g_FastICA_white_dwm);
%@ assignin('base',['E' suffix],g_FastICA_pca_E);
%@ assignin('base',['D' suffix],g_FastICA_pca_D);
%@
%@ close(hf_FastICA_Save);                  % close the dialog
%@ 
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@  
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Cancel'
%@ 
%@ close(hf_FastICA_Save);                       % do nothing just exit
%@
%@ % Use return to avoid reaching the watchoff statement at the end
%@ % (There used to be a 'break' statement here, but it resulted in
%@ % errors in more recent version of Matlab -- jarmo)
%@ return;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@case 'Help'
%@
%@ gui_help('gui_sc');
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@end    % switch
%@
%@watchoff (watchonInFigure);
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __icaplot.m__ -->
%@function icaplot(mode, varargin);
%@%ICAPLOT - plot signals in various ways
%@%
%@% ICAPLOT is mainly for plottinf and comparing the mixed signals and
%@% separated ica-signals.
%@%
%@% ICAPLOT has many different modes. The first parameter of the function
%@% defines the mode. Other parameters and their order depends on the
%@% mode. The explanation for the more common parameters is in the end.
%@%
%@% Classic
%@%     icaplot('classic', s1, n1, range, xrange, titlestr)
%@%
%@%     Plots the signals in the same manner as the FASTICA and FASTICAG
%@%     programs do. All the signals are plotted in their own axis.
%@%
%@% Complot
%@%     icaplot('complot', s1, n1, range, xrange, titlestr)
%@%
%@%     The signals are plotted on the same axis. This is good for
%@%     visualization of the shape of the signals. The scale of the signals 
%@%     has been altered so that they all fit nicely.
%@%
%@% Histogram
%@%     icaplot('histogram', s1, n1, range, bins, style)
%@%     
%@%     The histogram of the signals is plotted. The number of bins can be
%@%     specified with 'bins'-parameter. The style for the histograms can
%@%     be either 'bar' (default) of 'line'.
%@%
%@% Scatter
%@%     icaplot('scatter', s1, n1, s2, n2, range, titlestr, s1label,
%@%     s2label, markerstr)
%@%
%@%     A scatterplot is plotted so that the signal 1 is the 'X'-variable
%@%     and the signal 2 is the 'Y'-variable. The 'markerstr' can be used
%@%     to specify the maker used in the plot. The format for 'markerstr'
%@%     is the same as for Matlab's PLOT. 
%@%
%@% Compare
%@%     icaplot('compare', s1, n1, s2, n2, range, xrange, titlestr,
%@%     s1label, s2label)
%@%
%@%     This for for comparing two signals. The main used in this context
%@%     would probably be to see how well the separated ICA-signals explain 
%@%     the observed mixed signals. The s2 signals are first scaled with
%@%     REGRESS function.
%@%
%@% Compare - Sum
%@%     icaplot('sum', s1, n1, s2, n2, range, xrange, titlestr, s1label,
%@%     s2label)
%@%
%@%     The same as Compare, but this time the signals in s2 (specified by
%@%     n2) are summed together.
%@%
%@% Compare - Sumerror
%@%     icaplot('sumerror', s1, n1, s2, n2, range, xrange, titlestr,
%@%     s1label, s2label)
%@%     
%@%     The same as Compare - Sum, but also the 'error' between the signal
%@%     1 and the summed IC's is plotted.
%@%
%@%
%@% More common parameters
%@%     The signals to be plotted are in matrices s1 and s2. The n1 and n2
%@%     are used to tell the index of the signal or signals to be plotted
%@%     from s1 or s2. If n1 or n2 has a value of 0, then all the signals
%@%     from corresponding matrix will be plotted. The values for n1 and n2 
%@%     can also be vectors (like: [1 3 4]) In some casee if there are more
%@%     than 1 signal to be plotted from s1 or s2 then the plot will
%@%     contain as many subplots as are needed. 
%@%
%@%     The range of the signals to be plotted can be limited with
%@%     'range'-parameter. It's value is a vector ( 10000:15000 ). If range 
%@%     is 0, then the whole range will be plotted.
%@%
%@%     The 'xrange' is used to specify only the labels used on the
%@%     x-axis. The value of 'xrange' is a vector containing the x-values
%@%     for the plots or [start end] for begin and end of the range
%@%     ( 10000:15000 or [10 15] ). If xrange is 0, then value of range
%@%     will be used for x-labels.
%@%
%@%     You can give a title for the plot with 'titlestr'. Also the
%@%     's1label' and 's2label' are used to give more meaningfull label for 
%@%     the signals.
%@%
%@%     Lastly, you can omit some of the arguments from the and. You will
%@%     have to give values for the signal matrices (s1, s2) and the
%@%     indexes (n1, n2)
%@
%@% @(#)$Id: icaplot.m,v 1.2 2003/04/05 14:23:58 jarmo Exp $
%@
%@switch mode
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@  % 'dispsig' is to replace the old DISPSIG
%@  % '' & 'classic' are just another names - '' quite short one :-)
%@ case {'', 'classic', 'dispsig'} 
%@  % icaplot(mode, s1, n1, range, xrange, titlestr)
%@  if length(varargin) < 1, error('Not enough arguments.'); end
%@  if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
%@  if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
%@  if length(varargin) < 3, range = 0;else range = varargin{3}; end
%@  if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
%@  s1 = varargin{1};
%@  range=chkrange(range, s1);
%@  xrange=chkxrange(xrange, range);
%@  n1=chkn(n1, s1);
%@
%@  clf;
%@  
%@  numSignals = size(n1, 2);
%@  for i = 1:numSignals,
%@    subplot(numSignals, 1, i);
%@    plot(xrange, s1(n1(i), range));
%@  end
%@  subplot(numSignals,1, 1);
%@  if (~isempty(titlestr))
%@    title(titlestr);
%@  end
%@  
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@ case 'complot'
%@  % icaplot(mode, s1, n1, range, xrange, titlestr)
%@  if length(varargin) < 1, error('Not enough arguments.'); end
%@  if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
%@  if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
%@  if length(varargin) < 3, range = 0;else range = varargin{3}; end
%@  if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
%@  s1 = remmean(varargin{1});
%@  range=chkrange(range, s1);
%@  xrange=chkxrange(xrange, range);
%@  n1=chkn(n1, s1);
%@  
%@  for i = 1:size(n1, 2)
%@    S1(i, :) = s1(n1(i), range);
%@  end
%@  
%@  alpha = mean(max(S1')-min(S1'));
%@  for i = 1:size(n1,2)
%@    S2(i,:) = S1(i,:) - alpha*(i-1)*ones(size(S1(1,:)));
%@  end
%@  
%@  plot(xrange, S2');
%@  axis([min(xrange) max(xrange) min(min(S2)) max(max(S2)) ]);
%@  
%@  set(gca,'YTick',(-size(S1,1)+1)*alpha:alpha:0);
%@  set(gca,'YTicklabel',fliplr(n1));
%@  
%@  if (~isempty(titlestr))
%@    title(titlestr);
%@  end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@ case 'histogram'
%@  % icaplot(mode, s1, n1, range, bins, style)
%@  if length(varargin) < 1, error('Not enough arguments.'); end
%@  if length(varargin) < 5, style = 'bar';else style = varargin{5}; end
%@  if length(varargin) < 4, bins = 10;else bins = varargin{4}; end
%@  if length(varargin) < 3, range = 0;else range = varargin{3}; end
%@  if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
%@  s1 = varargin{1};
%@  range = chkrange(range, s1);
%@  n1 = chkn(n1, s1);
%@  
%@  numSignals = size(n1, 2);
%@  rows = floor(sqrt(numSignals));
%@  columns = ceil(sqrt(numSignals));
%@  while (rows * columns < numSignals)
%@    columns = columns + 1;
%@  end
%@  
%@  switch style
%@   case {'', 'bar'}
%@    for i = 1:numSignals,
%@      subplot(rows, columns, i);
%@      hist(s1(n1(i), range), bins);
%@      title(int2str(n1(i)));
%@      drawnow;
%@    end
%@    
%@   case 'line'
%@    for i = 1:numSignals,
%@      subplot(rows, columns, i);
%@      [Y, X]=hist(s1(n1(i), range), bins);
%@      plot(X, Y);
%@      title(int2str(n1(i)));
%@      drawnow;
%@    end
%@   otherwise
%@    fprintf('Unknown style.\n')
%@  end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@ case 'scatter'
%@  % icaplot(mode, s1, n1, s2, n2, range, titlestr, xlabelstr, ylabelstr, markerstr)
%@  if length(varargin) < 4, error('Not enough arguments.'); end
%@  if length(varargin) < 9, markerstr = '.';else markerstr = varargin{9}; end
%@  if length(varargin) < 8, ylabelstr = 'Signal 2';else ylabelstr = varargin{8}; end
%@  if length(varargin) < 7, xlabelstr = 'Signal 1';else xlabelstr = varargin{7}; end
%@  if length(varargin) < 6, titlestr = '';else titlestr = varargin{6}; end
%@  if length(varargin) < 5, range = 0;else range = varargin{5}; end
%@  n2 = varargin{4};
%@  s2 = varargin{3};
%@  n1 = varargin{2};
%@  s1 = varargin{1};
%@  range = chkrange(range, s1);
%@  n1 = chkn(n1, s1);
%@  n2 = chkn(n2, s2);
%@  
%@  rows = size(n1, 2);
%@  columns = size(n2, 2);
%@  for r = 1:rows
%@    for c = 1:columns
%@      subplot(rows, columns, (r-1)*columns + c);
%@      plot(s1(n1(r), range),s2(n2(c), range),markerstr);
%@      if (~isempty(titlestr))
%@	title(titlestr);
%@      end
%@      if (rows*columns == 1)
%@	xlabel(xlabelstr);
%@	ylabel(ylabelstr);
%@      else 
%@	xlabel([xlabelstr ' (' int2str(n1(r)) ')']);
%@	ylabel([ylabelstr ' (' int2str(n2(c)) ')']);
%@      end
%@      drawnow;
%@    end
%@  end
%@  
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@ case {'compare', 'sum', 'sumerror'}
%@  % icaplot(mode, s1, n1, s2, n2, range, xrange, titlestr, s1label, s2label)
%@  if length(varargin) < 4, error('Not enough arguments.'); end
%@  if length(varargin) < 9, s2label = 'IC';else s2label = varargin{9}; end
%@  if length(varargin) < 8, s1label = 'Mix';else s1label = varargin{8}; end
%@  if length(varargin) < 7, titlestr = '';else titlestr = varargin{7}; end
%@  if length(varargin) < 6, xrange = 0;else xrange = varargin{6}; end
%@  if length(varargin) < 5, range = 0;else range = varargin{5}; end
%@  s1 = varargin{1};
%@  n1 = varargin{2};
%@  s2 = varargin{3};
%@  n2 = varargin{4};
%@  range = chkrange(range, s1);
%@  xrange = chkxrange(xrange, range);
%@  n1 = chkn(n1, s1);
%@  n2 = chkn(n2, s2);
%@
%@  numSignals = size(n1, 2);
%@  if (numSignals > 1)
%@    externalLegend = 1;
%@  else
%@    externalLegend = 0;
%@  end
%@  
%@  rows = floor(sqrt(numSignals+externalLegend));
%@  columns = ceil(sqrt(numSignals+externalLegend));
%@  while (rows * columns < (numSignals+externalLegend))
%@    columns = columns + 1;
%@  end
%@  
%@  clf;
%@  
%@  for j = 1:numSignals
%@    subplot(rows, columns, j);
%@    switch mode
%@     case 'compare'
%@      plotcompare(s1, n1(j), s2,n2, range, xrange);
%@      [legendtext,legendstyle]=legendcompare(n1(j),n2,s1label,s2label,externalLegend);
%@     case 'sum'
%@      plotsum(s1, n1(j), s2,n2, range, xrange);
%@      [legendtext,legendstyle]=legendsum(n1(j),n2,s1label,s2label,externalLegend);
%@     case 'sumerror'
%@      plotsumerror(s1, n1(j), s2,n2, range, xrange);
%@      [legendtext,legendstyle]=legendsumerror(n1(j),n2,s1label,s2label,externalLegend);
%@    end
%@    
%@    if externalLegend
%@      title([titlestr ' (' s1label  ' ' int2str(n1(j)) ')']);
%@    else
%@      legend(char(legendtext));
%@      if (~isempty(titlestr))
%@	title(titlestr);
%@      end
%@    end
%@  end
%@  
%@  if (externalLegend)
%@    subplot(rows, columns, numSignals+1);
%@    legendsize = size(legendtext, 2);
%@    hold on;
%@    for i=1:legendsize
%@      plot([0 1],[legendsize-i legendsize-i], char(legendstyle(i)));
%@      text(1.5, legendsize-i, char(legendtext(i)));
%@    end
%@    hold off;
%@    axis([0 6 -1 legendsize]);
%@    axis off;
%@  end
%@  
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function plotcompare(s1, n1, s2, n2, range, xrange);
%@  style=getStyles;
%@  K = regress(s1(n1,:)',s2');
%@  plot(xrange, s1(n1,range), char(style(1)));
%@  hold on
%@  for i=1:size(n2,2)
%@    plotstyle=char(style(i+1));
%@    plot(xrange, K(n2(i))*s2(n2(i),range), plotstyle);
%@  end
%@  hold off
%@
%@function [legendText, legendStyle]=legendcompare(n1, n2, s1l, s2l, externalLegend);
%@  style=getStyles;
%@  if (externalLegend)
%@    legendText(1)={[s1l ' (see the titles)']};
%@  else
%@    legendText(1)={[s1l ' ', int2str(n1)]};
%@  end
%@  legendStyle(1)=style(1);
%@  for i=1:size(n2, 2)
%@    legendText(i+1) = {[s2l ' ' int2str(n2(i))]};
%@    legendStyle(i+1) = style(i+1);
%@  end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function plotsum(s1, n1, s2, n2, range, xrange);
%@  K = diag(regress(s1(n1,:)',s2'));
%@  sigsum = sum(K(:,n2)*s2(n2,:));
%@  plot(xrange, s1(n1, range),'k-', ...
%@       xrange, sigsum(range), 'b-');
%@
%@function [legendText, legendStyle]=legendsum(n1, n2, s1l, s2l, externalLegend);
%@  if (externalLegend)
%@    legendText(1)={[s1l ' (see the titles)']};
%@  else
%@    legendText(1)={[s1l ' ', int2str(n1)]};
%@  end
%@  legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
%@  legendStyle={'k-';'b-'};
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function plotsumerror(s1, n1, s2, n2, range, xrange);
%@  K = diag(regress(s1(n1,:)',s2'));
%@  sigsum = sum(K(:,n2)*s2(n2,:));
%@  plot(xrange, s1(n1, range),'k-', ...
%@       xrange, sigsum(range), 'b-', ...
%@       xrange, s1(n1, range)-sigsum(range), 'r-');
%@
%@function [legendText, legendStyle]=legendsumerror(n1, n2, s1l, s2l, externalLegend);
%@  if (externalLegend)
%@    legendText(1)={[s1l ' (see the titles)']};
%@  else
%@    legendText(1)={[s1l ' ', int2str(n1)]};
%@  end
%@  legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
%@  legendText(3)={'"Error"'};
%@  legendStyle={'k-';'b-';'r-'};
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function style=getStyles;
%@  color = {'k','r','g','b','m','c','y'};
%@  line = {'-',':','-.','--'};
%@  for i = 0:size(line,2)-1
%@    for j = 1:size(color, 2)
%@      style(j + i*size(color, 2)) = strcat(color(j), line(i+1));
%@    end
%@  end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function range=chkrange(r, s)
%@  if r == 0
%@    range = 1:size(s, 2);
%@  else
%@    range = r;
%@  end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function xrange=chkxrange(xr,r);
%@  if xr == 0
%@    xrange = r;
%@  elseif size(xr, 2) == 2
%@    xrange = xr(1):(xr(2)-xr(1))/(size(r,2)-1):xr(2);
%@  elseif size(xr, 2)~=size(r, 2)
%@    error('Xrange and range have different sizes.');
%@  else
%@    xrange = xr;
%@  end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function n=chkn(n,s)
%@  if n == 0
%@    n = 1:size(s, 1);
%@  end
%<-- ASCII ends here -->
%<-- ASCII begins here: __info.xml__ -->
%@<productinfo>
%@
%@<matlabrelease>13</matlabrelease>
%@<name>Fast ICA</name>
%@<area>toolbox</area>
%@<icon>$toolbox/matlab/icons/matlabicon.gif</icon>
%@
%@<list>
%@
%@<listitem>
%@<label>Start Fast ICA Toolbox</label>
%@<callback>fasticag</callback>
%@<icon>$toolbox/matlab/icons/figureicon.gif</icon>
%@</listitem>
%@
%@<listitem>
%@<label>Help</label>
%@<callback>helpwin FastICA/</callback>
%@<icon>$toolbox/matlab/icons/bookicon.gif</icon>
%@</listitem>
%@
%@<listitem>
%@<label>Product Page (Web)</label>
%@<callback>web http://www.cis.hut.fi/projects/ica/fastica -browser;</callback>
%@<icon>$toolbox/matlab/icons/webicon.gif</icon>
%@</listitem>
%@
%@</list>
%@
%@</productinfo>
%<-- ASCII ends here -->
%<-- ASCII begins here: __pcamat.m__ -->
%@function [E, D] = pcamat(vectors, firstEig, lastEig, s_interactive, ...
%@    s_verbose);
%@%PCAMAT - Calculates the pca for data
%@%
%@% [E, D] = pcamat(vectors, firstEig, lastEig, ... 
%@%                 interactive, verbose);
%@%
%@% Calculates the PCA matrices for given data (row) vectors. Returns
%@% the eigenvector (E) and diagonal eigenvalue (D) matrices containing the
%@% selected subspaces. Dimensionality reduction is controlled with
%@% the parameters 'firstEig' and 'lastEig' - but it can also be done
%@% interactively by setting parameter 'interactive' to 'on' or 'gui'.
%@%
%@% ARGUMENTS
%@%
%@% vectors       Data in row vectors.
%@% firstEig      Index of the largest eigenvalue to keep.
%@%               Default is 1.
%@% lastEig       Index of the smallest eigenvalue to keep.
%@%               Default is equal to dimension of vectors.
%@% interactive   Specify eigenvalues to keep interactively. Note that if
%@%               you set 'interactive' to 'on' or 'gui' then the values
%@%               for 'firstEig' and 'lastEig' will be ignored, but they
%@%               still have to be entered. If the value is 'gui' then the
%@%               same graphical user interface as in FASTICAG will be
%@%               used. Default is 'off'.
%@% verbose       Default is 'on'.
%@%
%@%
%@% EXAMPLE
%@%       [E, D] = pcamat(vectors);
%@%
%@% Note 
%@%       The eigenvalues and eigenvectors returned by PCAMAT are not sorted.
%@%
%@% This function is needed by FASTICA and FASTICAG
%@
%@% For historical reasons this version does not sort the eigenvalues or
%@% the eigen vectors in any ways. Therefore neither does the FASTICA or
%@% FASTICAG. Generally it seams that the components returned from
%@% whitening is almost in reversed order. (That means, they usually are,
%@% but sometime they are not - depends on the EIG-command of matlab.)
%@
%@% @(#)$Id: pcamat.m,v 1.5 2003/12/15 18:24:32 jarmo Exp $
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Default values:
%@if nargin < 5, s_verbose = 'on'; end
%@if nargin < 4, s_interactive = 'off'; end
%@if nargin < 3, lastEig = size(vectors, 1); end
%@if nargin < 2, firstEig = 1; end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Check the optional parameters;
%@switch lower(s_verbose)
%@ case 'on'
%@  b_verbose = 1;
%@ case 'off'
%@  b_verbose = 0;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
%@end
%@
%@switch lower(s_interactive)
%@ case 'on'
%@  b_interactive = 1;
%@ case 'off'
%@  b_interactive = 0;
%@ case 'gui'
%@  b_interactive = 2;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''interactive''\n', ...
%@		s_interactive));
%@end
%@
%@oldDimension = size (vectors, 1);
%@if ~(b_interactive)
%@  if lastEig < 1 | lastEig > oldDimension
%@    error(sprintf('Illegal value [ %d ] for parameter: ''lastEig''\n', lastEig));
%@  end
%@  if firstEig < 1 | firstEig > lastEig
%@    error(sprintf('Illegal value [ %d ] for parameter: ''firstEig''\n', firstEig));
%@  end
%@end
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Calculate PCA
%@
%@% Calculate the covariance matrix.
%@if b_verbose, fprintf ('Calculating covariance...\n'); end
%@covarianceMatrix = cov(vectors', 1);
%@
%@% Calculate the eigenvalues and eigenvectors of covariance
%@% matrix.
%@[E, D] = eig (covarianceMatrix);
%@
%@% The rank is determined from the eigenvalues - and not directly by
%@% using the function rank - because function rank uses svd, which
%@% in some cases gives a higher dimensionality than what can be used
%@% with eig later on (eig then gives negative eigenvalues).
%@rankTolerance = 1e-7;
%@maxLastEig = sum (diag (D) > rankTolerance);
%@if maxLastEig == 0,
%@  fprintf (['Eigenvalues of the covariance matrix are' ...
%@	    ' all smaller than tolerance [ %g ].\n' ...
%@	    'Please make sure that your data matrix contains' ...
%@	    ' nonzero values.\nIf the values are very small,' ...
%@	    ' try rescaling the data matrix.\n'], rankTolerance);
%@  error ('Unable to continue, aborting.');
%@end
%@
%@% Sort the eigenvalues - decending.
%@eigenvalues = flipud(sort(diag(D)));
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Interactive part - command-line
%@if b_interactive == 1
%@
%@  % Show the eigenvalues to the user
%@  hndl_win=figure;
%@  bar(eigenvalues);
%@  title('Eigenvalues');
%@
%@  % ask the range from the user...
%@  % ... and keep on asking until the range is valid :-)
%@  areValuesOK=0;
%@  while areValuesOK == 0
%@    firstEig = input('The index of the largest eigenvalue to keep? (1) ');
%@    lastEig = input(['The index of the smallest eigenvalue to keep? (' ...
%@                    int2str(oldDimension) ') ']);
%@    % Check the new values...
%@    % if they are empty then use default values
%@    if isempty(firstEig), firstEig = 1;end
%@    if isempty(lastEig), lastEig = oldDimension;end
%@    % Check that the entered values are within the range
%@    areValuesOK = 1;
%@    if lastEig < 1 | lastEig > oldDimension
%@      fprintf('Illegal number for the last eigenvalue.\n');
%@      areValuesOK = 0;
%@    end
%@    if firstEig < 1 | firstEig > lastEig
%@      fprintf('Illegal number for the first eigenvalue.\n');
%@      areValuesOK = 0;
%@    end
%@  end
%@  % close the window
%@  close(hndl_win);
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Interactive part - GUI
%@if b_interactive == 2
%@
%@  % Show the eigenvalues to the user
%@  hndl_win = figure('Color',[0.8 0.8 0.8], ...
%@    'PaperType','a4letter', ...
%@    'Units', 'normalized', ...
%@    'Name', 'FastICA: Reduce dimension', ...
%@    'NumberTitle','off', ...
%@    'Tag', 'f_eig');
%@  h_frame = uicontrol('Parent', hndl_win, ...
%@    'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@    'Units', 'normalized', ...
%@    'Position',[0.13 0.05 0.775 0.17], ...
%@    'Style','frame', ...
%@    'Tag','f_frame');
%@
%@b = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@	'HorizontalAlignment','left', ...
%@	'Position',[0.142415 0.0949436 0.712077 0.108507], ...
%@	'String','Give the indices of the largest and smallest eigenvalues of the covariance matrix to be included in the reduced data.', ...
%@	'Style','text', ...
%@	'Tag','StaticText1');
%@e_first = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'Callback',[ ...
%@          'f=round(str2num(get(gcbo, ''String'')));' ...
%@          'if (f < 1), f=1; end;' ...
%@          'l=str2num(get(findobj(''Tag'',''e_last''), ''String''));' ...
%@          'if (f > l), f=l; end;' ...
%@          'set(gcbo, ''String'', int2str(f));' ...
%@          ], ...
%@	'BackgroundColor',[1 1 1], ...
%@	'HorizontalAlignment','right', ...
%@	'Position',[0.284831 0.0678168 0.12207 0.0542535], ...
%@	'Style','edit', ...
%@        'String', '1', ...
%@	'Tag','e_first');
%@b = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@	'HorizontalAlignment','left', ...
%@	'Position',[0.142415 0.0678168 0.12207 0.0542535], ...
%@	'String','Range from', ...
%@	'Style','text', ...
%@	'Tag','StaticText2');
%@e_last = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'Callback',[ ...
%@          'l=round(str2num(get(gcbo, ''String'')));' ...
%@          'lmax = get(gcbo, ''UserData'');' ...
%@          'if (l > lmax), l=lmax; fprintf([''The selected value was too large, or the selected eigenvalues were close to zero\n'']); end;' ...
%@          'f=str2num(get(findobj(''Tag'',''e_first''), ''String''));' ...
%@          'if (l < f), l=f; end;' ...
%@          'set(gcbo, ''String'', int2str(l));' ...
%@          ], ...
%@	'BackgroundColor',[1 1 1], ...
%@	'HorizontalAlignment','right', ...
%@	'Position',[0.467936 0.0678168 0.12207 0.0542535], ...
%@	'Style','edit', ...
%@        'String', int2str(maxLastEig), ...
%@        'UserData', maxLastEig, ...
%@	'Tag','e_last');
%@% in the first version oldDimension was used instead of 
%@% maxLastEig, but since the program would automatically
%@% drop the eigenvalues afte maxLastEig...
%@b = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'BackgroundColor',[0.701961 0.701961 0.701961], ...
%@	'HorizontalAlignment','left', ...
%@	'Position',[0.427246 0.0678168 0.0406901 0.0542535], ...
%@	'String','to', ...
%@	'Style','text', ...
%@	'Tag','StaticText3');
%@b = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'Callback','uiresume(gcbf)', ...
%@	'Position',[0.630697 0.0678168 0.12207 0.0542535], ...
%@	'String','OK', ...
%@	'Tag','Pushbutton1');
%@b = uicontrol('Parent',hndl_win, ...
%@	'Units','normalized', ...
%@	'Callback',[ ...
%@          'gui_help(''pcamat'');' ...
%@          ], ...
%@	'Position',[0.767008 0.0678168 0.12207 0.0542535], ...
%@	'String','Help', ...
%@	'Tag','Pushbutton2');
%@
%@  h_axes = axes('Position' ,[0.13 0.3 0.775 0.6]);
%@  set(hndl_win, 'currentaxes',h_axes);
%@  bar(eigenvalues);
%@  title('Eigenvalues');
%@
%@  uiwait(hndl_win);
%@  firstEig = str2num(get(e_first, 'String'));
%@  lastEig = str2num(get(e_last, 'String'));
%@
%@  % close the window
%@  close(hndl_win);
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% See if the user has reduced the dimension enought
%@
%@if lastEig > maxLastEig
%@  lastEig = maxLastEig;
%@  if b_verbose
%@    fprintf('Dimension reduced to %d due to the singularity of covariance matrix\n',...
%@           lastEig-firstEig+1);
%@  end
%@else
%@  % Reduce the dimensionality of the problem.
%@  if b_verbose
%@    if oldDimension == (lastEig - firstEig + 1)
%@      fprintf ('Dimension not reduced.\n');
%@    else
%@      fprintf ('Reducing dimension...\n');
%@    end
%@  end
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Drop the smaller eigenvalues
%@if lastEig < oldDimension
%@  lowerLimitValue = (eigenvalues(lastEig) + eigenvalues(lastEig + 1)) / 2;
%@else
%@  lowerLimitValue = eigenvalues(oldDimension) - 1;
%@end
%@
%@lowerColumns = diag(D) > lowerLimitValue;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Drop the larger eigenvalues
%@if firstEig > 1
%@  higherLimitValue = (eigenvalues(firstEig - 1) + eigenvalues(firstEig)) / 2;
%@else
%@  higherLimitValue = eigenvalues(1) + 1;
%@end
%@higherColumns = diag(D) < higherLimitValue;
%@
%@% Combine the results from above
%@selectedColumns = lowerColumns & higherColumns;
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% print some info for the user
%@if b_verbose
%@  fprintf ('Selected [ %d ] dimensions.\n', sum (selectedColumns));
%@end
%@if sum (selectedColumns) ~= (lastEig - firstEig + 1),
%@  error ('Selected a wrong number of dimensions.');
%@end
%@
%@if b_verbose
%@  fprintf ('Smallest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(lastEig));
%@  fprintf ('Largest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(firstEig));
%@  fprintf ('Sum of removed eigenvalues [ %g ]\n', sum(diag(D) .* ...
%@    (~selectedColumns)));
%@end
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Select the colums which correspond to the desired range
%@% of eigenvalues.
%@E = selcol(E, selectedColumns);
%@D = selcol(selcol(D, selectedColumns)', selectedColumns);
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@% Some more information
%@if b_verbose
%@  sumAll=sum(eigenvalues);
%@  sumUsed=sum(diag(D));
%@  retained = (sumUsed / sumAll) * 100;
%@  fprintf('[ %g ] %% of (non-zero) eigenvalues retained.\n', retained);
%@end
%@
%@
%@
%@
%@
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%@function newMatrix = selcol(oldMatrix, maskVector);
%@
%@% newMatrix = selcol(oldMatrix, maskVector);
%@%
%@% Selects the columns of the matrix that marked by one in the given vector.
%@% The maskVector is a column vector.
%@
%@% 15.3.1998
%@
%@if size(maskVector, 1) ~= size(oldMatrix, 2),
%@  error ('The mask vector and matrix are of uncompatible size.');
%@end
%@
%@numTaken = 0;
%@
%@for i = 1 : size (maskVector, 1),
%@  if maskVector(i, 1) == 1,
%@    takingMask(1, numTaken + 1) = i;
%@    numTaken = numTaken + 1;
%@  end
%@end
%@
%@newMatrix = oldMatrix(:, takingMask);
%<-- ASCII ends here -->
%<-- ASCII begins here: __remmean.m__ -->
%@function [newVectors, meanValue] = remmean(vectors);
%@%REMMEAN - remove the mean from vectors
%@%
%@% [newVectors, meanValue] = remmean(vectors);
%@%
%@% Removes the mean of row vectors.
%@% Returns the new vectors and the mean.
%@%
%@% This function is needed by FASTICA and FASTICAG
%@
%@% @(#)$Id: remmean.m,v 1.2 2003/04/05 14:23:58 jarmo Exp $
%@
%@newVectors = zeros (size (vectors));
%@meanValue = mean (vectors')';
%@newVectors = vectors - meanValue * ones (1,size (vectors, 2));
%@
%<-- ASCII ends here -->
%<-- ASCII begins here: __whitenv.m__ -->
%@function [newVectors, whiteningMatrix, dewhiteningMatrix] = whitenv ...
%@    (vectors, E, D, s_verbose);
%@%WHITENV - Whitenv vectors.
%@%
%@% [newVectors, whiteningMatrix, dewhiteningMatrix] = ...
%@%                               whitenv(vectors, E, D, verbose);
%@%
%@% Whitens the data (row vectors) and reduces dimension. Returns
%@% the whitened vectors (row vectors), whitening and dewhitening matrices.
%@%
%@% ARGUMENTS
%@%
%@% vectors       Data in row vectors.
%@% E             Eigenvector matrix from function 'pcamat'
%@% D             Diagonal eigenvalue matrix from function 'pcamat'
%@% verbose       Optional. Default is 'on'
%@%
%@% EXAMPLE
%@%       [E, D] = pcamat(vectors);
%@%       [nv, wm, dwm] = whitenv(vectors, E, D);
%@%
%@%
%@% This function is needed by FASTICA and FASTICAG
%@%
%@%   See also PCAMAT
%@
%@% @(#)$Id: whitenv.m,v 1.3 2003/10/12 09:04:43 jarmo Exp $
%@
%@% ========================================================
%@% Default value for 'verbose'
%@if nargin < 4, s_verbose = 'on'; end
%@
%@% Check the optional parameter verbose;
%@switch lower(s_verbose)
%@ case 'on'
%@  b_verbose = 1;
%@ case 'off'
%@  b_verbose = 0;
%@ otherwise
%@  error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
%@end
%@
%@% ========================================================
%@% In some cases, rounding errors in Matlab cause negative
%@% eigenvalues (elements in the diagonal of D). Since it
%@% is difficult to know when this happens, it is difficult
%@% to correct it automatically. Therefore an error is 
%@% signalled and the correction is left to the user.
%@if any (diag (D) < 0),
%@  error (sprintf (['[ %d ] negative eigenvalues computed from the' ...
%@		   ' covariance matrix.\nThese are due to rounding' ...
%@		   ' errors in Matlab (the correct eigenvalues are\n' ...
%@		   'probably very small).\nTo correct the situation,' ...
%@		   ' please reduce the number of dimensions in the' ...
%@		   ' data\nby using the ''lastEig'' argument in' ...
%@		   ' function FASTICA, or ''Reduce dim.'' button\nin' ...
%@		   ' the graphical user interface.'], ...
%@		  sum (diag (D) < 0)));
%@end
%@
%@% ========================================================
%@% Calculate the whitening and dewhitening matrices (these handle
%@% dimensionality simultaneously).
%@whiteningMatrix = inv (sqrt (D)) * E';
%@dewhiteningMatrix = E * sqrt (D);
%@
%@% Project to the eigenvectors of the covariance matrix.
%@% Whiten the samples and reduce dimension simultaneously.
%@if b_verbose, fprintf ('Whitening...\n'); end
%@newVectors =  whiteningMatrix * vectors;
%@
%@% ========================================================
%@% Just some security...
%@if ~isreal(newVectors)
%@  error ('Whitened vectors have imaginary values.');
%@end
%@
%@% Print some information to user
%@if b_verbose
%@  fprintf ('Check: covariance differs from identity by [ %g ].\n', ...
%@    max (max (abs (cov (newVectors', 1) - eye (size (newVectors, 1))))));
%@end
%@
%<-- ASCII ends here -->

