/* ************************************************************* */
/* demo5.c For Turbo C - Demonstrates how to set palettes        */
/*                                                               */
/*                                                               */
/* Use the RM to create palette tables.                          */
/*                                                               */
/* NOTE: The BGI setrgbpalette function does not work properly.  */
/*       Use the setrgb function that is provided here.          */
/* ************************************************************* */

#include <stdio.h>
#include <dos.h>
#include <graphics.h>

int huge DetectVGA256(void)
{
 return(0);   /* change 0 to other value for SVGA modes */
}

void setvga256(void)
{
 int gm,driver = DETECT;
 installuserdriver("svga256",DetectVGA256);
 initgraph(&driver,&gm,"");
}

void setvga16()
{
 int driver = VGA,
       mode = VGAHI;

 initgraph(&driver, &mode, "");
}

void setrgb(int c, int r, int g, int b)
{
  union REGS reg;

if ((getmaxcolor()==15) && (c<16))
{
 reg.h.ah = 0x10;
 reg.h.al = 0;
 reg.h.bl = c;
 reg.h.bh = c;
 int86(0x10, &reg, &reg);
}
 reg.h.ah = 0x10;
 reg.h.al = 0x10;
 reg.x.bx = c;
 reg.h.dh = r;
 reg.h.ch = g;
 reg.h.cl = b;
 int86 (0x10, &reg,&reg);
}

void setnewpalette()
{
 /* C Palette Source, 16 Colors (RGB)  */

 char Pal[48] = {
          0x00,0x00,0x00,0x3F,0x15,0x15,0x3F,0x18,0x18,0x3F,0x1B,0x1B,
          0x3F,0x1E,0x1E,0x3F,0x21,0x21,0x3F,0x24,0x24,0x3F,0x27,0x27,
          0x3F,0x2A,0x2A,0x3F,0x2D,0x2D,0x3F,0x30,0x30,0x3F,0x33,0x33,
          0x3F,0x36,0x36,0x3F,0x39,0x39,0x3F,0x3C,0x3C,0x3F,0x3F,0x3F};

 int i;
 for(i=0;i<16;i++)
 {
 setrgb(i,Pal[i*3],Pal[i*3+1],Pal[i*3+2]);
 }
}

void drawbars()
{
 int i;
 int barwidth,barheight;
 int numcolors;

 numcolors=getmaxcolor()+1;
 barwidth=getmaxx() / numcolors;
 barheight=getmaxy() / 2;

 for(i=0;i<numcolors;i++)
 {
   setfillstyle(SOLID_FILL,i);
   bar(i*barwidth,0,i*barwidth+barwidth,barheight);
 }
}

void main()
{
  setvga16();          /* replace with setvga256 for 256 color palettes */

  drawbars();
  getch();
  setnewpalette();
  setcolor(15);
  outtextxy(getmaxx()/2-50,getmaxy()/2+50,"NEW PALETTE");

  getch();
  closegraph();
}
