%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%
%  Example for binary data read
%
%  R. Unger 11/2012
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5

clear;

% open the datafile for reading in binary mode
fid=fopen('persons.dat','rb');

% read the number of records
n=fread(fid,1,'int32');

fprintf('# Records: %d \n',n);


% and now read record by record
for i=1:n

  index(i) = fread(fid,1,'int32');
  
  name1  = fread(fid,256,'char');
  name(i,:) = name1';


  pad(i)   = fread(fid,1,'int32');
 
  size(i)  = fread(fid,1,'double');

  age(i)  = fread(fid,1,'int32'); 

  mf(i)   = fread(fid,1,'int32');

  if (i<5)
    fprintf('Index: %d \n',index(i));
    fprintf('Name: %s \n',name(i,:));
    fprintf('Age: %d \n',age(i));
    fprintf('Size: %f \n',size(i));
    fprintf('Male/female: %d \n',mf(i));
  end;


end;

% close the file
fclose(fid);

fprintf('Reading is done \n');
  

% now do some statistics

histo_age         = zeros(120,1);
histo_size_all    = zeros(300,1);
histo_size_male   = zeros(300,1);
histo_size_female = zeros(300,1);

for i=1:n
  a=age(i);
  if (a<1) a=1; end;
  if (a>120) a=120; end;
  histo_age(a) = histo_age(a)+1;

  si=floor( size(i) +0.5 );
  if (si<1) si=1; end;
  if (si>300) si=300; end;
  histo_size_all(si)=histo_size_all(si)+1;

  if ( mf(i) == 0 )
    histo_size_male(si)=histo_size_male(si)+1;
  else
    histo_size_female(si)=histo_size_female(si)+1;
  end;
end;



% and plot it

figure(1)
plot(histo_age);
xlabel('age [years]');
ylabel('#');
title('Histogram of age distribution')

figure(2)
i=[1:300];
plot(i,histo_size_all,i,histo_size_male,i,histo_size_female);
legend('all','male','female');
xlabel('size [cm]');
ylabel('#');
title('Histogram of size distribution')



