#ifndef __CACHES_RJ
#define __CACHES_RJ

#include "maqmap.h"
#include "maqmap_index.h"

#define READ_SELECT		0x00000001
#define READ_SHOWTIP	0x00000002

#ifndef MAX_READ_SIZE
#define MAX_READ_SIZE 128
#endif

typedef struct Read {
	maqmap1_t read;
	unsigned int flag;
	int y;
} Read;

#define free_read(r) free(r)

typedef struct ReadCache {
	MapIndex *index;
	Read *reads;
	int offset;
	int size;
	int capacity;
	int64_t start;
	int64_t end;

	int64_t length;

	int n_ref;
	int64_t *ref_lengths;
	int ref_id;

	int64_t stream_pos;
} ReadCache;

ReadCache* read_cache_init(MapIndex *index);
void read_cache_free(ReadCache *cache);
int read_cache_put(ReadCache *cache, int ref_id, int64_t start, int64_t end);

typedef struct {
//	bit32_t avg01:12, qDiff:5, het:1, qMax:6, depth:8;
	bit32_t depth:8, qMax:6, het:1, qNei:5, avg01:12;
//	bit32_t ref_base:4, base:4; qual:8, base2:4, base3:4, qual2:8;
	bit32_t qual2:8, base3:4, base2:4, qual:8, base:4, ref_base:4;
} cns_t;

#define cns_get_cns(seq) nst_nt16_rev_table[(seq).base]
#define cns_set_cns(seq, val) (seq).base = (val)&0xF
#define cns_get_ref(seq) nst_nt16_rev_table[(seq).ref_base]
#define cns_set_ref(seq, val) (seq).ref_base = (val)&0xF

#define CNS_SRC_FILE	0
#define CNS_SRC_GUESS	1

typedef struct {
	zr_stream *stream;
	char **ref_name;
	int n_ref;
	int64_t *ref_offsets;
	int64_t *ref_lengths;
	int *ref_states;
	int ref_id;
	int64_t last_ref_pos;
	cns_t *seqs;
	int offset;
	int size;
	int capacity;
	int src_type;
	int n_mm_ref, *mm_map, *cns_map;

	int64_t start, end;
} CNSCache;


CNSCache* cns_cache_init();
CNSCache* make_cns_index(const char * filename, int level);
CNSCache* open_cns_cache(const char *filename);
void justify_cns_cache(CNSCache *cache, char **ref_name, int n_ref);
void close_cns_cache(CNSCache *cache);
int cns_cache_put(CNSCache *cache, int ref_id, int64_t start, int64_t end);
int cns_cache_guess(CNSCache *cns, ReadCache *cache);

typedef struct RefSeq {
	ReadCache *cache;
	int show_id;
	int64_t show_start;
	unsigned char *tooltips;
	/*
	char *seqs;
	int **guess_seqs;
	int64_t seq_start;
	int seq_size;
	int seq_capacity;
	*/
	CNSCache *cns;
} RefSeq;

#endif
