function compareIDs(){
    if (sp>bp) {return 1;} else {
	if (sp<bp) {return -1;} else {
	    if (sq>bq) {return 1;} else {
		if (sq<bq) {return -1;} else {
		    if (sr>br) {return 1;} else {
			if (sr<br) {return -1;} else {
			    return 0;
			}
		    }
		}
	    }
	}
    }
}

function splitID(){
	split(substr(i,2),a,"_");
	p=a[1];q=a[2];r=a[3];
}


function getBC(){
    found=0;
    while (getline <bcf){
	i=$1
	if (substr(i,1,1)==">") {
	    if (getline <bcf) {
		bc=$0;
		found=1;
	    }
	    break;
	}
    }
    if (found==1) {
#	print nBC" "i" "bc;
	nBC++;
	splitID();
	bp=p;bq=q;br=r;
    }
    return found;
}

function getSeq(){
    found=0;
    while (getline ){
	i=$1
	if (substr(i,1,1)==">") {
	    h=i;
	    if (getline ) {
		s=$0;
		found=1;
	    }
	    break;
	}
    }
    if (found==1) {
#	print nSeq" "h;
	nSeq++;	
	splitID();
	sp=p;sq=q;sr=r;
    }
    return found;
}

BEGIN{    
    bctab="/home/reczko/data/robb/CSBarcodes.txt";
    ibc=1; npr=0;
    while (getline<bctab){
	bct[$3]=ibc;
	bcti[ibc]=$3;;
	bcl=length($3);
	ibc++;
    }
    totalbc=ibc;
    close(bctab);

    done=0;
    rBC=1;rSeq=1;
    nBC=1;nSeq=1;
    while (done==0) {
	if (rBC==1) {
	    f=getBC();
	    if (f==0) {break;}
	}

	if (rSeq==1) {
	    f=getSeq();
	    if (f==0) {break;}
	}
	comp=compareIDs();
#	print "c "comp;
	if (comp==0) { 

	    if (++npr==1000000) {
		printf("%dM ",++npk);
		system("sleep 10");
		npr=0;
	    }
#	    print h" "bp" "bq" "br" "bc" "s;
	    bci=bct[substr(bc,1,bcl)];
	    if (bci>0) {
#		print bci":"h" "bp" "bq" "br" "bc" "s;
		spfn="bcseq"bci".qual";
		print h"\n"s >> spfn;
		nbcm[bci]++;
		nok++;
	    }
	    rBC=1;rSeq=1;	    
	} else {
	    if (comp==-1) {
		rBC=0;rSeq=1;	    
	    } else {
		rBC=1;rSeq=0;	    
	    }
	}
    }
    print "mapped "nok" of "nBC;
    for (i=1;i<totalbc;i++) {
	spfn="bcseq"i".qual";
	print "BC "i" "bcti[i]" mapped to "spfn" #reads "nbcm[i]" = "100.0*nbcm[i]/nok" of "nok;
    }
    exit 0;
}{}