function USPS2matlab(USPSdir, MATdir)
% script for converting the original non-matlab-readable 
% USPS digits dataset into matlab *.MAT files
%
% assuming to have the files (e.g. obtainable in gzipped form from 
% ftp://ftp.kyb.tuebingen.mpg.de/pub/bs/data) in the directory USPSdir:
% ocr16-train.mat
% ocr16-test.mat
% train-desired.mat
% test-desired.mat
%
% generating matlab files into MATdir:
% USPS-MATLAB-train.mat
% USPS-MATLAB-test.mat
%
% the original labels range from 1 to 10 for digits 0 to 9
% here, the labels are rotated cyclically, such that labels
% 1-9 correspond to the real digit and label 10 corresponds to 
% digit 0

% Bernard Haasdonk 22.7.2005

dsname = {'train','test'};
ms = [7291,2007];
for ds = 1:2
  label_matrix = bin_read(fullfile(USPSdir,[dsname{ds},'-desired.mat']),...
			  10,ms(ds));
  inds = find(label_matrix==1);
  [labels,dummy] = ind2sub([10,ms(ds)],inds);
  labels = labels-1; % original labels range from 1 to 10 with
                     % "shift of 1" 
  i = find(labels==0);
  labels(i) = 10; % replace label zero with 10;
  if ~isequal(dummy(:)',(1:ms(ds)))
    disp('problem in reading labels, please check');
    keyboard;
  end;
  
  samples = bin_read(fullfile(USPSdir,['ocr16-',dsname{ds},'.mat']),...
			  256,ms(ds));
  if (min(min(samples)~=-1) || (max(max(samples)~=1)))
    disp('problem in reading samples, please check');
    keyboard;  
  end;
  samples = samples +1; % shift for 0 boundary values
  save(fullfile(MATdir,['USPS-MATLAB-',dsname{ds},'.mat']),'samples','labels');
end;  

function M = bin_read(fn,n,m)
fid = fopen(fn,'rb');
if fid<0
  status = -1;
  error(['error opening file ',fn])
  return;
end;
% skip head
[head] = fread(fid,20,'int8');
% read data
[A,cn] = fread(fid,'float32','ieee-be');
fclose(fid);
M = reshape(A,n,m);
