#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int,char *[]);

FILE *fInputp;

static char locSet[100] = "";
static char chrSet[100] = "";
static char bin[10] = ".bin";
static char chrFn[10] = "";

main (int argc,char *argv[])
{
	int  linPtr, mask;
	long int n, setPos, endPos, seqLen;
	char base;
	
	if(argc != 6)
		{
		printf("argc %d; syntax posRcvBLR locSet chrNo.bin setPos endPos mask/unmask\n");
		exit(0);
		}
	strcpy(locSet,argv[1]);
	strcpy(chrSet,argv[2]);
	strcpy(chrFn,chrSet);
	strcat(chrFn,bin);
	setPos = atol(argv[3]);
	endPos = atol(argv[4]);
	mask = atoi(argv[5]);
	
	fInputp = fopen(chrFn,"rb");
		if (fInputp == NULL)
		{
		printf("Infile .bin chromosome test command failed.\n");
		exit(0);
		}
		
	n = 0;
	linPtr = 0;
	
	seqLen = endPos - setPos;

	fseek(fInputp,setPos - 1,0);
	
	n = 0;
	printf(">%s_%ld.fa\t%s %ld to %ld\n",locSet,seqLen,chrSet,setPos,endPos);
	do
		{
		base = getc(fInputp);
		if (base == 'A' || base == 'G' || base == 'C' || base == 'T' || base == 'N' ||
			base == 'a' || base == 'g' || base == 'c' || base == 't' || base == 'n')
			{
			n++;
			if(base == 'a' || base == 'g' || base == 'c' || base == 't' || base == 'n')
				{
				if(!mask)
					{
					base = toupper(base);
					printf("%c",base);
					}
				else if(mask)
					{
					printf("N");
					} 
				}
			else printf("%c",base);
			linPtr++;
			if (linPtr == 60)
				{
				printf("\n");
				linPtr = 0;
				}
			}
		}while(n <= seqLen - 1 && !feof(fInputp));

	printf("\n");
	if(feof(fInputp))
		{
		printf("feof before flnkRcv %s; exit (0)\n",chrSet);
		exit(0);
		}

	fclose(fInputp);
	
	return 0;
}

