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

void usage(FILE *out, char *prog){
	fprintf(out, "Usage: %s make | use\n", prog);
	fprintf(out, "\tmake <gz-file> [<index level>]\tmake index for gz-file,index filename will be <gz-file>.idx\n");
	fprintf(out, "\t                                \teach level increasing the time for search whist decreasing the size of index\n");
	fprintf(out, "\t                                \tlevel: default 1024, 1/1024 of source file\n");
	fprintf(out, "\t                                \tlevel:         512, 1/512 of source file\n");
	fprintf(out, "\t                                \tlevel: ...\n");
	fprintf(out, "\tuse  <gz-file> <offset>[ <offlen>]\tuse index <gz-file>.idx, exact from offset(source position) to stdout\n");
}

int main(int argc, char **argv){
	int64_t offset, offlen;
	int i, level, ret;
	zr_stream *zr;
	char buffer[WINSIZE + 1];
	if(argc < 2) return usage(stderr, argv[0]), 1;
	if(strcmp(argv[1], "make") == 0){
		if(argc < 3) return usage(stderr, argv[0]), 1;
		if(argc >= 4){
			level = atoi(argv[3]);
			if(level < 2) level = 2;
		} else level = 1024;
		if(!zrmkindex(argv[2], level, NULL, NULL)){
			fprintf(stderr, "Cannot make index for gzfile[%s]\n", argv[2]);
			return 1;
		}
		return 0;
	} else if(strcmp(argv[1], "use") == 0){
		if(argc < 4) return usage(stderr, argv[0]), 1;
		zr = zropen(argv[2]);
		if(zr == NULL){
			fprintf(stderr, "Cannot open %s\n", argv[2]);
			return 1;
		}
		offset = atol(argv[3]);
		if(argc == 4){
			offlen = (int)((~((unsigned int)0)) >> 1);
		} else {
			offlen = atol(argv[4]);
		}
		if(zrseek(zr, offset) < 0){
			fprintf(stderr, "Cannot seek to position %ld\n", offset);
			zrclose(zr);
			return 1;
		}
		while(offlen && !zreof(zr)){
			ret = zrread(buffer, WINSIZE, zr);
			if(ret > offlen){ ret = offlen;}
			for(i=0;i<ret;i++){
				fputc(buffer[i], stdout);
			}
			offlen -= ret;
		}
		zrclose(zr);
		return 0;
	} else {
		fprintf(stderr, "Unknown command %s\n", argv[1]);
		return 1;
	}
}
