function data = uart_plot(n,tw,port,ufreq)
%   Get data from the uart and plot it. Pressing 'q' terminates the plot
%   
%   data = uart_plot(n,tw,port,ufreq)
%
%   Input Arguments:
%       n - the number of plots. n integers should be sent
%           to the uart.
%       tw - time window, the number of data points to display
%       port - the name of the serial port
%       ufreq - the update frequency.  How many times the plot gets updated
%               per tw points. (optional, defaults to 1)
%   Output Argumentss:
%       The data collected.  Each column is another time slice.
%
%   Example:
%       uart_plot(3,1000,'/dev/ttyUSB0',2) means that we are receiving 3
%       numbers.  Plotting 1000 samples in the plot window.  We update the
%       plot twice per plot window (or every 500 samples)
    if nargin < 4
        period = tw
    else
        period = tw/ufreq
    end
    
    nsamples = 0;

    t = 1:tw;           %we will show 100 data points at a time
    data = zeros(n,tw);

    %setup the initial plots
    phandles = cell(1,n);

    f=figure;
    hold all;
    
    fmtstring = '';
    for i=1:n
        phandles{i} = plot(t,data(i,t));
        set(phandles{i},'XDataSource','t');
        set(phandles{i},'YDataSource','data(i,t)');
        fmtstring = [fmtstring,'%d ']; %#ok<AGROW> this will be small
    end
  
    % check to see if any ports are open, close them if they are
    if ~isempty(instrfind)
        fclose(instrfind);
        delete(instrfind);
    end

    mySerial = serial(port, 'BaudRate', 230400, 'FlowControl', 'hardware');
    fopen(mySerial);
    disp('Reading...');

    rfresh = 0;
    while true
        if(mySerial.BytesAvailable > n*3)
            data_read = fscanf(mySerial, fmtstring);      
            if (length(data_read)==n)
                nsamples = nsamples + 1;
                if nsamples > length(t)
                    t = t + 1;
                end
                if nsamples > size(data,2)
                    data = [data,zeros(size(data))]; %#ok<AGROW> will grow less frequently as time goes on
                end
                data(:,nsamples) = data_read;
            end
            rfresh = rfresh + 1;
            if rfresh == period %refresh the plot
                for i=1:n
                    refreshdata(phandles{i},'caller');
                end
                drawnow;
                rfresh = 0;
                if get(gcf,'CurrentCharacter') == 'q'
                    break;
                end
            end
        end
        
        
        
    end

    % close the port
    fclose(mySerial);
    disp('Compete');
    data = data(:,1:nsamples);
end