
/*
 * out.c
 *
 * (C) Copyright 1995 Archie L. Cobbs
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "util.h"
#include "error.h"
#include "names.h"
#include "obj.h"
#include "asm.h"

/*
 * INTERNAL FUNCTIONS
 */

	static unsigned		WriteSeg(FILE *fp, int segment);

/*
 * WriteObj()
 *
 * Write out object file
 */

void
WriteObj(FILE *fp)
{
	struct ObjHeader	header;

	header.n_magic = OBJ_HEADER_MAGIC;

/* Write incomplete header */

	if (fwrite(&header, sizeof(header), 1, fp) != 1)
	{
		perror("fwrite");
		cerror("can't write object header");
	}

/* Write text, data, (bss) segments */

	header.n_text = WriteSeg(fp, CodeSegment);
	header.n_data = WriteSeg(fp, DataSegment);
	header.n_bss = gMaxAddress[BssSegment];

/* Write text, data relocation */

	header.n_treloc = RelocDumpEntries(fp, CodeSegment);
	header.n_dreloc = RelocDumpEntries(fp, DataSegment);

/* Write global symbols */

	header.n_symbols = ExportDump(fp);

/* Write names database */

	header.n_strings = NamesDump(fp, gObjNames);

/* Rewrite completed header */

	rewind(fp);
	if (fwrite(&header, sizeof(header), 1, fp) != 1)
	{
		perror("fwrite");
		cerror("can't write object header");
	}
}

/*
 * WriteSeg()
 */

static unsigned
WriteSeg(FILE *fp, int segment)
{
	if (fwrite(gSegBuffer[segment], 1,
		gMaxAddress[segment], fp) != gMaxAddress[segment])
	{
		perror("fwrite");
		cerror("can't write segment");
	}
	return(gMaxAddress[segment]);
}


