% This code converts an animated GIF into a .c source
% file that contains bytes for showing bitmap graphics
% on an LCD display connected to the Arduino.
%
% The input needs to be a GIF file that is saved as an
% indexed color image. It will automatically be dithered
% down to black and white. The image width and height must
% be a power of two.
%
% (c) 2018 Marcio Teixeira
%
% The source code is free software: you can
% redistribute it and/or modify it under the terms of the GNU
% General Public License (GNU GPL) as published by the Free Software
% Foundation, either version 3 of the License, or (at your option)
% any later version.  The code is distributed WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
%
function gif2arduino(gifname, outname)
  [img,map] = imread(gifname, "Index", "all");
  img = ind2gray(img,map);

  f = fopen(outname , "w");

  fprintf(f,"PROGMEM const unsigned char frames[][%d*%d/8] = {\n",size(img,1),size(img,2));

  for i = 1:size(img,4)
    frame = img(:,:,1,i);

    dithered = bayer(8,frame);
    imshow(dithered);
    pause (.001);
        
    asBytes = sum(diag(2.^(7:-1:0)) * reshape(dithered'/255, 8, []));

    fprintf(f,"  {");
    fprintf(f, "0x%02x,", asBytes(1:end-1));
    fprintf(f, "0x%02x" , asBytes(  end));
    fprintf(f,"},\n");
  endfor
  
  fprintf(f,"};\n");
  fclose(f);
end