#include <windows.h>
#include <vector>
#include <valarray>

using namespace std;

// ==EZplot=======
// note, we are only compiling this if DEBUG is defined
bool EZplot(HWND hwnd, const valarray<double>& x, const valarray<double>& y)
{
   RECT rect;
   GetClientRect(hwnd, &rect);
   HDC hdc = GetDC(hwnd);
   if (hdc)
   {
      HPEN pen = CreatePen( PS_SOLID, 0, RGB(0,0,0) );
      if (pen==0) disp("EZplot failed to create pen");
      HPEN prevpen = (HPEN) SelectObject(hdc, pen);
      if (prevpen==0) disp("EZplot failed to select pen");

      HBRUSH brush = CreateSolidBrush( RGB(255,255,200) );
      if (brush==0) disp("EZplot failed to create brush");
      HPEN prevbrush = (HPEN) SelectObject(hdc, brush);
      if (prevbrush==0) disp("EZplot failed to select brush");

      // draw rectangle with current pen, and fill it with current brush
      Rectangle(hdc, rect.left,rect.top,rect.right,rect.bottom);


      // Now reduce rect a bit
      LONG tmp = rect.left;
      rect.left = rect.left*19/20 + rect.right/20;
      rect.right = tmp/20 + rect.right*19/20;
      tmp = rect.bottom;
      rect.bottom = rect.bottom*19/20 + rect.top/20;
      rect.top = tmp/20 + rect.top*19/20;

      // Now create a white brush
      HBRUSH wbrush = CreateSolidBrush( RGB(255,255,255) );
      if (wbrush==0) disp("EZplot failed to create wbrush");
      if ( SelectObject(hdc, wbrush)==0)
      disp("EZplot failed to select wbrush");

      // paint the plotting region using the brush
      Rectangle(hdc, rect.left-1,rect.top-1,rect.right+1,rect.bottom+1);

// This method may be quicker?:
//      ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rect, "", 0, 0);

      double xsc = (double) (rect.right - rect.left)/(x.max() - x.min());
      double ysc = (double) (rect.top - rect.bottom)/(y.max() - y.min());

      valarray<double> ix(x.size());
      valarray<double> iy(y.size());
      ix = (double) rect.left + (x-x.min())*xsc;
      iy = (double) rect.bottom + (y-y.min())*ysc;

      // Plot the curve
      MoveToEx(hdc, (int) ix[0], (int) iy[0], (LPPOINT) NULL);
      for(int i=1; i<x.size(); ++i) LineTo(hdc, (int) ix[i], (int) iy[i]);

      // Tidy up
      SelectObject(hdc, prevpen);
      SelectObject(hdc, prevbrush);
      ReleaseDC(hwnd, hdc);
      DeleteObject(pen);
      DeleteObject(brush);
      DeleteObject(wbrush);
      return true;
   }
   else
   {  disp("EZplot failed to get dc"); return false;  }
}