% Script to dmonstrate processing HIFT data using MATLAB
%
% 5June2000 initial version...K.Metzger

clear all;
tic;                       % start timer running

SoundSpeed = 1498;         % meters per second
details = 1;               % turn on input log output

fname = 'x0270949.sam';    % process this data file
signal = 'M2';             % waveform M2 was sent
VonC = -1.798/SoundSpeed;  % Doppler estimate from earlier processing

channel = 0;               % process this channel (names start at 0)

% read the desired channel's sample values
%
samples = hreadchn(fname, channel, details);

% set up the sequence law based on transmitted waveform
%
if signal == 'M1'
  law = 537;
elseif signal == 'M2'
  law = 1473;
elseif  signal == 'M3'
  law = 2033;
elseif signal == 'M4'
  law = 5747;
else
  error('invalid signal designator\n');
end

FConFS = 57/228;   % carrier to sample rate ratio
sam_cyc = 4;       % samples per carrier cycle
cyc_dig = 5;       % number of carrier cycles per sequence bit
angle = 45;        % modulation angle
Qfilter = 4;       % number of samples in periodic sliding filter summation

perm = fmstset(law);      % set up permutation information for fmt
L = 2^perm.layers-1;        % number of sequence bits per period
sam_dig = sam_cyc*cyc_dig;  % samples per sequence bit (digit)

start_scan = 1;       % starting A/D scan to use in processing
n_scans = L*sam_dig;  % number of A/D scans per sequence period
Eflag = 0;            % clear the data flag
PeriodCount = 0;      % initialize the number of sequence periods read

ns = n_scans/2;              % this mimics earlier processing start point
start_scan = start_scan+ns;  % by skipping 1/2 half period worth of A/D scans

while Eflag == 0             % read periods till input is exhausted
  
  % read one period correcting for Doppler
  %
  [demods, Eflag] = Hdedop(samples, VonC, FConFS, start_scan, n_scans);
  
  if Eflag == 0                      % process if a set of samples was read
    PeriodCount = PeriodCount + 1;   % increment count of periods
    start_scan = start_scan+n_scans; % set up start of next period read
    
    % apply sinc filter wrapping around full period
    %
    temp = zeros(size(demods));
    N = length(demods);
    for count = 0:Qfilter-1
      temp = temp+demods(mod([0:N-1]+count, N)+1);
    end
    demods = temp/Qfilter; temp=[];  % and normalize 
    
    % do sequence removal keeping only resulting amplitudes
    %
    tseries(:,PeriodCount) = abs(fmst(demods, perm, angle));
    
  end
end

% write out the processed data set and the name of the input file
%
save plot tseries fname;

fprintf('Number of sequence periods processed: %d\n', PeriodCount);
toc          % print total execution time

