function [signal,Fs,Label,PhysDim,NoChan]=loadrg64(FILENAME,CHAN)
%signal=loadrg64(FILENAME,CHANNELS)
%	FILENAME 	optional
%	CHANNELS 	optional, default: inf (all channels)

% 	Version 1.01
%	19.04.2001
%	Copyright (c) 1997-2001  Alois Schloegl
%	a.schloegl@ieee.org	

% 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 2
% 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, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
%    

               
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Load HEADER Info %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%


DotPos=max(find(FILENAME=='.'));
if DotPos>0 	FILENAME(DotPos+2)='h';
else		FILENAME=[FILENAME '.rhf'];
end;

fid=fopen(FILENAME,'r','ieee-le');
if fid<0 fprintf(2,'\nError LOADRG64: Header File %s missing\n',FILENAME); end;

IDCODE=fread(fid,4,'char');	%
	if setstr(IDCODE')~='RG64' 
	    	fprintf(2,'\nError LOADRG64: %s not an RG64-File\n',FILENAME); 
	end; %end;

VER=fread(fid,1,'int32');
REL=fread(fid,1,'int32');
Ver=VER+REL/100;
NoChan=fread(fid,1,'int32');
Fs=fread(fid,1,'int32');
NoS=fread(fid,1,'int32');
AMPF=fread(fid,64,'int32');		
fclose(fid);

if nargin<2 CHAN=inf; end;

if prod(size(CHAN))==1, 
        if CHAN==0, CHAN=1:NoChan; 
        elseif CHAN==inf, CHAN=1:NoChan;  
        end;
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%    Load Data     %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FILENAME(length(FILENAME)-1)='d';
fid=fopen(FILENAME,'r','ieee-le');
if fid<0 fprintf(2,'\nError LOADRG64: %s not found\n',FILENAME); end;

[SIG,count]=fread(fid,[NoChan, inf],'int16');

%if (count~=(NoS*NoChan))
if (count~=NoS)
		fprintf(2,'Warning LOADRG64: File "%s" corrupted', FILENAME);
end;

signal=zeros(size(SIG,2),length(CHAN));
Label=setstr(zeros(length(CHAN),4));
for k=1:length(CHAN),
    	Label(k,:)=sprintf('Ch%2i',CHAN(k));
	signal(:,k)=((5E6/2048)/AMPF(CHAN(k)))*SIG(CHAN(k),:)';
end;
fclose(fid);

PhysDim='µV';


