/* libsizzle/fport.c - stdio file port handling
 
  Copyright (C) 1999, 2000 Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
 
  This is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2, or (at your option)
  any later version.
  
  This software 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 General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this package; see the file COPYING.  If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.  */

#if HAVE_CONFIG_H
# include <config.h>
#endif 

#if ENABLE_NLS
# include <libintl.h>
# define _(String) gettext(String)
#else
# define _(String) (String)
#endif

#include "alloc.h"
#include "eval.h"
#include "node.h"
#include "capi.h"
#include "port.h"
#include "fport.h"

/* Port type descriptor for stdio file ports.  */
zzz_object_t zzz_fport_port_type;

/* The following three variables hold stdio file ports for the three
   standard files stdin, stdout and stderr.  */
zzz_scm_t zzz_stdin_fport;
zzz_scm_t zzz_stdout_fport;
zzz_scm_t zzz_stderr_fport;

static void
fport_putc (int ch, zzz_scm_t port)
{
  fputc (ch, fport_file (port));
}

static int
fport_getc (zzz_scm_t port)
{
  return fgetc (fport_file (port));
}

static void
fport_ungetc (int ch, zzz_scm_t port)
{
  ungetc (ch, fport_file (port));
}

static void
fport_close (zzz_scm_t port)
{
  FILE * file = fport_file (port);

  if (file != stdin && file != stdout && file != stderr)
    fclose (file);
}

static void
fport_flush (zzz_scm_t port)
{
  fflush (fport_file (port));
}

static long
fport_seek (zzz_scm_t port, long ofs, int whence)
{
  fseek (fport_file (port), ofs, whence);
  return ftell (fport_file (port));
}

static long
fport_tell (zzz_scm_t port)
{
  return ftell (fport_file (port));
}

static int
fport_char_ready_p (zzz_scm_t port)
{
  return 0;
}

zzz_scm_t
zzz_make_fport (FILE * file, int read, int write)
{
  zzz_scm_t port;

  port = zzz_make_port (zzz_fport_port_type, file);
  port_read_p (port) = read;
  port_write_p (port) = write;
  return port;
}

result_t
zzz_init_fport (void)
{
  zzz_fport_port_type = zzz_define_port_type (fport_getc, fport_ungetc,
					      fport_putc, NULL,
					      fport_flush, fport_close,
					      fport_seek, fport_tell,
					      fport_char_ready_p,
					      NULL, NULL);
  zzz_protect_global (&zzz_stdin_fport);
  zzz_protect_global (&zzz_stdout_fport);
  zzz_protect_global (&zzz_stderr_fport);
  zzz_stdin_fport = zzz_make_fport (stdin, 1, 0);
  zzz_stdout_fport = zzz_make_fport (stdout, 0, 1);
  zzz_stderr_fport = zzz_make_fport (stderr, 0, 1);

  return RESULT_SUCCESS;
}

