function [ origImageData newImageData ] = RGB2BW_FPGA( imageFile, PORT, BAUD)
% Sends RGB image to FPGA through UART and FPGA returns
% BW version of image
%
%   imageFile: Location of image to send
%        PORT: The UART port
%        BAUD: The UART baud rate 

%Ensure file exists
fileExist = exist(imageFile,'file');
if(~fileExist)
    error('Error: File doesnt exist or is unreadable');
end

%Read in image file
origImageData = imread(imageFile);

%Get image size
[num_rows num_cols rgb] = size(origImageData);

%Display original RGB image
figure('Name','Original RGB Image'),
imshow(origImageData);

%Open serial port with given port & baud
sp = serial(PORT,'BaudRate',BAUD,'InputBufferSize',num_rows*num_cols*3);
fopen(sp);

%Ensure serial port can be openned
if(strcmp(sp.Status,'closed'))
    delete(sp);
    clear sp;
    delete(instrfindall);
    error('Error: Unable to open serial port');
end

%Send all bytes through UART
for row = 1:1:num_rows
    for col = 1:1:num_cols
        fwrite(sp,origImageData(row,col,1),'uint8');
        fwrite(sp,origImageData(row,col,2),'uint8');
        fwrite(sp,origImageData(row,col,3),'uint8');
    end
end

%Keep reading until received all bytes
newImageData = uint8(zeros(size(origImageData)));
row = 1; col = 1; rgb = 1;
while(sp.BytesAvailable > 0)
    newImageData(row,col,rgb) = fread(sp,1,'uint8');
    rgb = mod(rgb,3)+1;
    if(rgb == 3)
        col = mod(col,num_cols)+1;
        if(col == num_cols)
            row = mod(row,num_rows)+1;
        end
    end
end

%Display received B&W image
figure('Name','Adjusted BW Image'),
imshow(newImageData);

%Release everything
fclose(sp);
delete(sp);
clear sp;
delete(instrfindall);
