%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% .m script of web demo "Insert title here" 
% Written for GNU Octave
% 
% INSTITUTE OF TELECOMMUNICATIONS  
% University of Stuttgart 
% www.inue-uni-stuttgart.de 
% author: Marc Gauger / Alexander Knaub   
% date: 11.04.2014   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function [h_x,r] = entropy_fun(filename_input, uploadfile, svg_en, webdemo_en, filname_output)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BEGIN, set up graphical output

% Create an invisible figure.
if (webdemo_en)
  fig = figure(1); set(fig, "visible", "off");
else
  fig = figure(1); set(fig, "visible", "on");
endif

landscape = "-S930,350";
portrait  = "-S640,480";

output_format = landscape; %portrait;     % default


set(0, "defaultlinelinewidth", 2);

if (webdemo_en)
  set(0, "defaultaxesfontsize", 8);
  set(0, "defaultaxesfontname", "Helvetica");
  set(0, "defaulttextfontsize", 8);
  set(0, "defaulttextfontname", "Helvetica");
  const_lw = 2;
elseif (svg_en)
  set(0, "defaultaxesfontsize", 6);
  set(0, "defaultaxesfontname", "Helvetica");
  set(0, "defaulttextfontsize", 6);
  set(0, "defaulttextfontname", "Helvetica");
  const_lw = 1;
else
  set(0, "defaultaxesfontsize", 10);
  set(0, "defaultaxesfontname", "Helvetica");
  set(0, "defaulttextfontsize", 8);
  set(0, "defaulttextfontname", "Helvetica");
  const_lw = 2;
endif

% END, set up graphical output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if(strcmp(filename_input,"tmp-File"))
	fileID = fopen(uploadfile, 'r');
else
	fileID = fopen(filename_input, 'r');
endif	
A = fread(fileID, inf, 'uint8=>double');
[n, x] = hist(A, 256);
p = n/sum(n);
bar(x,p,'b','EdgeColor','b', "linewidth",  const_lw)
axis([0 255 0 max(p)]);
line([0 255],[1/256 1/256],'color','r');
xlabel('symbol');
ylabel('probability');
legend(filename_input,'Pi=1/256')  
h_x = sum(-log2(p(p>0)).*p(p>0));
r=8-h_x;
fclose(fileID);

description_text = ["N=256\nentropy       : " num2str(h_x) " bit/symbol\nredundancy : " num2str(r) " bit/symbol\n"];
text(50, 0.9*max(p), description_text, "color", "red");

print(filname_output, "-dpng","-S640,480");

if (svg_en)
  print(["fig_",filname_output], "-dsvg",output_format);
endif

end
