%define scan dimensions
xmax = 37;
ymax = 3;

%open serial connection
s = serial('COM8','DataBits',8,'BaudRate',9600,'Parity','None','StopBits',1);
fopen(s);
fprintf(s,'start');

%run scan and read in data
%data = scan(s,xmax,ymax);
l = xmax*ymax;
data = zeros(l,8);

%receive data until finished
for i = 1:l
  data(i,:) = fread(s,8);
end


%close serial connection
fclose(s);

%create bitmap
%bitmap = process_scan(data,xmax,ymax);

%initialize bitmap
%y and x are reversed because coordinate system is transposed in matrix
bitmap = zeros(ymax*8,xmax);

for y=1:ymax
  %read all data in 1 row along x direction
  temp = data((y-1)*xmax+1:y*xmax,:)';
  
  %case 1: camera was moving left
  if(mod(y,2) == 1)
    bitmap((y-1)*8+1:y*8,:) = temp;
  %case 2: camera was moving right (take mirror)
  else
    bitmap((y-1)*8+1:y*8,:) = fliplr(temp);
  end
end

%%in case we are increaing scan resolution
% for y=1:ymax
%     %read all data in 1 row along x direction
%     temp = data((y-1)*xmax+1:y*xmax,:)';
%     
%     %case 1: camera was moving left
%     if(mod(y,2) == 1)
%         bitmap((ceil(y/2)-1)*16+1:2:ceil(y/2)*16,:) = temp;
%     %case 2: camera was moving right (take mirror)
%     else
%         bitmap((ceil(y/2)-1)*16+2:2:ceil(y/2)*16,:) = fliplr(temp);
%     end
% end
      
%remove costant error due to ADC
raw = bitmap;
load base
bitmap = uint8(bitmap - base);
