function data = rawfileread(pathstr,prefix,suffix,cfg)
%function data = rawfileread(pathstr,prefix,suffix,cfg) opens and reads the
%SeaSoar file defined by directory path pathstr, prefix prefix, and a hex
%suffix.  The total path is then pathstr/prefix.suffix
%cfg is a configuration structure returned by cfgload.
%Data is returned in a self-explanatory structure.

%D. Rudnick 01/06/05
%Calculate nmax using filesize parameter in cfg.  03/21/05

headbytes=18; %number of bytes in header exclusive of string characters.
gpsbytes=34; %number of bytes in gps record.

file=[fullfile(pathstr,[prefix '.' suffix])];
fid=fopen(file,'r','b');
if fid < 0
   data=fid;
   disp(['File ' file ' not found.']);
   return
else
   disp(['Opened file ' file]);
end

strlength1=fread(fid,1,'int32');
str=fread(fid,strlength1,'uchar');
strlength2=fread(fid,1,'int32');
data.filename=fread(fid,strlength2,'uchar=>char')';
data.systemtime=fread(fid,1,'uint32');
data.filescanrate=fread(fid,1,'uint16');
data.ctdscanrate=fread(fid,1,'uint16');
data.numctdbytes=fread(fid,1,'uint16');

headlen=headbytes+strlength1+strlength2;
recordlen=gpsbytes+data.ctdscanrate*data.numctdbytes;
nmax=ceil((cfg.filesize-headlen)/recordlen);

data.gpstime=zeros(nmax,1);
data.lat=zeros(nmax,1);
data.lon=zeros(nmax,1);
data.course=zeros(nmax,1);
data.speed=zeros(nmax,1);
data.systime=zeros(nmax,1);
data.moog=zeros(nmax,1);
data.tension=zeros(nmax,1);
data.bottomdepth=zeros(nmax,1);
data.ctdscans=zeros(nmax*data.ctdscanrate,data.numctdbytes,'uint8');

isfull=logical(1);

for n=1:nmax
   gpst=fread(fid,1,'int32');
   if isempty(gpst)
      isfull=logical(0);
      break
   end
   data.gpstime(n)=gpst;
   data.lat(n)=fread(fid,1,'int32')/1e6;
   data.lon(n)=fread(fid,1,'int32')/1e6;
   data.course(n)=fread(fid,1,'int16')/10;
   data.speed(n)=fread(fid,1,'int16')/10;
   data.systime(n)=fread(fid,1,'uint32');
   data.moog(n)=fread(fid,1,'int16')/10;
   data.tension(n)=fread(fid,1,'int16');
   data.bottomdepth(n)=fread(fid,1,'int16');
   arrayelements=fread(fid,1,'int32');   %not returning these two variables as they are equivalent to 
   bytesinarray=fread(fid,1,'int32');    %ctdscanrate and numctdbytes, and they are constant in a file
   data.ctdscans((n-1)*data.ctdscanrate+1:n*data.ctdscanrate,:)=fread(fid,[data.numctdbytes data.ctdscanrate],'*uchar')';
end

if isfull
    test=fread(fid,1,'uchar');
   if ~isempty(test)
      error('Data remains in file, need to increase nmax.')
   end
else
   data.gpstime=data.gpstime(1:n-1);
   data.lat=data.lat(1:n-1);
   data.lon=data.lon(1:n-1);
   data.course=data.course(1:n-1);
   data.speed=data.speed(1:n-1);
   data.systime=data.systime(1:n-1);
   data.moog=data.moog(1:n-1);
   data.tension=data.tension(1:n-1);
   data.bottomdepth=data.bottomdepth(1:n-1);
   data.ctdscans=data.ctdscans(1:data.ctdscanrate*(n-1),:);
end

fclose(fid);
