
#include <stdio.h>
#include <string.h>
#include "libpdftex.h"

/* This size must ideally overbound the highest changebar index that
   changebar.sty can ever generate */
#define SIZE 512

static int xcoords[SIZE];
static int ycoords[SIZE];

void cbardefine(int a, int b, int c) {
  int i1;
  double x;
  if (sscanf(strpool + a, "%d%lf", &i1, &x) == 2) {
    xcoords[i1 % SIZE] = (int)(0.5 + (x + 72.27) * 100.0);
    ycoords[i1 % SIZE] = (int)(0.5 + (double) c * (100.0 / 65782.0));
  }
}

int cbarlookupx(int a, int b, int c) {
  int i1, i2;
  double thickness, greyness;
  if (sscanf(strpool + a, "%d%d%lf%lf", &i1, &i2, &thickness, &greyness) == 4) {
    if (c == 1) {
      return xcoords[i1 % SIZE];
    } else if (c == 2) {
      return xcoords[i2 % SIZE];
    } else {
      return 0;
    }
  } else {
    return 0;
  }
}

int cbarlookupy(int a, int b, int c) {
  int i1, i2;
  double thickness, greyness;

  if (sscanf(strpool + a, "%d%d%lf%lf", &i1, &i2, &thickness, &greyness) == 4) {
    if (c == 1) {
      return -ycoords[i1 % SIZE];
    } else if (c == 2) {
      return -ycoords[i2 % SIZE];
    } else {
      return 0;
    }
  } else {
    return 0;
  }
}

int cbargetthickness(int a, int b) {
  int i1, i2;
  double thickness, greyness;

  if (sscanf(strpool + a, "%d%d%lf%lf", &i1, &i2, &thickness, &greyness) == 4) {
    return (int)(0.5 + thickness * 100.0);
  } else {
    return 0;
  }
}

int cbargetgreyness(int a, int b) {
  int i1, i2;
  double thickness, greyness;
  if (sscanf(strpool + a, "%d%d%lf%lf", &i1, &i2, &thickness, &greyness) == 4) {
    /* I'm not sure why the 0.1 is needed here - I would have expected
       there not to be a factor required (because changebar.sty
       inserts the greyness as hundredths and pdf_print_real takes
       hundredths as an argument).  Anyway, this works empirically. */
    return (int)(0.1 * greyness);
  } else {
    return 0;
  }
}
