//=-- FSNormal.cpp - Normal Uncompressed File Streams ------------------------=
//
//   This class provides one implementation of the FileStreamPlugin interface.
//   This allows MagicStats to read from normal uncompressed files.  Pretty
//   simple stuff.
//
//=---------------------------------------------------------------------------=
//  This file is copyright (c) 1997-1998 Chris Lattner
//=---------------------------------------------------------------------------=

#include "FSNormal.h"

INIT_PLUGIN(FSNormal)

// PlainReadFileStream - Implemented in terms of STDIO calls.  
//
FSNormal::FSNormal(const char *Filename, int OpenCode, 
                   int &ErrorOccurred) {
  ErrorOccurred = 1; F = 0;
  if (OpenCode != FileStreamPlugin::OPEN_READ) return;

  F = fopen(Filename, "rb");
  if (F == 0) return;

  ErrorOccurred = 0;  // If we made it this far, no error occurred.
}

FSNormal::~FSNormal() {
  if (F != 0)
    fclose(F);
}

// seek - Seek the file to the specified position, return 0 if successful,
// true if seek failed.
//
int FSNormal::seek(long Position, int From) {
  return fseek(F, Position, From);
}

long FSNormal::tell() {
  return ftell(F);
}

FileStreamPlugin *FSNormal::getline(char *Buffer, int BufferLength, char Delimiter) {
  char c = Delimiter;
  int BytesWritten = 0;

  if (BufferLength == 0) return this;
  if (BufferLength == 1) {
    Buffer[0] = 0;
    return this;
  }

  c = fgetc(F);
  if (feof(F)) return 0;
  while (c != Delimiter) {
    *Buffer++ = c;
    BytesWritten++;
    if (BytesWritten == BufferLength-1) {
      *Buffer = 0;
      return this;
    }

    c = fgetc(F);
    if (feof(F)) break;
  }

  *Buffer = 0;
  return this;
}

int FSNormal::eof() {
  return feof(F);
}
