#include<stdio.h>
#include <malloc.h>
#include "BlastIndex.h"


BlastIndex 
newBlastIndex (FILE * file)
{
  char line[80], locus[80];
  int start, end, counter = 0;
  BlastIndex newNode, curPtr, startPtr;
  double p;

  curPtr = startPtr = NULL;
  while (!feof (file)) {
    fgets (line, 80, file);
    if (line[0] != '>')
      continue;
    else
      counter++;
    if (counter % 2 == 1) {
      sscanf (line, ">%s %d-%d %*s %lf", locus, &start, &end, &p);
      newNode = (BlastIndex) BlastIndexCalloc ((size_t) 1, sizeof (BlastIndexNode));
      newNode->name = (char *)
	BlastIndexCalloc ((size_t) strlen (locus) + 1, sizeof (char));
      strcpy (newNode->name, locus);
      newNode->start = start;
      newNode->end = end;
      newNode->p = p;
      newNode->matchPos = (long) ftell (file) - strlen (line);
      newNode->next = NULL;
      if (curPtr == NULL)
	startPtr = curPtr = newNode;
      else
	curPtr->next = newNode;
      curPtr = newNode;
    }
  }
  return startPtr;
}

BlastIndex 
nextBlastNode (BlastIndex index)
{
  if (index == NULL)
    return NULL;
  else
    return index->next;
}

void
freeBlastIndex (BlastIndex index)
{
  BlastIndex current = index, next;

  while (current != NULL) {
    next = current->next;
    free (current->name);
    free (current);
    current = next;
  }
}


void *
BlastIndexCalloc (size_t elements, size_t size)
{
  void *ptr;
  ptr = calloc (elements, size);
  if (ptr == NULL) {
    fprintf (stderr, "cannot allocate memory for BlastIndex\n");
    exit (1);
  }
  else
    return ptr;
}
