#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cgiutils.h"
#include "rle22gif.h"

#define hexdigit(X) (isdigit((X)) ? (X)-'0' : (isupper((X)) ? (X)-'A' + 10 : (X)-'a' + 10))

main()
{
  char *rle_fname, *colors_in, *array_in, *s, rle_fname_full[80] ;
  char *scale_in, *top_in, *bottom_in, *left_in, *right_in ;
  int num_colors, *r_level, *g_level, *b_level ;
  int *r_array, *g_array, *b_array ;
  int i, nregs, step ;

  /* hex digits here are number plus 'A' */

  decode_query_string("fname", &rle_fname, "colors", &colors_in, 
		      "array",&array_in, "scale", &scale_in,
		      "top", &top_in, "bot", &bottom_in,
		      "left", &left_in, "right", &right_in,
		      NULL) ;

  num_colors = ((int)strlen(colors_in) / 6)+1 ;
  r_level = (int *)malloc(sizeof(int) * num_colors) ;
  g_level = (int *)malloc(sizeof(int) * num_colors) ;
  b_level = (int *)malloc(sizeof(int) * num_colors) ;

  r_level[0] = g_level[0] = b_level[0] = 255 ;

  for (s=colors_in, i=1 ; *s != '\0' ; i++, s+=6) {
    r_level[i] = hexdigit(s[0])*16 + hexdigit(s[1]) ;
    g_level[i] = hexdigit(s[2])*16 + hexdigit(s[3]) ;
    b_level[i] = hexdigit(s[4])*16 + hexdigit(s[5]) ;
  }

  nregs = strlen(array_in) ;
  r_array = (int *)malloc(sizeof(int) * nregs) ;
  g_array = (int *)malloc(sizeof(int) * nregs) ;
  b_array = (int *)malloc(sizeof(int) * nregs) ;

  for (i=0 ; i < nregs ; i++) {
    if (array_in[i] >= '0' && array_in[i] <= '9') 
      step = array_in[i] - '0' ;
    else if (array_in[i] >= 'a' && array_in[i] <= 'z') 
      step = array_in[i] - 'a' + 10 ;
    else if (array_in[i] >= 'A' && array_in[i] <= 'Z') 
      step = array_in[i] - 'Z' + 36 ;
    else step = 0 ;
    r_array[i] = r_level[step] ;
    g_array[i] = g_level[step] ;
    b_array[i] = b_level[step] ;
  }

  printf("Content-type: image/gif\n\n") ;
  fflush(stdout) ;

  if (nonempty(scale_in) ||
      (nonempty(top_in) && nonempty(bottom_in) &&
       nonempty(left_in) && nonempty(right_in))) {
    void *image ;
    image = rle22mem(rle_fname, nregs, r_array, g_array, b_array) ;

    if (nonempty(top_in)) 
      rle2clip_mem(image, atoi(left_in), atoi(right_in), 
		   atoi(top_in), atoi(bottom_in)) ;

    if (nonempty(scale_in)) 
      rle2scale_mem(image, atof(scale_in)) ;

    rle2output_mem(image, 0) ;
  }
  else
    rle22gif(rle_fname, nregs, 0, r_array, g_array, b_array) ;
 
}
