/* omflibwr.c (emx+gcc) */

/* Write an OMFLIB.

Copyright (c) 1993 Eberhard Mattes

This file is part of the emx OMFLIB library.  This library is free
software; you can redistribute it and/or modify it under the terms of
the GNU Library General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.  This library is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

As a special exception, programs written by Eberhard Mattes can use
this library without restrictions unless changed by someone else. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "omflib0.h"
#include "omflib.h"


int omflib_write_record (struct omflib *p, byte rec_type, word rec_len,
                         const byte *buffer, int chksum, char *error)
{
  struct omf_rec rec;
  byte sum;
  int i;

  rec.rec_type = rec_type;
  rec.rec_len = (chksum ? rec_len + 1 : rec_len);
  if (fwrite (&rec, sizeof (rec), 1, p->f) != 1
      || fwrite (buffer, rec_len, 1, p->f) != 1)
    return (omflib_set_error (error));
  if (chksum)
    {
      sum = rec_type + (rec.rec_len & 0xff) + (rec.rec_len >> 8);
      for (i = 0; i < rec_len; ++i)
        sum += buffer[i];
      sum = (byte)(256 - sum);
      if (fputc (sum, p->f) == EOF)
        return (omflib_set_error (error));
    }
  if (rec_type == MODEND || rec_type == (MODEND|REC32))
    if (omflib_pad (p->f, p->page_size, FALSE, error) != 0)
      return (-1);
  return (0);
}


int omflib_write_module (struct omflib *p, const char *name, word *pagep,
                         char *error)
{
  char tmp_name[256+1];
  byte buf[256];
  long long_page;
  int len;

  omflib_module_name (tmp_name, name);
  long_page = ftell (p->f) / p->page_size;
  if (long_page > 65535)
    {
      strcpy (error, "Library too big -- increase page size");
      return (-1);
    }
  *pagep = (word)long_page;
  strcat (tmp_name, "!");
  if (omflib_add_pub (p, tmp_name, *pagep, error) != 0)
    return (-1);
  len = strlen (name);
  if (len > 255)
    {
      strcpy (error, "Module name too long");
      return (-1);
    }
  memcpy (buf+1, name, len);
  buf[0] = (byte)len;
  return (omflib_write_record (p, THEADR, len + 1, buf, TRUE, error));
}
