#include <ncbi.h>
#include <gishlib.h>
#include "blastapp.h"
#include "gcode.h"

int LIBCALL
print_tx(biop, hlp)
	BlastIoPtr	biop;
	BLAST_HitListPtr	hlp;
{
	FILE	*fp;
	long	nseqlen;
	unsigned long	id;
	int		i, npos, nlen, prevframe, frame;
	BLAST_StrPtr	dbsp, tsp;
	BLAST_HSPPtr	hp;
	BLAST_LetterPtr	nbuf;
	BLAST_Letter	stackbuf[10*KBYTE];
	register char	*cp, *cpmax;

	fp = biop->fp;

	dbsp = &hlp->str2;
	id = dbsp->id.data.intvalue;
	db_seek(dbfp, id);
	/*db_get_seq(dbfp, dbsp);*/
	nseqlen = dbsp->len;

	if (fp != NULL) {
		cp = dbsp->name;
		cpmax = cp + dbsp->namelen;
		while (cp < cpmax && !isspace(*cp))
			++cp;
		while (cp < cpmax && isspace(*cp))
			++cp;
		i = cp - dbsp->name + 1;
		i = MIN(i, 12);
		putc_unlocked('\n', fp);
		putc_unlocked('\n', fp);
		wrap(fp, ">", dbsp->name, dbsp->namelen, 79, i);
		fprintf(fp, "%*sLength = %s\n", i, "", Ltostr(nseqlen,1));
	}

	prevframe = 0;
	for (hp = *hlp->hpp; hp != NULL; hp = hp->next) {
		tsp = BlastStrNew(hp->len, ncbiaa, 1);
		tsp->src = dbsp;
		tsp->offset = hp->s_seg.offset;
		frame = tsp->frame = hp->s_seg.frame;
		tsp->gcode_id = dbgcode;
		hp->s_seg.sp = tsp;
		hp->s_seg.offset = 0;

		nlen = hp->len * CODON_LEN;
		if (frame > 0)
			npos = tsp->offset*CODON_LEN + frame - 1;
		else
			npos = nseqlen - tsp->offset*CODON_LEN + frame - nlen + 1;
		if (nlen <= DIM(stackbuf))
			nbuf = stackbuf;
		else {
			nbuf = (BLAST_LetterPtr)malloc(nlen * sizeof(*nbuf));
			if (nbuf == NULL)
				return 1;
		}
		db_get_str_specific(dbfp, nt4ap, nbuf, npos, nlen);
		if (frame > 0)
			trans2b(nbuf, tsp->str, hp->len, ncbiaa, db_gcode);
		else
			rtrans2b(nbuf, tsp->str, hp->len, ncbiaa, db_revgcode);
		if (nbuf != stackbuf)
			mem_free(nbuf);

		if (fp != NULL && SIGN(prevframe) != SIGN(frame)) {
			if (frame > 0)
				fprintf(fp, "\n  Plus");
			else
				fprintf(fp, "\n  Minus");
			fprintf(fp, " Strand HSPs:\n");
		}
		prevframe = frame;

		if (hsp_print(fp, hp, TRUE) != 0)
			return 1;
	}
	return 0;
}
