#!/usr/local/bin/octave --silent 
##  Run Jade from the shell as a standalone program on an ascii-formatted  data file
##
## Call as :
## $  runjade <datafilename> [<number_of_independent_components>]
##
## The data file should be a matrix of numerical values
## Its small dimension is taken to be the number of sensors
## Its large dimension is taken to be the number of samples
##
## An optional argument is the number of requested independent components
## If absent, it defaults to the number of sensors
## 
## The resulting components are save in a similarly
## formatted file named  <datafilename>_jade.txt
##
## Author: JF Cardoso.  Please report bugs at:   cardoso <at> enst <dot> fr
##

if ((nargin==0) | (nargin>2))
  printf("Usage: runjade <datafilename> [<number_of_independent_components>]\n")
  exit ;
endif
arg_list = argv ();


## Read data in
input_file_name  = arg_list{1} ;
try
  X = load("-ascii", input_file_name);
catch
  error("Cannot load file %s", input_file_name);
end_try_catch

## Get dimensions
[ n_samples n_sensors ] = size(X) ;
if (n_samples<n_sensors)  ## We assume that this is the other way around
  data_transposed = false ;
  [ n_sensors n_samples ] = size(X) ;
else
  X = X' ;
  data_transposed = true ;
endif

printf("We found %i samples from %i sensors\n", n_samples, n_sensors ) ;

## How many components ?
if (nargin==1)
  required_number_of_ICs = n_sensors ; ## default
  printf("By default, jade will extract as many components as sensors\n");
else
  try
    required_number_of_ICs = str2num(arg_list{2}) ; 
  catch
    error("Second input argument should be a number\n");
  end_try_catch
  if (required_number_of_ICs>n_sensors)
    error("Jade cannot extract more sources than sensors\n");
  endif
endif


## Jade finds a separating matrix of size  required_number_of_ICs * n_samples
printf ("Running jade\n");
B = jadeR( X, required_number_of_ICs ) ;
X = B*X ;

if data_transposed
  X = X';
endif

output_file_name = sprintf("%s_jade.txt", input_file_name);
save("-ascii", output_file_name, "X");

printf("Independent components saved in ascii file %s", output_file_name);
