clear all; close all; clc;
% Octave 4.2.2: yoou might need to execute 'pkd load image' in the command line
img_file = 'iss.jpg';
IM = rgb2gray(imread(img_file));
[n, m]  = size(IM);

fname_i = 'iss.bif'; % Input binary file
fname_o = 'iss.bof'; % Output binary file

K = [0 -1 0; -1 4 -1; 0 -1 0];

%K = [0 -1 0; -1 5 -1; 0 -1 0];
%K = [-1 -1 -1; -1 8 -1; -1 -1 -1];
%K = [-1 2 1; 2 4 2; 1 -2 1];

OM = conv2(double(IM),K, 'same');

figure; imshow(IM, []); title ('Input image');
figure; imshow(OM, []); title ('Ouput image (conv)');
figure; imshow(uint8(OM), []); title ('Output image: [0,255]');

disp ('Simple Image test:');
disp ('1. Create .bif file that stores image in a binary file as a row vector');
disp ('2. Compare .bof file (generated) with the MATLAB processed image');
disp ('Any other number to exit');

while(1)
    method = input ('Select Operator (1-2)', 's');
    switch method
        case '1'
            figure; imshow(IM);
            B = reshape (IM', 1,n*m); % raster scan into row vector
            fid = fopen (fname_i, 'w'); % bif: binary image file
            fwrite (fid, B, 'uint8');
            fclose (fid);
        case '2'
            % here, each element is an int (32-bits wide)
            fod = fopen (fname_o, 'r');
            raster_in = fread(fod, n*m, 'int32=>int32');
            OMr = reshape (raster_in, m, n)';
            %figure; imshow(OMr, []); % does not work in Octave
            figure; imshow(uint8(OMr), []);  title ('Output image (board): [0, 255]');
            
            figure; imshow( abs(OM - double(OMr) ), []); title ('difference');
            fclose(fod);
        otherwise
            disp ('unknown option, bye!'); break;
    end
end
