/*
 * Color.C  - methods for color handling.
 *
 * Copyright (C) 1992, Christoph Streit (streit@iam.unibe.ch)
 *                     University of Berne, Switzerland
 * All rights reserved.
 *
 * This software may be freely copied, modified, and redistributed
 * provided that this copyright notice is preserved on all copies.
 *
 * You may not distribute this software, in whole or in part, as part of
 * any commercial product without the express consent of the authors.
 *
 * There is no warranty or other guarantee of fitness of this software
 * for any purpose.  It is provided solely "as is".
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <stream.h>

#include "globals.h"
#include "Color.h"
#include "table.h"
#include "Error.h"

//___________________________________________________________ Color

struct cvector {
  float r, g, b;
};

declareTable(ColorTable, rcString, cvector);
implementTable(ColorTable, rcString, cvector);

ColorTable* Color::colors = NULL;
rcString Color::ColorFile;


#ifdef AMIGA_GCC

void Color::setupColors()
{
  char name[256];
  if (GetVar(COLOR_ENV,name,256,0)!=-1)
    ColorFile = name;
  else
    ColorFile = defaultColorFile;
  readColors();
}

#else

void Color::setupColors()
{
  char* name;
  if (name = getenv(COLOR_ENV))
    ColorFile = name;
  else
    ColorFile = defaultColorFile;
  readColors();
}

#endif

Color::Color()
: red(1), green(0), blue(0), name("red")
{
  /*
   * color table already build up?
   */
  if (colors == NULL)
    readColors();
}

Color::Color(const rcString& colorName)
{
  /*
   * color table already build up?
   */
  if (colors == NULL)
    readColors();

  cvector rgbValues;
  if (colors->lookup(colorName, rgbValues)) {
    red   = rgbValues.r/255;
    green = rgbValues.g/255;
    blue  = rgbValues.b/255;
    name  = colorName;
  }
  else {
    Error(ERR_WARN, "unknown color " + colorName);
    red   = rgbValues.r = 1;
    green = rgbValues.g = 0;
    blue  = rgbValues.b =0;
    name  = colorName;

    /*
     * The next time we will know the color!
     */
    colors->insert(colorName, rgbValues);
  }
}

void Color::readColors()
{
  FILE* inFile = fopen(ColorFile, "r+");
  if (inFile == NULL)
    Error(ERR_PANIC, "could't open file '" + ColorFile 
	  + "'\n(Is environment variable COLORFILE set?)");
  colors = new ColorTable(200);
  char cName[300];
  cvector rgbValues;

  long colorNum = 1;
  
  while(1) {
    int n = fscanf(inFile, "%f%f%f%s", 
		   &rgbValues.r, &rgbValues.g, &rgbValues.b, cName);
    if (n > 0 && n < 4)
      Error(ERR_ABORT, "ill fomatted color file near line " 
	               + rcString(form("%ld", colorNum)));
    else if (n <= 0)
      break;

    colorNum++;
    colors->insert(cName, rgbValues);
  }

  fclose(inFile);
}

