#ifndef _INTERVAL_H_
#define _INTERVAL_H_

/**
 *    WHAM - high-throughput sequence aligner
 *    Copyright (C) 2011  WHAM Group, University of Wisconsin
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*	$Id: interval.h 157 2012-07-25 05:58:09Z yinan $ */

#include "lib.h"

/*	interval tree leaf level entry */
typedef struct IntervalLEntry {
  uint32 key; /* the offset in compact sequence */
  uint32 len;
  uint32 sid; /* the sequence id */
  uint32 offset; /* the offset in the originial sequence */
} IntervalLEntry;

/* interval tree internal level entry */
typedef struct IntervalIEntry {
  uint32 key; /* the offset in compact sequence */
  uint32 offset; /* the position of the node in its child level */
} IntervalIEntry;

/* interval tree level */
typedef struct IntervalLevel {
  uint32 curNode; /* the current node in the level */
  uint32 curEntry;/* the current entry in the current node */
} IntervalLevel;

class IntervalTree {
private:
  uint32 lenNSeg;
  uint32 numIEntry; /* the number of internal entries */
  uint32 numLEntry; /* the number of leaf entries */
  uint32 numLevel; /* the number of levels */
  uint32 fl; /* the fanout of leaf node */
  uint32 fi; /* the fanout of internal node */

  uint32 curLNode; /* the current allocation position in leaf node pool */
  uint32 curINode; /* the current allocation position in internal node pool */
  IntervalLEntry * lpool; /* the leaf node pool */
  IntervalIEntry * ipool; /* the internal node pool */
  IntervalLevel * level; /* the levels */

public:
  IntervalTree();
  IntervalTree(uint32 num, uint32 len);
  int append(uint32 key, uint32 len, uint32 sid, uint32 offset);
  int flush(uint32 key, uint32 len, uint32 sid, uint32 offset);
  int lookup(uint32 key, uint32 & sid, uint32 & offset);
  int save(char * path);
  int load(char * path);

private:
  int append(uint32 key, uint32 offset, uint32 l);
  int flush(uint32 key, uint32 offset, uint32 l);
};

#endif
