// C++ code Copyright (C) David R. Evans G4AMJ/NQ0I

// class for grey scale for surface

#include <defines.h>
#include <gf_win.h>
#include <surface.h>

#include <ctype.h>
#include <iostream.h>
#include <stdlib.h>

grey_font_windows::grey_font_windows(const uint16 width, const uint16 height) :
                   grey_font(width, height)
{ bias = 0;
  heap_check(pr = new HBITMAP [w * h + 1]);
  _generate_squares();
}


// private -- generate memory versions of all the squares
void grey_font_windows::_generate_squares(void)
{ HDC hdc = CreateCompatibleDC(NULL);

  for (int n_black = 0; n_black <= w * h; n_black++)
	 pr[n_black] = (HBITMAP)_generate_square(n_black, hdc);

  DeleteDC(hdc);
}

// private -- generate a memory map of a single square
HBITMAP grey_font_windows::_generate_square(const uint16 n_black, HDC hdc)
{ yield();

  HBITMAP hbm;
  hbm = CreateCompatibleBitmap(hdc, w, h);

  const int square_size = w * h,
				breakpoint = square_size / 2;

  int  n_marked = 0, n_to_do;
  DWORD default_value = RGB(255, 255, 255), put_value;

  HBITMAP obm;
  obm = (HBITMAP)SelectObject(hdc, hbm);
  PatBlt(hdc, 0, 0, w, h, BLACKNESS);;

  if (n_black > breakpoint) then
  { for (int i = 0; i < w; i++)
		for (int j = 0; j < h; j++)
		  SetPixel(hdc, i, j, default_value);
	 put_value = 0;
	 n_to_do = square_size - n_black;
  }
  else
  { put_value = default_value;
	 n_to_do = n_black;
  }
  if (n_to_do)
  { for (int j = 1; n_marked < n_to_do; j++)
	 { for (int i = 0; (i < square_size) && (n_marked < n_to_do); i++)
		{ if ((GetPixel(hdc, i % w, i / w) != put_value) &&
//            ((random()  / 2147483648.0) < (1.0 / (10.0 * w))))
	  ((rand()  / (1.0 * RAND_MAX)) < (1.0 / (10.0 * w))))
		  { SetPixel(hdc, i % w, i / w, put_value);
			 n_marked++;
		  }
		}
	 }
  }
  SelectObject(hdc, obm);
  return hbm;
}

uint16 grey_font_windows::_rebuild(const uint16 width, const uint16 height)
{ if (pr) then
    delete [] pr;

  w = width;
  h = height;

  heap_check(pr = new HBITMAP [w * h + 1]);

  font_number = ++fonts_created;

  _generate_squares();
  index = 0;

  return (width * height);
};

