#include <stdio.h>
#include <io.h>
#include <windows.h>

struct text_info {
    WORD normattr;
    WORD attribute;
    SHORT winleft;
    SHORT wintop;
    SHORT winright;
    SHORT winbottom;
    SHORT screenheight;
    SHORT screenwidth;
    SHORT curx;
    SHORT cury;
    unsigned char currmode;	/* unused and unsupported for Windows */
};

static void
gettextinfo (struct text_info *ti)
{
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  static TCHAR errbuf[500];
  HANDLE hstdout;

  hstdout = GetStdHandle (STD_OUTPUT_HANDLE);
  printf ("hstdout: 0x%lx 0x%lx\n", (long)hstdout, _get_osfhandle (1));
  printf ("hstdin: 0x%lx 0x%lx\n",
	  (long)GetStdHandle (STD_INPUT_HANDLE), _get_osfhandle (0));

  if (hstdout != INVALID_HANDLE_VALUE
      && GetConsoleScreenBufferInfo (hstdout, &csbi))
    {
      ti->normattr = csbi.wAttributes;
      ti->winleft = csbi.srWindow.Left;
      ti->wintop = csbi.srWindow.Top;
      ti->winright = csbi.srWindow.Right;
      ti->winbottom = csbi.srWindow.Bottom;
      ti->attribute = csbi.wAttributes;
      ti->screenheight = csbi.dwSize.Y;
      ti->screenwidth = csbi.dwSize.X;
      ti->curx = csbi.dwCursorPosition.X;
      ti->cury = csbi.dwCursorPosition.Y;
    }
  else
    {
      DWORD error_no = GetLastError ();

      if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL,
			  error_no,
			  0, /* choose most suitable language */
			  errbuf, sizeof (errbuf), NULL))
	sprintf (errbuf, "w32 error %lu", error_no);
      fprintf (stderr, "Terminal cannot be initialized: %s\n", errbuf);
      exit (1);
    }
}

int
main (void)
{
  struct text_info ti;

  gettextinfo (&ti);
  printf ("Console Information:\n\n"
	  "Window rectangle:    L%d T%d R%d B%d\n"
	  "Screen Size (HxW):   %dx%d\n"
	  "Current Attribute:   0x%4.4x\n"
	  "Normal Attribute:    0x%4.4x\n"
	  "Cursor Position:     X=%d Y=%d\n",
	  ti.winleft,
	  ti.wintop,
	  ti.winright,
	  ti.winbottom,
	  ti.screenheight,
	  ti.screenwidth,
	  ti.attribute,
	  ti.normattr,
	  ti.curx,
	  ti.cury);

  return 0;
}
