#include <stdio.h>

#define BUFFER_LEN	100000

int JaccardToDice (FILE *in, FILE *out);

int main (int argc, char **argv) {
  FILE *in, *out;

  if (argc < 3) {
    printf ("syntax: %s <jaccard_input_file> <dice_output_file>\n", argv[0]);
    return 0;
  }

  if ((in = fopen (argv[1], "rt")) == NULL) {
    fprintf (stderr, "could not open jaccard input file '%s'\n", argv[1]);
    return 0;
  }

  if ((out = fopen (argv[2], "wt")) == NULL) {
    fprintf (stderr, "could not open dice output file '%s'\n", argv[2]);
    return 0;
  }

  JaccardToDice (in, out);

  fclose (in);
  fclose (out);
}

int JaccardToDice (FILE *in, FILE *out) {
  int row, col;
  char str[20], bigstr[BUFFER_LEN+1], *ptr;
  float j, d;

  for (row = 0; !feof (in); row++) {
    /* read row_id1 */

    fgets (bigstr, BUFFER_LEN, in);
    sscanf  (bigstr,  "%s", &str);

    if (str[0] != 'D') {
      printf ("Warning, row %d, str '%s' should start with 'D'\n", row, str);
    }
    fprintf (out, "%s\n", str);

  /* read data for that row */

    fgets (bigstr, BUFFER_LEN, in);

printf ("row %d has %d characters\n", row, strlen (bigstr));

    if (strlen (bigstr) >= BUFFER_LEN - 1) {
      fprintf (stderr, "Error: line too long for buffer (max %d char)\n", 
BUFFER_LEN);
      return 0;
    }

    if (strlen (bigstr) >= 2) {
      for (col = 0, ptr = &bigstr[0]; ptr = strstr (ptr, "D"); ptr++, col++) {
        sscanf (ptr, "%s %f", &str, &j);
        d = (2 * j) / (1 + j);
        if (ptr > bigstr) fprintf (out, " ");
        fprintf (out, "%s %6.4f", str, d);
      }
    }
    fprintf (out, "\n");
  }
}


