function sam = hreadchn(samfile, channel, details)
% function sam = hreadchn(samfile, channel, details)
%
% reads HIFT sample file and extracts specified channel's
% time series
%
% samfile    is text string containing name of the input file
% channel    is the number of the channel to extract
% details    if non-zero prints header and other information
%
% sam        returned time series ... column
% time_text  string containing Julian time string from header
%
% KM 10Aug2000 based on code supplied by Matt Dzieciuch

fid=fopen(samfile, 'r', 'ieee-le'); %open file little endian

% read header (uncomment disp commands to print header)

N_chans=0;
chan_index = 0;
line=fgetl(fid);  
if details disp(line); end
while strcmp(line, '*DATA*') == 0
  line=fgetl(fid); 
  if details disp(line); end
  off=findstr(line, 'Julian:');
  if off
    time_text = line;  
  end
  off=findstr(line, 'channel:');
  if off
    N_chans = N_chans+1;
    chan_num = str2num(line(off+8:off+9));
    if chan_num == channel
      chan_index = N_chans;
    end
  end
end

if chan_index == 0
  error(sprintf('channel %d not found in input file\n', channel));
end
  
start=ftell(fid); fseek(fid,0,'eof'); stop=ftell(fid);
fseek(fid,start,'bof'); sizs=(stop-start)/2;

scan_count = floor(sizs/N_chans);

if N_chans == 1
  [sam count] = fread(fid, sizs, 'int16');
else
  [temp count] = fread(fid, chan_index-1, 'int16');
  % try to read extra scans and see if it does...paranoia
  [sam count] = fread(fid, scan_count+100, 'int16', 2*(N_chans-1));
end

if count ~= scan_count
  error(sprintf('computed scans: %d  read: %d\n', scan_count, count));
end

fclose( fid);

if details 
  fprintf('size: %d  chans: %d  scans: %d  channel: %d  chan_index: %d\n', ...
    sizs, N_chans, scan_count, channel, chan_index);
end

return


