
% function saveImageAsHeader(image, filename, imageName)

function saveImageAsHeader(image, filename, imageName, outputTypename)

if ~exist('outputTypename', 'var')
    outputTypename = 'u8';
end

assert(size(image, 3) == 1, 'Image must be grayscale.');

image = im2uint8(image)';

fileId = fopen(filename, 'w');

curDate = date();

maxSlash = max([strfind(filename, '\'), strfind(filename, '/')]);
if isempty(maxSlash)
    maxSlash = 0;
end

maxDot = max(strfind(filename, '.'));
defineFilename = filename((maxSlash+1):(maxDot-1));

if ~exist('imageName', 'var')
    imageName = defineFilename;
end

% Swapped, because the input array is flipped
width = size(image,1);
height = size(image,2);

curDateAndTime = round(clock());

widthName = [imageName, '_WIDTH'];
heightName = [imageName, '_HEIGHT'];

fprintf(fileId,...
    ['// Autogenerated by saveImageAsHeader.m on ', sprintf('%04d-%02d-%02d at %02d:%02d:%02d', curDateAndTime(1), curDateAndTime(2), curDateAndTime(3), curDateAndTime(4), curDateAndTime(5), curDateAndTime(6)), '\n',...
    '\n',...
    '#ifndef _SAVEIMAGEASHEADER_', defineFilename, '_H_\n',...
    '#define _SAVEIMAGEASHEADER_', defineFilename, '_H_\n',...
    '\n',...
    '#include "anki/common/robot/config.h"\n\n',...
    '#define ', widthName,  sprintf(' %d\n', width),...
    '#define ', heightName, sprintf(' %d\n', height),...
    '#define ', imageName, '_NAME "', imageName, '"\n',...
    '\n',...  
    '#if defined(_MSC_VER)\n',...
    '__declspec(align(MEMORY_ALIGNMENT_RAW))\n',... % using the #define MEMORY_ALIGNMENT doesn't seem to work here
    '#endif\n',...    
    sprintf('const %s ', outputTypename), imageName, '[', widthName, '*', heightName, ']\n',...
    '#if defined(__EDG__) || defined(__GNUC__) // ARM-MDK or GCC\n',...
    '__attribute__ ((aligned (MEMORY_ALIGNMENT_RAW)))\n',...
    '#endif\n',...
    '= {\n']);

for y = 1:size(image,2)
    fprintf(fileId, '%d,', image(:,y));
    fprintf(fileId, '\n');
end

fprintf(fileId,...
    ['};\n\n',...
     '#endif // _SAVEIMAGEASHEADER_', defineFilename, '_H_\n']);

fclose(fileId);