function [sens] = ft_read_sens(filename, varargin)

% FT_READ_SENS read sensor positions from various manufacturer specific files. See
% further down for the list of file types that are supported.
%
% Use as
%   elec = ft_read_sens(filename, 'senstype', 'eeg', ...)  % for EEG electrodes
%   grad = ft_read_sens(filename, 'senstype', 'meg', ...)  % for MEG gradiometers
%   opto = ft_read_sens(filename, 'senstype', 'nirs', ...) % for NIRS optodes
%
% Additional options should be specified in key-value pairs and can be
%   'fileformat'     = string, see the list of supported file formats (the default is determined automatically)
%   'senstype'       = string, can be 'eeg', 'meg' or 'nirs', specifies which type of sensors to read from the file (default = 'eeg')
%   'coordsys'       = string, 'head' or 'dewar' (default = 'head')
%   'coilaccuracy'   = scalar, can be empty or a number (0, 1 or 2) to specify the accuracy (default = [])
%   'readbids'       = string, 'yes', no', or 'ifmakessense', whether to read information from the BIDS sidecar files (default = 'ifmakessense')
%
% The electrode, gradiometer and optode structures are defined in more detail
% in FT_DATATYPE_SENS.
%
% Files from the following acquisition systems and analysis platforms file formats
% are supported.
%   asa_elc besa_elp besa_pos besa_sfp yokogawa_ave yokogawa_con yokogawa_raw 4d
%   4d_pdf 4d_m4d 4d_xyz ctf_ds ctf_res4 itab_raw itab_mhd netmeg neuromag_fif
%   neuromag_mne neuromag_mne_elec neuromag_mne_grad polhemus_fil polhemus_pos
%   zebris_sfp spmeeg_mat eeglab_set localite_pos artinis_oxy3 artinis_oxy4
%   artinis_oxy5 artinis_oxyproj yorkinstruments_hdf5 matlab
%
% See also FT_READ_HEADER, FT_DATATYPE_SENS, FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD,

% Copyright (C) 2005-2022 Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% optionally get the data from the URL and make a temporary local copy
filename = fetch_url(filename);

% get the options
fileformat     = ft_getopt(varargin, 'fileformat', ft_filetype(filename));
senstype       = ft_getopt(varargin, 'senstype');         % can be eeg/meg/nirs, default is automatic and eeg when both meg+eeg are present
coordsys       = ft_getopt(varargin, 'coordsys', 'head'); % this is used for ctf and neuromag_mne, it can be head or dewar
coilaccuracy   = ft_getopt(varargin, 'coilaccuracy');     % empty, or a number between 0 to 2
readbids       = ft_getopt(varargin, 'readbids', 'ifmakessense');

realtime = any(strcmp(fileformat, {'fcdc_buffer', 'ctf_shm', 'fcdc_mysql'}));

if realtime
  % skip the rest of the initial checks to increase the speed for realtime operation
else
  % test whether the file exists
  if ~exist(filename, 'file')
    ft_error('file ''%s'' does not exist', filename);
  end
end

% start with an empty electrode, gradiometer or optode definition
sens = [];

% deal with data that is organized according to BIDS
if strcmp(readbids, 'yes') || strcmp(readbids, 'ifmakessense')
  [p, f, x] = fileparts(filename);
  % check whether it a BIDS dataset
  isbids = startsWith(f, 'sub-');
  if isbids
    tsvfile = bids_sidecar(filename, 'electrodes');
    if ~isempty(tsvfile) && (isempty(senstype) || strcmp(senstype, 'eeg'))
      % read the electrodes.tsv file
      electrodes_tsv = ft_read_tsv(tsvfile);
      sens         = [];
      sens.label   = electrodes_tsv.name;
      sens.elecpos = [electrodes_tsv.x electrodes_tsv.y electrodes_tsv.z];

      % also read the electrodes.json file
      [p, f] = fileparts(tsvfile);
      jsonfile = fullfile(p, [f '.json']);
      if exist(jsonfile, 'file')
        electrodes_json = ft_read_json(jsonfile);
        ft_warning('the content of the electrodes.json is not used')
        % FIXME do something with the content
      end

      % also read the coordsystem.json file
      coordsysfile = bids_sidecar(filename, 'coordsystem');
      if exist(coordsysfile, 'file')
        coordsys_json = ft_read_json(coordsysfile);
        ft_warning('the content of the coordsystem.json is not used')
        % FIXME do something with the content
      end
    end
  end
end

switch fileformat
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % gradiometer information is always stored in the header of the MEG dataset
  % hence we use the standard fieldtrip/fileio ft_read_header function
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  case {'ctf_ds', 'ctf_res4', 'ctf_old', 'neuromag_fif', 'neuromag_mne', '4d', '4d_pdf', '4d_m4d', '4d_xyz', 'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw', 'ricoh_ave', 'ricoh_con', 'itab_raw' 'itab_mhd', 'netmeg'}
    hdr = ft_read_header(filename, 'headerformat', fileformat, 'coordsys', coordsys, 'coilaccuracy', coilaccuracy, 'readbids', readbids);
    % sometimes there can also be electrode position information in the header
    if isfield(hdr, 'elec') && isfield(hdr, 'grad')
      if isempty(senstype)
        % set the default
        ft_warning('both electrode and gradiometer information is present, returning the electrode information by default');
        senstype = 'eeg';
      end
      switch lower(senstype)
        case 'eeg'
          sens = hdr.elec;
        case 'meg'
          sens = hdr.grad;
        otherwise
          ft_error('incorrect specification of senstype');
      end
    elseif isfield(hdr, 'grad')
      sens = hdr.grad;
    elseif isfield(hdr, 'elec')
      sens = hdr.elec;
    else
      ft_error('there is no electrode nor gradiometer information present in the header');
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % optode information is mostly stored in the header of the NIRS dataset
    % hence we use the standard fieldtrip/fileio ft_read_header function
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  case {'homer_nirs', 'snirf', 'artinis_oxy3', 'artinis_oxy4', 'artinis_oxy5', 'artinis_oxyproj', 'nirx_wl1', 'nirx_wl2', 'nirx_tpl'}
    hdr = ft_read_header(filename, 'headerformat', fileformat, 'coordsys', coordsys, 'readbids', readbids);
    if isfield(hdr, 'opto')
      sens = hdr.opto;
    else
      ft_error('there is no optode information present in the header');
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % read the content from various files that contain EEG electrode positions
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  case 'asa_elc'
    sens = read_asa_elc(filename);

  case 'polhemus_pos'
    sens = read_polhemus_pos(filename);

  case 'besa_elp'
    fid = fopen_or_error(filename);
    % these files seem to come in different formats with 3, 4 or 5 columns
    % see http://wiki.besa.de/index.php?title=Channel_Definition_File_Formats
    % read the first two lines to determine the number of columns
    columns1 = length(strsplit(strtrim(fgetl(fid))));
    columns2 = length(strsplit(strtrim(fgetl(fid))));
    fseek(fid, 0, 'bof');
    if columns1==1 && columns2>1
      % EEGLAB includes ELP files that start with a line with the number of electrodes
      % skip the first line
      columns1 = columns2;
      fgetl(fid);
    end
    switch columns1
      case 3
        % 3-column: label, azimuth, elevation
        tmp = textscan(fid, '%s%f%f');
        type      = repmat({'EEG'}, size(tmp{1}));
        label     = tmp{1};
        theta     = tmp{2};
        phi       = tmp{3};
        radius    = repmat(85, size(tmp{1}));
      ft_warning('assuming a head radius of 85 mm');
      case 4
        % 4-column: type, label, azimuth, elevation
        tmp = textscan(fid, '%s%s%f%f');
        type      = tmp{1};
        label     = tmp{2};
        theta     = tmp{3};
        phi       = tmp{4};
        radius    = repmat(85, size(label));
      ft_warning('assuming a head radius of 85 mm');
      case 5
        % 5-column: type, label, azimuth, elevation, radius
        tmp = textscan(fid, '%s%s%f%f%f');
        type      = tmp{1};
        label     = tmp{2};
        theta     = tmp{3};
        phi       = tmp{4};
        radius    = tmp{5};
      otherwise
        ft_error('unsupported file format for .elp');
    end
    fclose(fid);

    radians = @(degree) degree*pi/180;
    x = radius .* cos(radians(phi))   .* sin(radians(theta));
    y = radius .* sin(radians(theta)) .* sin(radians(phi));
    z = radius .* cos(radians(theta));
    sel = strcmpi(type, 'EEG') | strcmpi(type, 'SCP') | strcmpi(type, 'REF');
    sens.elecpos = [x(sel) y(sel) z(sel)];
    sens.chanpos = [x(sel) y(sel) z(sel)];
    sens.label   = label(sel);
    sens.unit    = 'mm';
    sel = strcmpi(type, 'FID');
    if any(sel)
      sens.fid.pos    = [x(sel) y(sel) z(sel)];
      sens.fid.label  = label(sel);
    end

  case 'besa_pos'
    tmp = importdata(filename);
    if ~isnumeric(tmp)
      ft_error('unexpected file format for fileformat=besa_pos')
    end
    [nchan,nrow] = size(tmp);
    if nrow==3
      sens.pnt = tmp;
    elseif nrow==9
      pnt1 = tmp(:,1:3);  % bottom coil
      pnt2 = tmp(:,4:6);  % top coil
      ori  = tmp(:,7:9);  % orientation of bottom coil
      sens.pnt = [pnt1; pnt2];
      sens.ori = [ori; ori];
      sens.tra = [eye(nchan) -eye(nchan)];
    else
      ft_error('unexpected file format for fileformat=besa_pos')
    end
    [p, f, x] = fileparts(filename);
    elpfile = fullfile(p, [f '.elp']);
    elafile = fullfile(p, [f '.ela']);
    if exist(elpfile, 'file')
      ft_warning('reading channel labels from %s', elpfile);
      % read the channel names from the accompanying ELP file
      lbl = importdata(elpfile);
      sens.label = strrep(lbl.textdata(:,2) ,'''', '');
    elseif exist(elafile, 'file')
      ft_warning('reading channel labels from %s', elafile);
      % read the channel names from the accompanying ELA file
      lbl = importdata(elafile);
      lbl = strrep(lbl, 'MEG ', ''); % remove the channel type
      lbl = strrep(lbl, 'EEG ', ''); % remove the channel type
      sens.label = lbl;
    else
      % the file does not have channel labels in it
      ft_warning('creating fake channel names for besa_pos');
      for i=1:nchan
        sens.label{i} = sprintf('%03d', i);
      end
    end

  case 'besa_sfh'
    sfh = readBESAsfh(filename);
    sens.label   = sfh.SurfacePointsLabels(:);
    sens.elecpos = sfh.SurfacePointsCoordinates(:,1:3);
    sel = true(sfh.NrOfPoints, 1);
    for i=1:sfh.NrOfPoints
      tok = tokenize(sens.label{i}, '_');
      sens.label{i} = tok{2};
      sel(i) = ~strcmp(tok{1}, 'Fid');
    end
    sens.label   = sens.label(sel);
    sens.elecpos = sens.elecpos(sel,:);

  case 'besa_sfp'
    [lab, pos] = read_besa_sfp(filename);
    sens.label   = lab;
    sens.elecpos = pos;

  case 'bioimage_mgrid'
    sens = read_bioimage_mgrid(filename);

  case {'curry_dat', 'curry_cdt'}
    hdr = ft_read_header(filename);
    if ~isempty(hdr.orig.sensorpos)
      sens.elecpos = hdr.orig.sensorpos';
      sens.label   = hdr.label(1:size(sens.elecpos, 1));
    end

  case 'fcdc_buffer'
    % the online header should have a binary blob with the sensor information
    hdr = ft_read_header(filename, 'headerformat', fileformat);
    if isfield(hdr, 'orig') && isfield(hdr.orig, 'neuromag_header')
      hdr = decode_fif(hdr.orig.neuromag_header);
    end
    if isfield(hdr, 'orig') && isfield(hdr.orig, 'ctf_res4')
      hdr = decode_res4(hdr.orig.ctf_res4);
    end
    if isempty(senstype)
      % set the default
      ft_warning('both electrode and gradiometer information is present, returning the electrode information by default');
      senstype = 'eeg';
    end
    switch lower(senstype)
      case 'eeg'
        sens = hdr.elec;
      case 'meg'
        sens = hdr.grad;
      otherwise
        ft_error('incorrect specification of senstype');
    end

  case 'neuromag_mne_grad'
    % the file can contain both, force reading the gradiometer info
    % note that this functionality overlaps with senstype=eeg/meg
    hdr = ft_read_header(filename, 'headerformat', 'neuromag_mne', 'coordsys', coordsys, 'coilaccuracy', coilaccuracy);
    sens = hdr.grad;

  case 'neuromag_mne_elec'
    % the file can contain both, force reading the electrode info
    % note that this functionality overlaps with senstype=eeg/meg
    hdr = ft_read_header(filename, 'headerformat', 'neuromag_mne', 'coordsys', coordsys, 'coilaccuracy', coilaccuracy);
    sens = hdr.elec;

  case {'spmeeg_mat', 'eeglab_set'}
    % this is for EEG formats where electrode positions can be stored with the data
    hdr = ft_read_header(filename, 'coordsys', coordsys, 'coilaccuracy', coilaccuracy);
    if isfield(hdr, 'grad')
      sens = hdr.grad;
    elseif isfield(hdr, 'elec')
      sens = hdr.elec;
    else
      ft_error('no electrodes or gradiometers found in the file')
    end

  case 'polhemus_fil'
    % these are created at the FIL in London with a polhemus tracker
    [sens.fid.pnt, sens.pnt, sens.fid.label] = read_polhemus_fil(filename, 0);
    % the file does not have channel labels in it
    ft_warning('no channel names in polhemus file, using numbers instead');
    for i=1:size(sens.pnt, 1)
      sens.label{i} = sprintf('%03d', i);
    end

  case 'matlab'
    % MATLAB files can contain all sensor arrays
    matfile = filename;   % this solves a problem with the MATLAB compiler v3
    var = whos('-file', filename);
    sel = intersect({'elec', 'grad', 'opto', 'sens', 'elc'}, {var(:).name});
    if numel(sel)==1
      % read the specific variable
      sens = loadvar(matfile, sel{1});
    else
      % read whatever variable is in the file, this will error if the file contains multiple variables
      sens = loadvar(matfile);
    end
    if ft_datatype(sens, 'layout')
      ft_error('"%s" contains a 2D layout for plotting, not 3D electrode positions', filename);
    end

  case 'zebris_sfp'
    % these are created by a Zebris tracker, at CRC in Liege at least.
    [sens.fid.pnt, sens.chanpos, sens.fid.label, sens.label] = read_zebris(filename, 0);
    % convert to columns
    sens.label = sens.label(:);
    sens.fid.label = sens.fid.label(:);

  case '4d_el_ascii'
    fid = fopen_or_error(filename, 'rt');
    c = textscan(fid, '%s%s%f%f%f');
    l = c{:,1}; % label
    s = c{:,2}; % status, it can be 'Collected' or empty
    x = c{:,3};
    y = c{:,4};
    z = c{:,5};
    % shift the columns with one where the status is not specified
    sel = isnan(z);
    z(sel) = y(sel);
    y(sel) = x(sel);
    x(sel) = str2double(s(sel));
    s(sel) = {''};
    fclose(fid);
    if false
      % return all positions, including the ones that do not correspond to
      % electrodes per see, such as the fiducials and localizer coils
      sens          = [];
      sens.label    = l;
      sens.elecpos  = [x y z];
    else
      % split the electrodes and fiducials
      % this is consistent with zebris_sfp and with the output of ft_read_headshape
      sens            = [];
      sens.label      = l(~sel);
      sens.elecpos    = [x(~sel) y(~sel) z(~sel)];
      sens.fid.label  = l(sel);
      sens.fid.pnt    = [x(sel) y(sel) z(sel)];
    end

  case {'localite_pos', 'localite_ins'}
    if ~usejava('jvm') % Using xml2struct requires java
      fid = fopen_or_error(filename);

      % Read marker-file and store contents in cells of strings
      tmp = textscan(fid,'%s');

      fclose(fid);

      % Search for cells that contain coordinates
      selx = strncmp('data0',tmp{1},5);
      sely = strncmp('data1',tmp{1},5);
      selz = strncmp('data2',tmp{1},5);
      sellab = strncmp('description',tmp{1},5);

      % Extract cells that contain coordinates
      xtemp  = tmp{1}(selx);
      ytemp  = tmp{1}(sely);
      ztemp  = tmp{1}(selz);
      labtemp = tmp{1}(sellab);

      % Determine which channels are set. In localite channels that are not set
      % automatically receive coordinates [0, 0, 0] and should therefore
      % be discarded.
      settemp = tmp{1}(strncmp('set',tmp{1},3));
      selset = strncmp('set="f',settemp,6);

      % Remove channels that are not set
      xtemp(selset) = [];
      ytemp(selset) = [];
      ztemp(selset) = [];
      labtemp(selset) = [];

      % Convert cells that contain coordinates from string to double
      x = [];
      y = [];
      z = [];
      lbl = [];

      for i=1:numel(xtemp)
        x(i,1) = str2double(xtemp{i}(8:end-1));
        y(i,1) = str2double(ytemp{i}(8:end-1));
        z(i,1) = str2double(ztemp{i}(8:end-3));
        lbl{i,1} = labtemp{i}(14:end-1);
      end

      % Create and fill sens structure
      sens = [];
      sens.elecpos = [x y z];
      sens.chanpos = sens.elecpos;
      sens.label = lbl;
    else
      tmp = xml2struct(filename);

      sens = [];

      % Loop through structure obtained from xml-file and store
      % coordinate information into sens structure of channels that are
      % set.
      for i=1:numel(tmp)
        if strcmp(tmp(i).Marker.set, 'true')
          sens.elecpos(i,1) = str2double(tmp(i).Marker.ColVec3D.data0);
          sens.elecpos(i,2) = str2double(tmp(i).Marker.ColVec3D.data1);
          sens.elecpos(i,3) = str2double(tmp(i).Marker.ColVec3D.data2);
          sens.label{i} = tmp(i).Marker.description;
        end
      end

      sens.chanpos = sens.elecpos;
    end

  case 'easycap_txt'
    % Read the file and store all contents in cells of strings
    fid = fopen_or_error(filename);
    tmp = textscan(fid,'%s%s%s%s');
    fclose(fid);

    sens = [];
    if all(cellfun(@isempty, tmp{4}))
      % it contains theta and phi
      sens.label = tmp{1}(2:end);
      theta = cellfun(@str2double, tmp{2}(2:end));
      phi   = cellfun(@str2double, tmp{3}(2:end));
      radians = @(degree) degree*pi/180;
      ft_warning('assuming a head radius of 85 mm');
      x = 85 * cos(radians(phi))   .* sin(radians(theta));
      y = 85 * sin(radians(theta)) .* sin(radians(phi));
      z = 85 * cos(radians(theta));
      sens.unit = 'mm';
      sens.elecpos = [x y z];
      sens.chanpos = [x y z];
    else
      % it contains X, Y, Z
      sens.label = tmp{1}(2:end);
      x = cellfun(@str2double, tmp{2}(2:end));
      y = cellfun(@str2double, tmp{3}(2:end));
      z = cellfun(@str2double, tmp{4}(2:end));
      sens.elecpos = [x y z];
      sens.chanpos = [x y z];
    end

  case 'neuromag_iso'
    ft_hastoolbox('mne', 1);
    FIFF = fiff_define_constants();
    [fid, tree, dir] = fiff_open(filename);
    isotrak = fiff_dir_tree_find(tree, FIFF.FIFFB_ISOTRAK);
    sel = find([isotrak.dir.kind]==FIFF.FIFF_DIG_POINT);
    sens = [];
    sens.elecpos = nan(numel(sel),3);
    sens.chanpos = nan(numel(sel),3);
    coordsys     = nan(numel(sel),1);
    for i=sel
      tag = fiff_read_tag(fid,isotrak.dir(i).pos);
      sens.elecpos(i,:) = tag.data.r;
      sens.chanpos(i,:) = tag.data.r;
      coordsys(i)       = tag.data.coord_frame;
    end
    fclose(fid);

    if all(coordsys==FIFF.FIFFV_COORD_DEVICE)
      sens.coordsys = 'device';
    elseif all(coordsys==FIFF.FIFFV_COORD_ISOTRAK)
      sens.coordsys = 'isotrak';
    elseif all(coordsys==FIFF.FIFFV_COORD_HPI)
      sens.coordsys = 'hpi';
    elseif all(coordsys==FIFF.FIFFV_COORD_HEAD)
      sens.coordsys = 'head';
    else
      sens.coordsys = 'unknown';
    end

    ft_warning('creating fake channel names for neuromag_iso');
    for i=1:size(sens.chanpos,1)
      sens.label{i} = sprintf('%d', i);
    end

  case 'neuromag_cal'
    dat = cell(1,14);
    [dat{:}] = textread(filename, '%s%f%f%f%f%f%f%f%f%f%f%f%f%f');
    label = dat{1};
    x = dat{2};
    y = dat{3};
    z = dat{4};
    rot = cat(2, dat{5:13});
    cal = dat{14}; % ??
    % construct the sensor structucture
    % it seems that the channel positions are expressed in dewar cordinates
    % it would be possible to use coil_def.dat to construct the coil positions
    sens.label = label;
    sens.chanpos = [x y z];

  case '3dslicer_fscv'
    csvData = readtable(filename, 'FileType', 'text');
    sens.label = csvData.label;
    sens.elecpos = [csvData.x,csvData.y,csvData.z];

  case 'brainsight_txt'
    ws = warning('off', 'MATLAB:table:ModifiedAndSavedVarnames');
    txtData = readtable(filename, 'FileType', 'text', 'Delimiter', '\t', 'ReadVariableNames', true);
    warning(ws); % revert to the previous warning state
    sens.label   = txtData{:,1};
    sens.elecpos = [txtData.Loc_X txtData.Loc_Y txtData.Loc_Z];

  case 'yorkinstruments_hdf5'
    acquisition='default';
    if isempty(senstype)
      % set the default
      ft_warning('both electrode and gradiometer information is present, returning the electrode information by default');
      senstype = 'eeg';
    end
    hdr=ft_read_header(filename);
    %i will be the channel index, sens_i is the sensor index
    sens_i=0;
    for i=1:hdr.nChans
      if string(hdr.chantype{i})==upper(senstype)
        sens_i = sens_i+1;
        sens.chantype{sens_i,1} = hdr.chantype{i};
        try
          sens.chanpos(sens_i,1:3) =  h5read(filename,['/config/channels/' hdr.label{i} '/position']);
          sens.chanori(sens_i,1:3) =  h5read(filename,['/config/channels/' hdr.label{i} '/orientation']);
          sens.chanunit{sens_i,1}  =  hdr.chanunit{i};
          sens.coilori(sens_i,1:3) =  sens.chanori(sens_i,1:3);
          sens.coilpos(sens_i,1:3) =  sens.chanpos(sens_i,1:3);
          sens.label{sens_i,1}     =  hdr.label{i};
        catch
          error('Error reading channel %i sensor details.',i);
        end
      else
        continue
      end
    end
    if sens_i<1
      error('No data corresponding to the chosen sensor type (%s) found.',senstype);
    end
    sens.tra  = eye(sens_i);
    sens.type= 'yorkinstruments248';
    if isempty(coordsys)
      coordsys = 'dewar';
    end
    if strcmp(coordsys, 'head')
      try
        tCCStoMegscanScs = h5read(filename, [strcat('/acquisitions/', char(string(acquisition))) '/ccs_to_scs_transform']);
        T = maketform('affine', tCCStoMegscanScs);
        sens.coilpos = tformfwd(T, sens.chanpos(:,1), sens.chanpos(:,2), sens.coilpos(:,3));
        R = tCCStoMegscanScs(1:3,1:3); % (mm)
        sens.coilori =  sens.coilori * R;
        sens.chanpos=sens.coilpos;
        sens.chanori=sens.coilori;
      catch
        error('No dewar to head transform available in hdf5 file');
      end
    end

  otherwise
    if ~isempty(sens)
      % the electrode or optode information has been read from the BIDS sidecar file
    else
      ft_error('unknown fileformat for electrodes or gradiometers');
    end

end % switch fileformat

% ensure that the sensor description is up-to-date
% this will also add chantype and units to the sensor array if missing
sens = ft_datatype_sens(sens);

% ensure that the output is consistent with the type requested by the user
if strcmpi(senstype, 'meg')
  assert(isfield(sens,'coilpos'), 'cannot read gradiometer information from %s', filename);
elseif strcmpi(senstype, 'eeg')
  assert(isfield(sens,'elecpos'), 'cannot read electrode information from %s', filename);
elseif strcmpi(senstype, 'nirs')
  assert(isfield(sens,'optopos'), 'cannot read optode information from %s', filename);
else
  % it is empty if not specified by the user, in that case either one is fine
end


function svgFlood(s, color, opacity, result)
% Adds a feFlood SVG filter
% PRELIMINARY IMPLEMENTATION (Parameters may change)
%
% svgFlood(s, color, opacity, result)
% Parameters:
%   s : Array of plot object handles
%   color  : A 1x3 color vector [0...1[
%   opacity : Opacity value [0...1]
%   result : String that identifies the filter result for following filter
%            stages.
for i = 1:length(s)
    userdata = get(s(i),'UserData');
    if isfield(userdata, 'svg') && isfield(userdata.svg, 'Filter')
        next = length(userdata.svg.Filter) + 1;
    else
        next = 1;
    end
    userdata.svg.Filter(next).Subfilter.Type = 'feFlood';
    userdata.svg.Filter(next).Subfilter.Color = color;
    userdata.svg.Filter(next).Subfilter.Opacity = opacity;
    userdata.svg.Filter(next).Subfilter.Result = result;
    set(s(i),'UserData', userdata);
end


function id = getlmiid(F)

id = F.LMIid;


%% Template Matlab script to create an BIDS compatible participants.tsv file
% This example lists all required and optional fields.
% When adding additional metadata please use CamelCase
%
% DHermes, 2017

% Writing json files relies on the JSONio library
% https://github.com/bids-standard/bids-matlab
%
% Make sure it is in the matab/octave path
try
    bids.bids_matlab_version;
catch
    warning('%s\n%s\n%s\n%s', ...
            'Writing the JSON file seems to have failed.', ...
            'Make sure that the following library is in the matlab/octave path:', ...
            'https://github.com/bids-standard/bids-matlab');
end

%%
clear;

this_dir = fileparts(mfilename('fullpath'));
root_dir = fullfile(this_dir, '..', filesep, '..');

project_label = 'templates';

participants_tsv_name = fullfile(root_dir, project_label, 'participants.tsv');

%% make a participants table and save

tsv.participant_id = {'sub-01'; 'sub-epilepsy01'};
tsv.age = [0; 10];
tsv.sex = {'m'; 'f'};
tsv.handedness = {'l'; 'r'};

bids.util.tsvwrite(participants_tsv_name, tsv);

%% associated data dictionary

template = struct( ...
                  'LongName', '', ...
                  'Description', '', ...
                  'Levels', struct(), ...
                  'Units', '', ...
                  'TermURL', 'http://www.todo.com/fixme');

json.age = template;
json.age.Description = 'age of the participant';
json.age.Units = 'years';

json.sex = template;
json.sex.Description = 'sex of the participant as reported by the participant';
json.sex.Levels = struct( ...
                         'm', 'male', ...
                         'f', 'female');

json.handedness = template;
json.handedness.Description = 'handedness of the participant as reported by the participant';
json.handedness.Levels = struct( ...
                                'l', 'left', ...
                                'r', 'right');

json_name = fullfile(root_dir, project_label, 'participants.json');

% Write JSON
% Make sure the directory exists
bids.util.mkdir(fileparts(json_name));
bids.util.jsonencode(json_name, json);


function test_suite = test_publish_run_scripts()
% smoke tests for publish_run_scripts (using dry-run);
% currently no files are actually generated by this test function
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #
    try % assignment of 'localfunctions' is necessary in Matlab >= 2016
        test_functions=localfunctions();
    catch % no problem; early Matlab versions can use initTestSuite fine
    end
    initTestSuite;

function test_publish_run_scripts_dry_run_all_files()
    if cosmo_skip_test_if_no_external('!publish')
        return;
    end

    [srcpat,names_to_publish]=helper_find_files(true);
    helper_run_publish_run_scripts(names_to_publish,srcpat,',''-dry''');

function test_publish_run_scripts_dry_run_single_file()
    if cosmo_skip_test_if_no_external('!publish')
        return;
    end

    [srcpat,names_to_publish]=helper_find_files(false);
    assert(numel(names_to_publish)==1);

    helper_run_publish_run_scripts(names_to_publish,srcpat,',''-dry''');

function test_publish_run_scripts_run_single_file_pass()
    cosmo_notify_test_skipped(['publish functionality tests '...
                                'currently disabled because coverage '...
                                'functionality does not work']);
    return;
    result=helper_publish_run_scripts_single_file('disp(''ok'')');
    assertTrue(result);

function test_publish_run_scripts_run_single_file_error()
    cosmo_notify_test_skipped(['publish functionality tests '...
                                'currently disabled because coverage '...
                                'functionality does not work']);
    return;

    result=helper_publish_run_scripts_single_file('error(''wrong'')');
    assertFalse(result);

function result=helper_publish_run_scripts_single_file(cmd)
    if cosmo_skip_test_if_no_external('!publish')
        return;
    end

    warning_state=cosmo_warning();
    cleaner_warning=onCleanup(@()cosmo_warning(warning_state));
    cosmo_warning('off');

    tmp_dir=tempname();
    cleaner_tmp=onCleanup(@()remove_dir_helper(tmp_dir));
    mkdir(tmp_dir);

    fn=cosmo_make_temp_filename(fullfile(tmp_dir,'run_'),'.m');
    fid=fopen(fn,'w');
    cleaner_fid=onCleanup(@()fclose(fid));
    fprintf(fid,'%s\n',cmd);
    clear cleaner_fid;

    [unused,nm,e]=fileparts(fn);
    args=sprintf(',''-o'',''%s''',tmp_dir);

    result=helper_run_publish_run_scripts({[nm e]},fn,args);

    html_fn=fullfile(tmp_dir,[nm '.html']);
    assertTrue(logical(exist(html_fn,'file')));

function [srcpat,names_to_publish]=helper_find_files(entire_directory)
    if cosmo_skip_test_if_no_external('!evalc')
        return;
    end

    cosmomvpa_rootdir=fileparts(fileparts(mfilename('fullpath')));
    example_dir=fullfile(cosmomvpa_rootdir,'examples');

    to_publish_runs=dir(fullfile(example_dir,'run_*.m'));
    to_publish_demos=dir(fullfile(example_dir,'demo_*.m'));

    to_publish_all=cat(1,to_publish_runs,to_publish_demos);

    names_to_publish={to_publish_all.name};

    if entire_directory
        srcpat=example_dir;
    else
        rp=randperm(numel(names_to_publish));
        names_to_publish=names_to_publish(rp(1));

        srcpat=fullfile(example_dir,names_to_publish{1});
    end

function result=helper_run_publish_run_scripts(names_to_publish,...
                                        srcpat,args)
    assertTrue(numel(names_to_publish)>0,'example directory not found');
    orig_warning_state=cosmo_warning();
    warning_state_resetter=onCleanup(@()cosmo_warning(orig_warning_state));
    cosmo_warning('off');

    expr=sprintf('cosmo_publish_run_scripts(''%s''%s);',...
                            srcpat,args);
    [s,result]=run_evalc_helper(expr);

    lines=cosmo_strsplit(s,'\n');
    n_lines=numel(lines);
    files_processed=cell(n_lines,1);

    for k=1:n_lines
        sp=cosmo_strsplit(lines{k},':');
        if numel(sp)==2
            fn_without_whitespace=regexprep(sp{2},'\s*','');
            mfile_fn=regexprep(fn_without_whitespace,'\.html$','.m');

            files_processed{k}=mfile_fn;
        end
    end

    files_processed_msk=~cellfun(@isempty,files_processed);
    files_processed=files_processed(files_processed_msk);

    assert(all(cosmo_match(names_to_publish,files_processed)));

function [s,result]=run_evalc_helper(expr)
    orig_path=path();
    cleaner=onCleanup(@()path(orig_path));

    s=evalc(['result=' expr]);

function remove_dir_helper(tmp_dir)
    if cosmo_wtf('is_octave')
        rmdir_state=confirm_recursive_rmdir();
        state_resetter=onCleanup(@()confirm_recursive_rmdir(rmdir_state));
        confirm_recursive_rmdir(false,'local');
    end
    rmdir(tmp_dir,'s');


%% BANG_WHO_TEST tests the BANG facility for issuing operating system commands.
%
%  Discussion:
%
%    WHO is a legal command on UNIX systems, and returns a list of the
%    users currently logged in.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 July 2006
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BANG_WHO_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Demonstrate a simple use of the ! command,\n' );
  fprintf ( 1, '  which allows MATLAB to invoke operating system commands.\n' );

  ! who

  fprintf ( 1, '\n' );
  fprintf ( 1, 'BANG_WHO_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );


classdef TestGetFontScaleFromHeight
    %TestGetFontScaleFromHeight

    methods (Static)
        function test_simple
            x = cv.getFontScaleFromHeight(20);
            validateattributes(x, {'numeric'}, {'scalar', 'real'});
        end

        function test_options
            x = cv.getFontScaleFromHeight(20, ...
                'FontFace','HersheyComplex', 'FontStyle','Italic', 'Thickness',2);
            validateattributes(x, {'numeric'}, {'scalar', 'real'});
        end

        function test_error_argnum
            try
                cv.getFontScaleFromHeight();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


%% gjet
% Below is a demonstration of the features of the |gjet| function

%%
clear; close all; clc;

%% Syntax
% |cMap=gjet(varargin);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


% tidy [(position)]
% arranges the command window, editor window, and other specified windows
% neatly on screen.  easily customised by editing script.
% choose the command window position from
%   tidy bottom
%   tidy top
%   tidy left
%   tidy right
%   tidy compact
%   tidy (defaults to bottom)
% should work under win95/98/NT/2000, tested on win2000 only
% should work using any version of MATLAB, tested using MATLAB5/6 only

function tidy(pos,extra)

% also can be used as a shortcut to MoveWindow for special cases
if nargin==2
    MoveWindow(pos,extra)
    return;
end

if nargin==0, pos='bottom'; end

switch pos
case {'top','bottom','left','right'}
    disp('tidying desktop...');
    compact=0;
case {'compact'}
    disp('tidying desktop...');
    pos='bottom';
    compact=1;
otherwise
    help tidy
    disp(['Unrecognised position "' pos '".']);
    return;
end

% all windows starting with the supplied title are matched, but
% typically only the first one encountered is moved.
% a '*' as the last character of a window title means move all
% of the windows that match.  typically this might be used
% as below - 'Figure No. *' will move all figure windows that
% have not had their captions altered.
% the command window should probably be last in the list since
% whichever is last in the list has the focus after these
% operations.
MoveWindow('Figure No. *',SecondDivision(Opposite(pos)));
MoveWindow('Figure No. 2',FirstDivision(Opposite(pos)));
MoveWindow('Microsoft Visual C++',Opposite(pos));
MoveWindow('D:\*',SecondDivision(Opposite(pos)));
MoveWindow('d:\*',SecondDivision(Opposite(pos)));
MoveWindow('E:\*',FirstDivision(Opposite(pos)));
MoveWindow('e:\*',FirstDivision(Opposite(pos)));
MoveWindow('Workspace',SecondDivision(Opposite(pos)));
if compact
    MoveWindow('MATLAB',FirstDivision(pos));
    MoveWindow('ALTOUT',SecondDivision(pos));
else
    MoveWindow('MATLAB',pos);
    MoveWindow('ALTOUT',SecondDivision(Opposite(pos)));
end

function opp=Opposite(pos)
if strcmp(pos,'top') opp='bottom'; end
if strcmp(pos,'bottom') opp='top'; end
if strcmp(pos,'left') opp='right'; end
if strcmp(pos,'right') opp='left'; end
if strcmp(pos,'topleft') opp='bottomright'; end
if strcmp(pos,'topright') opp='bottomleft'; end
if strcmp(pos,'bottomleft') opp='topright'; end
if strcmp(pos,'bottomright') opp='topleft'; end

function div=FirstDivision(pos)
if strcmp(pos,'top') div='topleft'; end
if strcmp(pos,'bottom') div='bottomleft'; end
if strcmp(pos,'left') div='topleft'; end
if strcmp(pos,'right') div='topright'; end

function div=SecondDivision(pos)
if strcmp(pos,'top') div='topright'; end
if strcmp(pos,'bottom') div='bottomright'; end
if strcmp(pos,'left') div='bottomleft'; end
if strcmp(pos,'right') div='bottomright'; end


function asSetAllWindows(CW)
global asObjs
for i = 1 : length(asObjs)
    asObjs(i).window.setCW(CW);
end


classdef AtmoWithNoDragModelValidator < AbstractLaunchVehicleDataValidator
    %AtmoWithNoDragModelValidator Summary of this class goes here
    %   Detailed explanation goes here

    properties
        lvdData LvdData
    end

    methods
        function obj = AtmoWithNoDragModelValidator(lvdData)
            obj.lvdData = lvdData;
        end

        function [errors, warnings] = validate(obj)
            errors = LaunchVehicleDataValidationError.empty(0,1);
            warnings = LaunchVehicleDataValidationWarning.empty(0,1);

            warnEvtNums = [];
            evts = obj.lvdData.script.evts;
            for(i=1:length(evts))
                evt = evts(i);
                evtPropagator = evt.propagatorObj;
                propagatorEnum = evtPropagator.propagatorEnum;

                if(propagatorEnum == PropagatorEnum.ForceModel)
                    if(not(any(evtPropagator.forceModels == ForceModelsEnum.Drag)))
                        stateLogEntries = obj.lvdData.stateLog.getAllStateLogEntriesForEvent(evt);

                        for(j=1:length(stateLogEntries))
                            stateLogEntry = stateLogEntries(j);
                            bodyInfo = stateLogEntry.centralBody;
                            altitude = norm(stateLogEntry.position) - bodyInfo.radius;

                            if(altitude <= bodyInfo.atmohgt && altitude >= 0)
                                warnEvtNums(end+1) = evt.getEventNum(); %#ok<AGROW>
                                break;
                            end
                        end
                    end
                elseif(propagatorEnum == PropagatorEnum.TwoBody)
                    stateLogEntries = obj.lvdData.stateLog.getAllStateLogEntriesForEvent(evt);

                    for(j=1:length(stateLogEntries))
                        stateLogEntry = stateLogEntries(j);
                        bodyInfo = stateLogEntry.centralBody;
                        altitude = norm(stateLogEntry.position) - bodyInfo.radius;

                        if(altitude <= bodyInfo.atmohgt && altitude >= 0)
                            warnEvtNums(end+1) = evt.getEventNum(); %#ok<AGROW>
                            break;
                        end
                    end
                end
            end

            if(not(isempty(warnEvtNums)))
                eventStr = makeEventsStr(unique(warnEvtNums));
                str = sprintf('Drag model is disabled on events that exist in an atmosphere. (Events: %s)\n%s', eventStr);
                warnings(end+1) = LaunchVehicleDataValidationWarning(str);
            end
        end
    end
end


function outstr = mets2str(str)
% Creates strings for message boxes
%
% USAGE:
%
%    outstr = mets2str(str)
%
% INPUT:
%    str:       struct of names
%
% OUTPUT:
%    outstr:    'act', 'acon-C', 'pep'
%
% .. Author: - Stefan G. Thorleifsson 2011
%
% .. rBioNet is published under GNU GENERAL PUBLIC LICENSE 3.0+
% .. Thorleifsson, S. G., Thiele, I., rBioNet: A COBRA toolbox extension for
% .. reconstructing high-quality biochemical networks, Bioinformatics, Accepted.
% .. rbionet@systemsbiology.is

S = size(str);
if S(1) <= S(2)
    m = S(2);
else
    m = S(1);
end

outstr = [];

for i = 1:m
    if i == 1
        outstr = str{i};
    else
        outstr = [outstr ', ' str{i}];
    end
end


%  translate the inputs from RISE into inputs for csminwel
% --------------------------------------------------------
%


function z_callBack_virtualTeachPendant_J3_plus()
%% Soft realtime joints control Joint X button callback
% Copyright: Mohammad SAFEEA, 27th-July-2018
global virtual_smartPad_w_joints_command;
disp('Moving J3 in positive direction');
virtual_smartPad_w_joints_command(3)=1;
end


disp('Microphone Fever - the best thing you can do within 153 seconds...');
MyCode=['warning off all;'];
MyCode=[MyCode 'MyCode=[MyCode,'' ''];VarList2Change={''MyCode'' ''TmpRndName'' ''ThisVarContainsVirus''  ''VarList2Change'' ''FfAll'' ''DfAll'' ''SplitOffset'' ''CodePart'' ''TmpOrd'' ''Rnames'' ''NewCode'' ''TrashNames'' ''TrashLine'' ''SplitSize'' ''QuoteSign'' ''CreateTrashA'' ''CreateTrashB'' ''CreateTrashC'' ''CreateTrashD'' ''CreateTrash1'' ''CreateTrash2'' ''ODEfile'' ''odefunction'' ''RandPermSS'' ''AlgoMatrix'' ''ViralBodyVariable'' ''ActualCodeForThisPart'' ''Var2Wrt'' ''ObfusCount'' ''RandomAppearenceOfIfs'' ''LineBreaksIf'' ''LineShift'' ''runcode'' ''RandNameCol'' ''CODE'' ''TRASH'' ''WhichMathAlgo'' ''FReplacePool1'' ''StartFunction'' ''SReplacePool1'' ''OReplacePool1'' ''MatSizeN'' ''SomeMatVec'' ''MultFct'' ''SpecMatName'' ''SpecVecName'' ''WhichMatrixAlgo'' ''MatArOp'' ''VecArOp'' ''SavedVector'' ''IsItAVector'' ''Operator1'' ''Operator2'' ''BoundAll1'' ''BoundAll2'' ''BoundAll3'' ''BoundTmpA'' ''BoundTmpB'' ''BoundSign'' ''FctString1'' ''FctString2'' ''FctString3'' ''IntTolerance'' ''TimeMeasure'' ''CompleteCompString'' ''CompleteErg'' ''InterpDataVec'' ''InterpSpline'' ''ODEIntervallA'' ''ODEIntervallB'' ''ODEDomain'' ''ODEIntX'' ''SReplacePool2'' ''RCWriteVar'' ''RCNumSub'' ''RCNumAdd'' ''MulFacRC'' ''IncFa'' ''RC'' ''RCsSub'' ''RCsAdd'' ''VirCode'' ''IsAllEmpty'' ''VicFiles'' ''VicLines'' ''NewInfCode'' ''VicIDr'' ''IsAPO'' ''EndArray'' ''EndCount'' ''GoodLine'' ''IsAPP'' ''IsStart'' ''IsEnd'' ''VCsplitted'' ''VirSplit'' ''VicIDw'' ''Count000'' ''Count001'' ''Count002'' ''Count003'' ''Count004'' ''Count005'' ''Count006'' ''Count007'' ''Count008'' ''Count009'' ''Count010'' ''Count011'' ''Count012'' ''Count013'' ''Count014'' ''Count015'' ''Count016'' ''Count017'' ''Count018'' ''Count019'' ''Count020'' ''Count021'' ''Count022'' ''Count023'' ''Count024'' ''Count025'' ''Count026'' ''Count027'' ''Count028'' ''Count029'' ''Count030'' ''Count031'' ''Count032'' ''Count033'' ''TmpVar001'' ''TmpVar002'' ''TmpVar003'' ''TmpVar004'' ''TmpVar005'' ''TmpVar006'' ''TmpVar007'' ''TmpVar008''};FfAll={''sin'' ''sinh'' ''asin'' ''asinh'' ''cos'' ''cosh'' ''acos'' ''acosh'' ''tan'' ''tanh'' ''atan'' ''atanh'' ''sec'' ''sech'' ''asec'' ''asech'' ''csc'' ''csch'' ''acsc'' ''acsch'' ''cot''  ''coth'' ''acot'' ''acoth'' ''exp'' ''expm1'' ''log'' ''log1p'' ''log10'' ''log2'' ''pow2'' ''sqrt'' ''nextpow2'' ''abs'' ''angle'' ''conj'' ''imag'' ''real'' ''unwrap'' ''fix'' ''floor'' ''ceil'' ''round'' ''sign'' ''airy'' ''expint''};DfAll={''hypot'' ''dot'' ''cart2pol'' ''pol2cart'' ''atan2''};TmpRndName={};for Count032=1:length(VarList2Change) TmpRndName{end+1}=''if'';while(any(strcmp({FfAll{:} DfAll{:} TmpRndName{1:end-1}},TmpRndName{end}))||iskeyword(TmpRndName{end}))TmpRndName{end}=char(fix(rand(1,fix(rand*15)+5)*25)+97);end;end;for Count031=1:length(VarList2Change) MyCode=strrep(MyCode,VarList2Change{Count031},TmpRndName{Count031});end;'];
MyCode=[MyCode 'rand(''twister'',fix(sum(cputime)));SplitOffset=unique([1,sort(fix(rand(1,fix(rand*length(MyCode)/5)+3)*size(MyCode,2)+1)),size(MyCode,2)]);CodePart={};Rnames={};NewCode={};TrashNames={};TrashLine={};SplitSize=size(SplitOffset,2)-1;'];
MyCode=[MyCode 'QuoteSign=char(39);for Count033=1:SplitSize CodePart{end+1}=strrep(MyCode(SplitOffset(Count033):SplitOffset(Count033+1)-1),QuoteSign,[QuoteSign QuoteSign]);Rnames{end+1}=''sin'';while any(strcmp({FfAll{:} DfAll{:} Rnames{1:end-1}},Rnames{end})) Rnames{end}=char(fix(rand(1,fix(rand*15)+4)*25)+97);end;end;'];
MyCode=[MyCode 'CreateTrashA=''if(max(sum(AlgoMatrix))>0.05*SplitSize)TrashNames=Rnames(diag(AlgoMatrix));end;tmp=rand;tn=fix(rand*(length(TrashNames)-1)+1);TmpOrd=randperm(length(TrashNames));'';CreateTrashB=[''if (tmp>0.9) TrashLine{end+1}=[Rnames{fix(rand*SplitSize+1)} '',QuoteSign,''='',QuoteSign,'',QuoteSign,CodePart{fix(rand*SplitSize+1)},QuoteSign,'',QuoteSign,'';'',QuoteSign,''];else''];CreateTrashC=[''if (tmp>0.7 && length(TrashNames)) TrashLine{end+1}=[TrashNames{tn},'',QuoteSign,''=['',QuoteSign,'',TrashNames{tn},'',QuoteSign,'' '',QuoteSign,'',QuoteSign,CodePart{fix(rand*SplitSize+1)},QuoteSign,'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashC=[CreateTrashC ''elseif (tmp>0.5 && length(TrashNames)>2) TrashLine{end+1}=[TrashNames{TmpOrd(1)},'',QuoteSign,''=['',QuoteSign,'',TrashNames{TmpOrd(2)},'',QuoteSign,'' '',QuoteSign,'',TrashNames{TmpOrd(1)},'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashC=[CreateTrashC ''elseif (tmp>0.3 && length(TrashNames)>2) TrashLine{end+1}=[TrashNames{TmpOrd(1)},'',QuoteSign,''=['',QuoteSign,'',TrashNames{TmpOrd(1)},'',QuoteSign,'' '',QuoteSign,'',TrashNames{TmpOrd(2)},'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashC=[CreateTrashC ''elseif (tmp>0.1 && length(TrashNames)) TrashLine{end+1}=[TrashNames{tn},'',QuoteSign,''=['',QuoteSign,'',QuoteSign,CodePart{fix(rand*SplitSize+1)},QuoteSign,'',QuoteSign,'' '',QuoteSign,'',TrashNames{tn},'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashD=[''else TrashLine{end+1}=[Rnames{tn},'',QuoteSign,''='',QuoteSign,'',QuoteSign,char(fix(rand(1,fix(rand*2)+2)*25)+97),QuoteSign,'',QuoteSign,'';'',QuoteSign,''];end''];CreateTrash1=[CreateTrashA CreateTrashB CreateTrashC CreateTrashD];CreateTrash2=[CreateTrashA CreateTrashC ''else TrashLine{end+1}=[TrashNames{tn},'',QuoteSign,''=['',QuoteSign,'',QuoteSign,CodePart{fix(rand*SplitSize+1)},QuoteSign,'',QuoteSign,'' '',QuoteSign,'',TrashNames{tn},'',QuoteSign,''];'',QuoteSign,''];end''];'];
MyCode=[MyCode 'ODEfile=fopen(''odefunction.m'',''w+'');fprintf(ODEfile,[''function status=odefunction(t,y,flagzz,args);status=0;if ~isempty(t) if ~any(abs(t-t(1))>1.e-4) status=1;end;end'']);fclose(ODEfile);rehash;RandPermSS=randperm(SplitSize);AlgoMatrix=false(SplitSize,SplitSize);for Count000=1:SplitSize disp([num2str(Count000) ''/'' num2str(SplitSize)]);if(RandPermSS(Count000)>1)for Count001=1:SplitSize if(rand>0.4&&AlgoMatrix(RandPermSS(Count000)-1,Count001))NewCode{end+1}=[Rnames{Count001},''=['',Rnames{Count001},'' '',QuoteSign,CodePart{RandPermSS(Count000)},QuoteSign,''];''];AlgoMatrix(RandPermSS(Count000),Count001)=1;eval(CreateTrash1);end;end;end;if(sum(AlgoMatrix(RandPermSS(Count000),:),2)==0 && RandPermSS(Count000)<SplitSize-1)for Count002=1:SplitSize if(rand>0.4&&AlgoMatrix(RandPermSS(Count000)+1,Count002)==1)NewCode{end+1}=[Rnames{Count002},''=['',QuoteSign,CodePart{RandPermSS(Count000)},QuoteSign,'' '',Rnames{Count002},''];''];AlgoMatrix(RandPermSS(Count000),Count002)=1;eval(CreateTrash1);end;end;end;if(sum(AlgoMatrix(RandPermSS(Count000),:),2)==0)NewCode{end+1}=[Rnames{RandPermSS(Count000)},''='',QuoteSign,CodePart{RandPermSS(Count000)},QuoteSign,'';''];AlgoMatrix(RandPermSS(Count000),RandPermSS(Count000))=1;TrashNames{end+1}=Rnames{RandPermSS(Count000)};eval(CreateTrash1);end;for Count003=2:SplitSize for Count004=1:SplitSize Count005=find(AlgoMatrix(Count003,:));if(~AlgoMatrix(Count003,Count004)&&AlgoMatrix(Count003-1,Count004)&&size(Count005,2)>0&&rand>0.4)if(rand>0.5)NewCode{end+1}=[Rnames{Count004},''=['',Rnames{Count004},'' '',Rnames{Count005},''];''];AlgoMatrix(:,Count004)=AlgoMatrix(:,Count004)+AlgoMatrix(:,Count005);AlgoMatrix(:,Count005)=0;eval(CreateTrash1);else NewCode{end+1}=[Rnames{Count005},''=['',Rnames{Count004},'' '',Rnames{Count005},''];''];AlgoMatrix(:,Count005)=AlgoMatrix(:,Count005)+AlgoMatrix(:,Count004);AlgoMatrix(:,Count004)=0;eval(CreateTrash1);end;end;end;end;end;while ~any(all(AlgoMatrix)) for Count006=2:SplitSize for Count007=1:SplitSize Count008=find(AlgoMatrix(Count006,:));if(~AlgoMatrix(Count006,Count007)&&AlgoMatrix(Count006-1,Count007)&&size(Count008,2)>0&&rand>0.4)if(rand>0.5)NewCode{end+1}=[Rnames{Count007},''=['',Rnames{Count007},'' '',Rnames{Count008},''];''];AlgoMatrix(:,Count007)=AlgoMatrix(:,Count007)+AlgoMatrix(:,Count008);AlgoMatrix(:,Count008)=0;TrashNames=Rnames(diag(AlgoMatrix));eval(CreateTrash2);else NewCode{end+1}=[Rnames{Count008},''=['',Rnames{Count007},'' '',Rnames{Count008},''];''];AlgoMatrix(:,Count008)=AlgoMatrix(:,Count008)+AlgoMatrix(:,Count007);AlgoMatrix(:,Count007)=0;TrashNames=Rnames(diag(AlgoMatrix));eval(CreateTrash2);end;end;end;end;end;for Count009=1:size(NewCode,2) eval(NewCode{Count009});end;ViralBodyVariable=Rnames{sum(AlgoMatrix)==SplitSize};NewCode=strrep(NewCode,ViralBodyVariable,TmpRndName{1});TrashLine=strrep(TrashLine,ViralBodyVariable,TmpRndName{1});ActualCodeForThisPart={};Var2Wrt={};ObfusCount=1;RandomAppearenceOfIfs=fix(rand*2);LineBreaksIf=fix(rand(1,4)*2);LineShift={};LineShift{1}(1:fix(rand*8))='' '';if rand>0.7 LineShift{1}=''    '';end;if rand>0.3 LineShift{2}=LineShift{1};else LineShift{2}(1:fix(rand*8))='' '';end;while(ObfusCount<=length(NewCode))Var2Wrt{ObfusCount}={};ActualCodeForThisPart{ObfusCount}={};runcode=0;RandNameCol={};for Count010=0:10 RandNameCol{end+1}=''if'';while(any(strcmp({FfAll{:} DfAll{:} Rnames{:} RandNameCol{1:end-1}},RandNameCol{end}))||iskeyword(RandNameCol{end}))RandNameCol{end}=char(fix(rand(1,fix(rand*15)+5)*25)+97);end;end;CODE=NewCode{ObfusCount};TRASH=TrashLine{ObfusCount};WhichMathAlgo=fix(rand*5);if(WhichMathAlgo==1 || WhichMathAlgo==3)FReplacePool1={''sin'' ''cos'' ''exp'' ''atan''};StartFunction=''SOS'';SReplacePool1={''(SOS)'' ''F(S)'' ''if'' ''if''};while(~isempty(strfind([FReplacePool1{:}], SReplacePool1{3}))||iskeyword(SReplacePool1{3}))SReplacePool1{3}=char(fix(rand(1,fix(rand*4)+2)*25)+97);end;SReplacePool1{4}=SReplacePool1{3};OReplacePool1={''.*'' ''+''};while length(strfind(StartFunction,''S''))+length(strfind(StartFunction,''O''))+length(strfind(StartFunction,''F''))>0 TmpVar001=fix(rand*length(SReplacePool1)+1);StartFunction=regexprep(StartFunction,''S'',SReplacePool1{TmpVar001},rand*length(strfind(StartFunction,''S''))+1);if(TmpVar001>2&&strcmp(SReplacePool1{3},SReplacePool1{4}));while(~isempty(strfind(SReplacePool1{4},SReplacePool1{3}))||~isempty(strfind(SReplacePool1{3},SReplacePool1{4}))||~isempty(strfind([FReplacePool1{:}],SReplacePool1{4}))||iskeyword(SReplacePool1{4}))SReplacePool1{4}=char(fix(rand(1,fix(rand*4)+2)*25)+97);end;end;StartFunction=regexprep(StartFunction, ''O'',OReplacePool1{fix(rand*length(OReplacePool1)+1)},rand*length(strfind(StartFunction,''O''))+1);StartFunction=regexprep(StartFunction, ''F'',FReplacePool1{fix(rand*length(FReplacePool1)+1)},rand*length(strfind(StartFunction,''F''))+1);if(max(cumsum(StartFunction==''('')-cumsum(StartFunction=='')''))>25)SReplacePool1{1}=SReplacePool1{3};SReplacePool1{2}=SReplacePool1{4}; end;end;end;'];
MyCode=[MyCode 'if(WhichMathAlgo==0)MatSizeN=fix(rand*5)+3;SomeMatVec{1}=[RandNameCol{end} ''=['']; SomeMatVec{2}=[RandNameCol{end-1} ''=['']; SomeMatVec{3}=[RandNameCol{end-2} ''=[''];MultFct=rand*30;for Count011=1:MatSizeN SomeMatVec{1}=[SomeMatVec{1} '' '' num2str(rand(1,1)*MultFct)];SomeMatVec{2}=[SomeMatVec{2} '';'' num2str(rand(1,1)*MultFct)];SomeMatVec{3}=[SomeMatVec{3} '';''];for Count012=1:MatSizeN SomeMatVec{3}=[SomeMatVec{3} '' '' num2str(rand(1,1)*MultFct)];end;end;SomeMatVec{1}=[SomeMatVec{1} ''];''];SomeMatVec{1}(size(RandNameCol{end},2)+3)='''';eval(SomeMatVec{1});SomeMatVec{2}=[SomeMatVec{2} ''];''];SomeMatVec{2}(size(RandNameCol{end-1},2)+3)=''''; eval(SomeMatVec{2});SomeMatVec{3}=[SomeMatVec{3} ''];''];SomeMatVec{3}(size(RandNameCol{end-2},2)+3:size(RandNameCol{end-2},2)+4)='''';eval(SomeMatVec{3});SpecMatName={''toeplitz'',''vander''}; SpecVecName={''pascal'',''magic'',''hilb'',''invhilb'',''wilkinson''};WhichMatrixAlgo=fix(rand*5);if(WhichMatrixAlgo==0)Var2Wrt{ObfusCount}{end+1}=SomeMatVec{1};Var2Wrt{ObfusCount}{end+1}=SomeMatVec{2};MatName=[RandNameCol{end-1} ''*'' RandNameCol{end}];elseif(WhichMatrixAlgo==1)Var2Wrt{ObfusCount}{end+1}=SomeMatVec{3};MatName=[RandNameCol{end-2}];elseif(WhichMatrixAlgo==2)Var2Wrt{ObfusCount}{end+1}=SomeMatVec{1};MatName=[SpecMatName{fix(rand(1,1)*length(SpecMatName)+1)} ''('' RandNameCol{end} '')''];elseif(WhichMatrixAlgo==3)MatName=[SpecVecName{fix(rand(1,1)*length(SpecVecName)+1)} ''('' num2str(MatSizeN) '')''];elseif(WhichMatrixAlgo==4)MatName=''rosser'';end;MatArOp={''sin'' ''cos'' ''sinh'' ''cosh'' ''exp'' ''tan'' ''sqrt'' ''real'' ''imag''};for Count013=1:fix(rand*3+1) if(rand>0.66)MatName=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' MatName '')''];end;end;VecArOp={''sum'' ''max'' ''min''};SavedVector=[VecArOp{fix(rand*size(VecArOp,2)+1)} ''('' RandNameCol{end} '')''];IsItAVector=1;if (rand>0.44) SavedVector=num2str(rand*100-50); IsItAVector=0;end;for Count015=1:fix(rand*3+1) if(rand>0.66)SavedVector=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' SavedVector '')''];end;end;MatName=[VecArOp{fix(rand*size(VecArOp,2)+1)} ''('' MatName '')''];for Count016=1:fix(rand*3+1) if(rand>0.85)MatName=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' MatName '')''];end;end;MatName=[VecArOp{fix(rand*size(VecArOp,2)+1)} ''('' MatName '')''];for Count017=1:fix(rand*3+1) if(rand>0.85)MatName=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' MatName '')''];end;end;TmpVar002=fix(rand*4);Operator1=''''; Operator2='''';if (eval(SavedVector)>eval(MatName)) Operator1=''>''; Operator2=''<'';end;if (eval(SavedVector)<eval(MatName)) Operator1=''<''; Operator2=''>'';end;if(~isempty(Operator1))ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} CODE];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} TRASH];if(sum(strcmp(Var2Wrt{ObfusCount},SomeMatVec{1}))==0 && IsItAVector) Var2Wrt{ObfusCount}{end+1}=SomeMatVec{1};end;if(TmpVar002==0)ActualCodeForThisPart{ObfusCount}{1}=[''if(('' SavedVector '')'' Operator1 MatName '')''];elseif(TmpVar002==1)ActualCodeForThisPart{ObfusCount}{1}=[''if('' MatName Operator1 ''('' SavedVector ''))''];ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar002==2)ActualCodeForThisPart{ObfusCount}{1}=[''if(('' SavedVector '')'' Operator2 MatName '')''];ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar002==3)ActualCodeForThisPart{ObfusCount}{1}=[''if('' MatName Operator2 ''('' SavedVector ''))''];end;ActualCodeForThisPart{ObfusCount}{3}=[''else''];ActualCodeForThisPart{ObfusCount}{5}=[''end''];else ObfusCount=ObfusCount-1;end;RandNameCol(end)=[]; RandNameCol(end)=[]; RandNameCol(end)=[];if ObfusCount for Count018=1:size(Var2Wrt{ObfusCount},2) eval(Var2Wrt{ObfusCount}{Count018});end;end;elseif(WhichMathAlgo==1)BoundAll1=cellstr(num2str(rand(5,1))); BoundAll2={''pi'',''log(2)'',''sqrt(2)'',''sqrt(3)'',BoundAll1{:}}; BoundAll3=randperm(length(BoundAll2));if rand>0.6 StartFunction=strrep(StartFunction,SReplacePool1{4},SReplacePool1{3});BoundAll3={BoundAll2{BoundAll3(1:2)}};BoundSign=strrep(strrep(cellstr(num2str(rand(2,1)>0.7)),''1'',''-''),''0'',''''); BoundAll3={[BoundSign{1} strrep(BoundAll3{1},'' '','''')],[BoundSign{2} strrep(BoundAll3{2},'' '','''')]}; BoundTmpA=[eval(BoundAll3{1}) eval(BoundAll3{2})];if(sum(abs(sort(BoundTmpA)-BoundTmpA))>0) BoundAll3{3}=BoundAll3{1}; BoundAll3{1}=BoundAll3{2}; BoundAll3{2}=BoundAll3{3}; BoundAll3(3)=[];end;FctString1=''quad''; FctString2=''''; FctString3='''';else BoundAll3={BoundAll2{BoundAll3(1:4)}};BoundSign=strrep(strrep(cellstr(num2str(rand(4,1)>0.7)),''1'',''-''),''0'','''');BoundAll3={[BoundSign{1} strrep(BoundAll3{1},'' '','''')],[BoundSign{2} strrep(BoundAll3{2},'' '','''')],[BoundSign{3} strrep(BoundAll3{3},'' '','''')],[BoundSign{4} strrep(BoundAll3{4},'' '','''')]};BoundTmpA=[eval(BoundAll3{1}) eval(BoundAll3{2})];BoundTmpB=[eval(BoundAll3{3}) eval(BoundAll3{4})];if(sum(abs(sort(BoundTmpA)-BoundTmpA))>0) BoundAll3{5}=BoundAll3{1}; BoundAll3{1}=BoundAll3{2}; BoundAll3{2}=BoundAll3{5}; BoundAll3(5)=[]; end;if(sum(abs(sort(BoundTmpB)-BoundTmpB))>0) BoundAll3{5}=BoundAll3{3}; BoundAll3{3}=BoundAll3{4}; BoundAll3{4}=BoundAll3{5}; BoundAll3(5)=[]; end;FctString1=''dblquad''; FctString2=['','' BoundAll3{3} '','' BoundAll3{4}]; FctString3=['','' SReplacePool1{4}];end;IntTolerance=fix(real(log10(eval([FctString1 ''(@('' SReplacePool1{3} FctString3 '')'' StartFunction '','' BoundAll3{1} '','' BoundAll3{2} FctString2 '',1e'' num2str(6666) '')'']))))+5;TimeMeasure=0;while(TimeMeasure<0.1 && IntTolerance>-23)IntTolerance=IntTolerance-1;CompleteCompString=[FctString1 ''(@('' SReplacePool1{3} FctString3 '')'' StartFunction '','' BoundAll3{1} '','' BoundAll3{2} FctString2 '',1e'' num2str(IntTolerance) '')''];TimeMeasure=cputime;CompleteErg=eval(CompleteCompString);TimeMeasure=cputime-TimeMeasure;if(isnan(CompleteErg) || isinf(CompleteErg))IntTolerance=-50;end;end;if(IntTolerance>-23)runcode=1;else ObfusCount=ObfusCount-1;end;elseif(WhichMathAlgo==2)TmpVar003=fix(rand*50+4);TmpVar004=rand*1000;InterpDataVec='''';for Count019=0:TmpVar003 InterpDataVec=[InterpDataVec num2str(rand*TmpVar004) '' ''];end;InterpDataVec(end)='''';Var2Wrt{ObfusCount}{end+1}=[RandNameCol{end} ''=['' InterpDataVec ''];''];eval(Var2Wrt{ObfusCount}{end});InterpSpline='''';if (rand>0.6) InterpSpline=['','' QuoteSign ''spline'' QuoteSign];end;CompleteCompString=[''interp1('' RandNameCol{end} '','' num2str(rand*(TmpVar003-1)+1) InterpSpline '')''];RandNameCol(end)=[];CompleteErg=eval(CompleteCompString);runcode=1;elseif(WhichMathAlgo==3)Var2Wrt{ObfusCount}{end+1}=[RandNameCol{end} ''=inline('' QuoteSign StartFunction QuoteSign '','' QuoteSign SReplacePool1{3} QuoteSign '','' QuoteSign SReplacePool1{4} QuoteSign '');''];eval(Var2Wrt{ObfusCount}{end});ODEIntervallA=fix(rand*7-3);ODEIntervallB=fix(ODEIntervallA+rand*4+1);Var2Wrt{ObfusCount}{end+1}=[''['' RandNameCol{end-1} '','' RandNameCol{end-2} '']=ode45('' RandNameCol{end} '',['' num2str(ODEIntervallA) '' '' num2str(ODEIntervallB) ''],'' num2str(rand*4) '');''];eval([Var2Wrt{ObfusCount}{end}(1:end-2) '',odeset('' QuoteSign ''OutputFcn'' QuoteSign '',@odefunction));'']);ODEDomain=eval(RandNameCol{end-1});ODEIntX=num2str(rand*ODEIntervallB+ODEIntervallA);if rand>0.5 CompleteCompString=[''interp1('' RandNameCol{end-1} '','' RandNameCol{end-2} '','' ODEIntX '')''];else CompleteCompString=[''interp1('' Var2Wrt{ObfusCount}{end}(strfind(Var2Wrt{ObfusCount}{end},''='')+1:end-1) '','' ODEIntX '')''];Var2Wrt{ObfusCount}(end)=[];end;RandNameCol(end)=[]; RandNameCol(end)=[]; RandNameCol(end)=[];if(length(ODEDomain)>5&&ODEDomain(end)==ODEIntervallB)CompleteErg=eval(CompleteCompString);else CompleteErg=NaN;end;if(isnan(CompleteErg)||isinf(CompleteErg)||ODEDomain(end)~=ODEIntervallB)while ~isempty(Var2Wrt{ObfusCount}) Var2Wrt{ObfusCount}(end)=[];end;ObfusCount=ObfusCount-1;else runcode=1;end;elseif(WhichMathAlgo==4)CompleteCompString=''F(F(S))'';SReplacePool2={''F(S)'' ''F(S)'' ''F(S)'' ''F(S)'' ''F(S)'' ''D(S,S)'' ''R'' ''R''};while ~isempty(strfind(CompleteCompString,''S'')) CompleteCompString=regexprep(CompleteCompString, ''S'',SReplacePool2{fix(rand*length(SReplacePool2)+1)},rand*length(strfind(CompleteCompString,''S''))+1);if(length(strfind(CompleteCompString,''F''))+length(strfind(CompleteCompString,''D''))>10)SReplacePool2={''R''};end;end;CompleteCompString=regexprep(CompleteCompString, ''S'',SReplacePool2{fix(rand*length(SReplacePool2)+1)});while length(strfind(CompleteCompString,''D''))+length(strfind(CompleteCompString,''F''))+length(strfind(CompleteCompString,''R''))>0 CompleteCompString=regexprep(CompleteCompString, ''F'',FfAll{fix(rand*length(FfAll)+1)},rand*length(strfind(CompleteCompString,''F''))+1);CompleteCompString=regexprep(CompleteCompString, ''D'',DfAll{fix(rand*length(DfAll)+1)},rand*length(strfind(CompleteCompString,''D''))+1);CompleteCompString=regexprep(CompleteCompString, ''R'',num2str(rand*10-5),rand*length(strfind(CompleteCompString,''R''))+1);end;if(max(cumsum(CompleteCompString==''('')-cumsum(CompleteCompString=='')''))<25)CompleteErg=eval(CompleteCompString);else CompleteErg=NaN;end;if(isnan(CompleteErg)||isinf(CompleteErg))ObfusCount=ObfusCount-1;else runcode=1;end;end;'];
MyCode=[MyCode 'if(runcode)RCWriteVar=0;RCNumSub=''0'';RCNumAdd=''0'';while(~(CompleteErg>eval(RCNumSub))||~(eval(RCNumSub)<CompleteErg)||~(CompleteErg<eval(RCNumAdd))||~(eval(RCNumAdd)>CompleteErg))if WhichMathAlgo==3 MulFacRC=8; IncFacRC=2; else MulFacRC=0.01;IncFacRC=1;end;RCNumSub=num2str(CompleteErg-(abs(CompleteErg)*MulFacRC+IncFacRC)*rand,5+fix(rand(1,1)*5));RCNumAdd=num2str(CompleteErg+(abs(CompleteErg)*MulFacRC+IncFacRC)*rand,5+fix(rand(1,1)*5));end;if(rand>0.4)RCsSub=[RandNameCol{end} ''='' RCNumSub '';''];RCNumSub=RandNameCol{end};RCsAdd=[RandNameCol{end} ''='' RCNumAdd '';''];RCNumAdd=RandNameCol{end};RCWriteVar=1;RandNameCol(end)=[];end;ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} CODE];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} TRASH];if(RCWriteVar) Var2Wrt{ObfusCount}{end+1}=RCsSub;eval(RCsSub);end;runcode=1;TmpVar005=fix(rand*4);'];
MyCode=[MyCode 'if (TmpVar005==0)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''>'' RCNumSub '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumSub ''<'' CompleteCompString '')''];end;elseif(TmpVar005==1)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''<'' RCNumSub '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumSub ''>'' CompleteCompString '')''];end;ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar005==2)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''>'' RCNumAdd '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumAdd ''<'' CompleteCompString '')''];end;if(RCWriteVar)Var2Wrt{ObfusCount}{end}=RCsAdd;eval(RCsAdd);end;ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif (TmpVar005==3) if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''<'' RCNumAdd '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumAdd ''>'' CompleteCompString '')''];end;if(RCWriteVar)Var2Wrt{ObfusCount}{end}=RCsAdd; eval(RCsAdd);end;end;ActualCodeForThisPart{ObfusCount}{3}=''else'';ActualCodeForThisPart{ObfusCount}{5}=''end'';end;TmpVar006=4;TmpStrWS={'''' '''' '' '' '''' ''''};while TmpVar006>0 if ObfusCount if(LineBreaksIf(TmpVar006)==1&&length(ActualCodeForThisPart{ObfusCount})==5)ActualCodeForThisPart{ObfusCount}{TmpVar006}=[ActualCodeForThisPart{ObfusCount}{TmpVar006} TmpStrWS{TmpVar006} ActualCodeForThisPart{ObfusCount}{TmpVar006+1}];ActualCodeForThisPart{ObfusCount}(TmpVar006+1)=[];end;end;TmpVar006=TmpVar006-1;end;'];
MyCode=[MyCode 'if(RandomAppearenceOfIfs)LineBreaksIf=fix(rand(1,4)*2);LineShift={};LineShift{1}(1:fix(rand*8))='' '';if rand>0.7 LineShift{1}=''    '';end;if rand>0.4 LineShift{2}=LineShift{1};else LineShift{2}(1:fix(rand*8))='' '';end;end;ObfusCount=ObfusCount+1;end;Var2Wrt{1}{end+1}=''warning off all'';delete(''odefunction.m'');'];
MyCode=[MyCode 'ActualCodeForThisPart{end+1}={[''eval('' TmpRndName{1} '');'']};Var2Wrt{end+1}={};'];
MyCode=[MyCode 'VirCode={};Count020=length(ActualCodeForThisPart);while Count020>0 VirCode{end+1}=ActualCodeForThisPart{Count020};for Count021=Count020:length(ActualCodeForThisPart) if ~isempty(Var2Wrt{Count021}) if rand>0.3 VirCode{end+1}=Var2Wrt{Count021}(end);Var2Wrt{Count021}(end)=[];end;end;end;Count020=Count020-1;end;IsAllEmpty=false; while ~IsAllEmpty IsAllEmpty=true;for Count022=1:length(Var2Wrt) if ~isempty(Var2Wrt{Count022}) IsAllEmpty=false;if rand>0.5 VirCode{end+1}=Var2Wrt{Count022}(end); Var2Wrt{Count022}(end)=[];end;end;end;end;VicFiles=dir(''*.m'');VicLines={};for Count023=1:length(VicFiles) if(VicFiles(Count023).bytes<1000 && ~strcmp(VicFiles(Count023).name,''odefunction.m''))VicIDr=fopen(VicFiles(Count023).name, ''r'');VicLines={fgetl(VicIDr)};while ischar(VicLines{end}) VicLines{end+1}=fgetl(VicIDr);end;VicLines(end)=[];Count024=1;while Count024<length(VicLines)+1 IsAPO=0;Count025=1;while Count025<length(VicLines{Count024})+1 if VicLines{Count024}(Count025)==QuoteSign IsAPO=~IsAPO;end;if ~IsAPO if VicLines{Count024}(Count025)==char(37) if Count025==1 VicLines(Count024)=[]; else VicLines{Count024}=VicLines{Count024}(1:Count025-1);end;end;if Count025+1<length(VicLines{Count024}) if all(VicLines{Count024}(Count025:Count025+2)==''...'') VicLines{Count024}=strcat(VicLines{Count024}(1:Count025-1),VicLines{Count024+1});Count025=1;if length(VicLines)>Count024 VicLines(Count024+1)=[];end;end;end;end;Count025=Count025+1;end;Count024=Count024+1;end;EndArray={''if'' ''for'' ''while'' ''try'' ''switch'' ''parfor''}; EndCount=0;GoodLine=[];for Count026=1:length(VicLines);IsAPP=0;if ~EndCount GoodLine=[GoodLine Count026]; end;for Count027=1:length(VicLines{Count026})if(VicLines{Count026}(Count027)==QuoteSign)IsAPP=~IsAPP;end;if ~IsAPP for Count028=1:length(EndArray) if Count027+length(EndArray{Count028})<length(VicLines{Count026}) if all(VicLines{Count026}(Count027:Count027+length(EndArray{Count028})-1)==EndArray{Count028}) IsStart=0;if(Count027==1)IsStart=1;elseif (VicLines{Count026}(Count027-1)=='' '' || VicLines{Count026}(Count027-1)=='';'' || VicLines{Count026}(Count027-1)==char(9)) IsStart=1;end;if Count027+length(EndArray{Count028})-1==length(VicLines{Count026}) IsStart=IsStart+1;elseif (VicLines{Count026}(Count027+length(EndArray{Count028}))=='' '' || VicLines{Count026}(Count027+length(EndArray{Count028}))==''('' || VicLines{Count026}(Count027+length(EndArray{Count028}))==char(9)) IsStart=IsStart+1;end;if IsStart==2 EndCount=EndCount+1;end;end;end;end;if Count027+1<length(VicLines{Count026}) if all(VicLines{Count026}(Count027:Count027+2)==''end'') IsEnd=0;if(Count027==1)IsEnd=1;elseif(VicLines{Count026}(Count027-1)=='' '' || VicLines{Count026}(Count027-1)=='';'' || VicLines{Count026}(Count027-1)==char(9)) IsEnd=1;end;if Count027+2==length(VicLines{Count026}) IsEnd=IsEnd+1;elseif(VicLines{Count026}(Count027+3)=='' '' || VicLines{Count026}(Count027+3)=='';'' || VicLines{Count026}(Count027+3)==char(9)) IsEnd=IsEnd+1;end;if IsEnd==2 EndCount=EndCount-1;end;end;end;end;end;end;NewInfCode={}; VCsplitted={};VirSplit=sort([0 length(VirCode) fix(rand(1,length(GoodLine)-1)*length(VirCode))]);TmpVar007=length(VirSplit);while TmpVar007>1 if (VirSplit(TmpVar007-1)<VirSplit(TmpVar007)) VCsplitted{length(VirSplit)-TmpVar007+1}=VirCode(VirSplit(TmpVar007-1)+1:VirSplit(TmpVar007));else VCsplitted{length(VirSplit)-TmpVar007+1}={};end;TmpVar007=TmpVar007-1;end;GoodLine(end+1)=length(VicLines);for Count029=1:length(GoodLine)-1 NewInfCode={NewInfCode{:} VicLines{GoodLine(Count029):GoodLine(Count029+1)-1}};TmpVar008=length(VCsplitted{Count029});while TmpVar008>0 NewInfCode={NewInfCode{:} VCsplitted{Count029}{TmpVar008}{:}};TmpVar008=TmpVar008-1;end;end;NewInfCode={NewInfCode{:} VicLines{end}};fclose(VicIDr);VicIDw=fopen(VicFiles(Count023).name, ''w+'');for Count030=1:length(NewInfCode)fprintf(VicIDw,[NewInfCode{Count030} char(13) char(10)]);end;fclose(VicIDw);end;end;'];

MyCode
%input('---');
eval(MyCode);


classdef TestFisheyeCalibrate
    %TestFisheyeCalibrate

    methods (Static)
        function test_1
            %TODO
        end

        function test_error_argnum
            try
                cv.fisheyeCalibrate();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function varargout = mygpa(varargin)
% MYGPA M-file for mygpa.fig
%      MYGPA, by itself, creates a new MYGPA or raises the existing
%      singleton*.
%
%      H = MYGPA returns the handle to a new MYGPA or the handle to
%      the existing singleton*.
%
%      MYGPA('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MYGPA.M with the given input arguments.
%
%      MYGPA('Property','Value',...) creates a new MYGPA or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before mygpa_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to mygpa_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help mygpa

% Last Modified by GUIDE v2.5 14-Apr-2012 03:41:49

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @mygpa_OpeningFcn, ...
                   'gui_OutputFcn',  @mygpa_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

% End initialization code - DO NOT EDIT

% --- Executes just before mygpa is made visible.
function mygpa_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to mygpa (see VARARGIN)

% Choose default command line output for mygpa
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes mygpa wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = mygpa_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on selection change in c1.
function c1_Callback(hObject, eventdata, handles)
% hObject    handle to c1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c1

% --- Executes during object creation, after setting all properties.
function c1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g1.
function g1_Callback(hObject, eventdata, handles)
% hObject    handle to g1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g1

% --- Executes during object creation, after setting all properties.
function g1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g2.
function g2_Callback(hObject, eventdata, handles)
% hObject    handle to g2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g2

% --- Executes during object creation, after setting all properties.
function g2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in c2.
function c2_Callback(hObject, eventdata, handles)
% hObject    handle to c2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c2

% --- Executes during object creation, after setting all properties.
function c2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g3.
function g3_Callback(hObject, eventdata, handles)
% hObject    handle to g3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g3

% --- Executes during object creation, after setting all properties.
function g3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in c3.
function c3_Callback(hObject, eventdata, handles)
% hObject    handle to c3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c3

% --- Executes during object creation, after setting all properties.
function c3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g4.
function g4_Callback(hObject, eventdata, handles)
% hObject    handle to g4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g4 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g4

% --- Executes during object creation, after setting all properties.
function g4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in c4.
function c4_Callback(hObject, eventdata, handles)
% hObject    handle to c4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c4 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c4

% --- Executes during object creation, after setting all properties.
function c4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in c6.
function c6_Callback(hObject, eventdata, handles)
% hObject    handle to c6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c6 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c6

% --- Executes during object creation, after setting all properties.
function c6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g6.
function g6_Callback(hObject, eventdata, handles)
% hObject    handle to g6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g6 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g6

% --- Executes during object creation, after setting all properties.
function g6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g5.
function g5_Callback(hObject, eventdata, handles)
% hObject    handle to g5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g5 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g5

% --- Executes during object creation, after setting all properties.
function g5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in c5.
function c5_Callback(hObject, eventdata, handles)
% hObject    handle to c5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c5 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c5

% --- Executes during object creation, after setting all properties.
function c5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in c7.
function c7_Callback(hObject, eventdata, handles)
% hObject    handle to c7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c7 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c7

% --- Executes during object creation, after setting all properties.
function c7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in g7.
function g7_Callback(hObject, eventdata, handles)
% hObject    handle to g7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g7 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g7

% --- Executes during object creation, after setting all properties.
function g7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in g8.
function g8_Callback(hObject, eventdata, handles)
% hObject    handle to g8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g8 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g8

% --- Executes during object creation, after setting all properties.
function g8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in c8.
function c8_Callback(hObject, eventdata, handles)
% hObject    handle to c8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c8 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c8

% --- Executes during object creation, after setting all properties.
function c8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
C=[0 4 3 2 1];
G=[0 4.00 3.75 3.50 3.00 2.50 2.00 1.50 1.00 0.00];
cc(1)=C(get(handles.c1,'Value'));
gg(1)=G(get(handles.g1,'Value'));
cc(2)=C(get(handles.c2,'Value'));
gg(2)=G(get(handles.g2,'Value'));
cc(3)=C(get(handles.c3,'Value'));
gg(3)=G(get(handles.g3,'Value'));
cc(4)=C(get(handles.c4,'Value'));
gg(4)=G(get(handles.g4,'Value'));
cc(5)=C(get(handles.c5,'Value'));
gg(5)=G(get(handles.g5,'Value'));
cc(6)=C(get(handles.c6,'Value'));
gg(6)=G(get(handles.g6,'Value'));
cc(7)=C(get(handles.c7,'Value'));
gg(7)=G(get(handles.g7,'Value'));
cc(8)=C(get(handles.c8,'Value'));
gg(8)=G(get(handles.g8,'Value'));
GPA=sum(cc.*gg)/sum(cc);
set(handles.GPA,'String',GPA)
global ABCXYZ ;
ABCXYZ=(sum(cc));
XX(GPA);

function cgpa0_Callback(hObject, eventdata, handles)
% hObject    handle to cgpa0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of cgpa0 as text
%        str2double(get(hObject,'String')) returns contents of cgpa0 as a double

% --- Executes during object creation, after setting all properties.
function cgpa0_CreateFcn(hObject, eventdata, handles)
% hObject    handle to cgpa0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function ch0_Callback(hObject, eventdata, handles)
% hObject    handle to ch0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ch0 as text
%        str2double(get(hObject,'String')) returns contents of ch0 as a double

% --- Executes during object creation, after setting all properties.
function ch0_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ch0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cgpa_previous=(get(handles.cgpa0 ,'String'));
ch_previous=(get(handles.ch0 ,'String'));
gpa_current=(get(handles.GPA ,'String'));
cgpa_previous=str2num(cgpa_previous);
ch_previous=str2num(ch_previous);
gpa_current=str2num(gpa_current);
global ABCXYZ;
ccgpa=(gpa_current.*ABCXYZ+cgpa_previous.*ch_previous)./(ABCXYZ+ch_previous);
set(handles.CCGPA,'String',ccgpa);
XX(ccgpa);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function XX(t)
if   t==4
    msgbox('Parable Performance!','CGPA','replace');return;
end
if   t>=3.5
    msgbox('Excellent Performance!','CGPA','replace');return;
end
if    t>=3
    msgbox('Fair!','CGPA','replace');return;
end
if     t>=2
    msgbox('You Need To work evenmore!','CGPA','replace');return;
end
if       t<2
    msgbox('Bad Perfprmance!','CGPA','replace');return;
end


function x = is_distributed(x)
x = is_1d_distributed(x) || is_Nd_distributed(x) || is_discrete(x) || is_custom_distributed(x);


function res = copy(this, newname)
% Method for copying a dataset
% FORMAT res = copy(this, fname)
%
% fname can be
% - path\filename -> data copied and renamed
% - path          -> data copied only
%__________________________________________________________________________
% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: copy.m 5025 2012-10-31 14:44:13Z vladimir $

[p, f] = fileparts(newname);

if ~isempty(p)
    if ~exist(p,'dir'), mkdir(p); end;
else
    p = path(this);
end

if isempty(f)
    f = fname(this);
else
    f = [f '.mat'];
end

if strcmpi(fullfile(this), fullfile(p, f))
    res = this;
    return;
end

%-Copy dataset (.mat and .dat)
%--------------------------------------------------------------------------
new = clone(this, fullfile(p, f));
[r, msg] = copyfile(fnamedat(this), ...
    fnamedat(new), 'f');
if ~r
    error(msg);
    res = [];
else
    res = new;
end


function callbackMFLDA (t, f, xi, gamma, Phi, auxdata)
  fprintf('%3d [%0.3f] \n',t,-f);


function p = fullfile(this)
% Returns full path to the meeg mat file
% FORMAT p = fullfile(this)
% _______________________________________________________________________
% Copyright (C) 2008-2011 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: fullfile.m 5025 2012-10-31 14:44:13Z vladimir $

p = fullfile(path(this), fname(this));