%  NOTE:
%      (C) Copyright 2016 Texas Instruments, Inc.
%
%  Redistribution and use in source and binary forms, with or without
%  modification, are permitted provided that the following conditions
%  are met:
%
%    Redistributions of source code must retain the above copyright
%    notice, this list of conditions and the following disclaimer.
%
%    Redistributions in binary form must reproduce the above copyright
%    notice, this list of conditions and the following disclaimer in the
%    documentation and/or other materials provided with the
%    distribution.
%
%    Neither the name of Texas Instruments Incorporated nor the names of
%    its contributors may be used to endorse or promote products derived
%    from this software without specific prior written permission.
%
%  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
%  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
%  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
%  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
%  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
%  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%
%  capture_demo.m
%
%  Description:
%  This file is a sample MATLAB script to process the data captured from
%  Capture Demo.
%  It reads data from file("ccs_data.dat") which is saved from CCS or 
%  file("lvds_data.csv") which is saved from LVDS + TSW setup. 
%  It then generates first FFT graph of the captured data.
%  Please refer to the capture demo script for the parameters used in the
%  demo. Such as number of samples, number of chirps etc.
%  
%  Usages:
%  To call this function please enter:
%  "capture_demo(1)" to process CCS memory data file ccs_data.dat
%  or
%  "capture_demo(2)" to process LVDS data file lvds_data.csv

function capture_demo(fileSelect)
%clear all;
close all;

% Global variables
% Please align with the actual demo for these variables.

% Number of samples
K = 256;
% Number of chirps
Nchirp = 128;
% Slope const (MHz/usec)
freqSlope = 40 * 1e12;
% Velosity of light
C = 3e8;
% ADC sampling rate
sampleRate = 8000 * 1e3;
% ADC start time (usec)
adcStartTime = 5 * 1e-6;
% Start frequency (GHz)
startFreq = 77 * 1e9;
% ramp End time
rampEndTime = 40 * 1e-6;

if fileSelect == 1
    %Read in CCS memory file and convert to real number
    fid = fopen('ccs_data.dat', 'r');
    rawData = textscan(fid, '%s', 'Delimiter', '', 'headerLines',1);
    data = cell2mat(cat(2, rawData{:}));
    % Convert data to decimal, and reshape in two columns for I and Q
    dataDec = hex2dec(data);
    dataDec = dataDec - ( dataDec >=2.^15).* 2.^16;
    rad_in = reshape(dataDec, [2, length(dataDec)/2]).';
    fclose(fid);
elseif fileSelect == 2
    %Read in LVDS csv file
    data = csvread('lvds_data.csv');
    %reshape in two columns for I and Q
    [row col] = size(data);
    rad_in = reshape(data.', [2, row*col/2]).';
else
    fprintf('Please enter:\n');
    fprintf('"capture_demo(1)" to process CCS memory data file ccs_data.dat\n');
    fprintf('or\n');
    fprintf('"capture_demo(2)" to process LVDS data file lvds_data.csv\n'); 
    return;
end

% Plot I and Q
figure(1);
plot(rad_in(:,1));grid on;
hold on;
plot(rad_in(:,2),':r');grid on;
xlabel('ADC sample index');
ylabel('Sample value');
title('ADC raw data');

% Change to complex data and Calculate average
% To handle static object only, use average as an example filter.
frame = rad_in(1:K*Nchirp,1) + i*rad_in(1:K*Nchirp,2);
chAve = zeros(K,1);
avgChirp = Nchirp;
for nn = 1:avgChirp
    chAve = chAve + frame((nn-1)*K+1:(nn-1)*K+K);
end
chAve = chAve/avgChirp;

% Calculate range
rangeResolutionsInMeters = C * sampleRate / (2 * freqSlope * K);
rangeIdxToMeters = C * sampleRate / (2 * freqSlope * K);
rangeBin = linspace(0, K * rangeIdxToMeters, K);

% Do FFT on chirp average and plot results
fftResult = fft(chAve);

% Do FFT on chirp average and plot results
figure(2);
plot(rangeBin, abs(fftResult), '-m'); grid on;
hold on;
xlabel('range (m)');
title('Range FFT');



