function [ output_args ] = webcam( input_args )
%WEBCAM Summary of this function goes here
%   Detailed explanation goes here

if(exist('input_args', 'var'))
    s = serial('COM9', 'Parity', 'none', 'ByteOrder', 'BigEndian', 'InputBufferSize', 2000000, 'OutputBufferSize', 1000000 , 'BaudRate', 125000, 'DataBits', 8, 'RequestToSend', 'off', 'StopBits', 1, 'ReadAsyncMode', 'continuous', 'FlowControl', 'none');
    fopen(s);
    fwrite(s,'r','uint8');
    fclose(s);
    pause(0.1);
end

s = serial('COM9', 'Parity', 'none', 'ByteOrder', 'BigEndian', 'InputBufferSize', 2000000, 'OutputBufferSize', 1000000 , 'BaudRate', 1041666, 'DataBits', 8, 'RequestToSend', 'off', 'StopBits', 1, 'ReadAsyncMode', 'continuous', 'FlowControl', 'none');
fopen(s);

vid = videoinput('winvideo', 1, 'RGB24_160x120');
himage = preview(vid);

c = onCleanup(@()cleanup_fn(s, vid ));

output = zeros(3072, 1, 'uint8');
buffer = zeros(1024, 1, 'uint8');
prev_buffer = zeros(1024, 1, 'uint8');
prev_buffer2 = zeros(1024, 1, 'uint8');
prev_buffer3 = zeros(1024, 1, 'uint8');
prev_buffer4 = zeros(1024, 1, 'uint8');
prev_buffer5 = zeros(1024, 1, 'uint8');

while 1
    %tic
    data = getsnapshot(vid);
    data = imresize(data, [64 85]);
    data = rgb2gray(data);
    BW = edge(data,'canny');
    BW = BW(1:64,10:74);
    %toc
    
    index_store = 1;
    
    %tic
    for x=1:64
        for y=1:16
            A = 0;
            for j=1:4
                val = BW((y-1)*4 + j, 65 - x) * 3;
                A = bitor(A,bitshift(val,(4-j)*2));
            end
            
            buffer(index_store) = A;  
            output(index_store) = bitor(A, prev_buffer(index_store));
            output(index_store + 1024) = bitor(prev_buffer2(index_store), prev_buffer3(index_store));
            output(index_store + 2048) = bitor(prev_buffer4(index_store), prev_buffer5(index_store));      
            index_store = index_store + 1;
        end
    end
    
    prev_buffer5 = prev_buffer4;
    prev_buffer4 = prev_buffer3;
    prev_buffer3 = prev_buffer2;
    prev_buffer2 = prev_buffer;
    prev_buffer = buffer;
    
    while(strcmp(s.TransferStatus, 'idle') == 0)
        index_store = index_store + 1;
    end       
    fwrite(s,output,'uint8', 'async');  
    
    %toc
    %fprintf('\r\n');
end
end

function [] = cleanup_fn(stream, vid)
    while(strcmp(stream.TransferStatus, 'idle') == 0)
    end
    fclose(stream);
    delete(stream);
    stoppreview(vid);
    closepreview(vid);
end