package bigloo;

import java.io.*;

public class input_console_port extends input_port
{
  private InputStream in= System.in;

  public input_console_port( final int  size )
  {
    super( "[stdin]", size );
  }

  public void close()
    throws IOException
  {
  }

  public boolean rgc_charready()
  {
    try
    {
      return (   (forward+1) < abufsiz)
              || (0 < in.available());
    }
    catch (final Exception _)
    {
      return false;
    }
  }

  public boolean reset_eof()
  {
    eof= false;
    reset_console();
    //clearerr();
    return true;
  }

  public final void reset_console()
  {
    matchstart= 0;
    matchstop= 0;
    abufsiz= 1;
    buffer[0]= (byte)'\0';
    lastchar= (byte)'\n';
  }

  public boolean rgc_fill_buffer()
    throws IOException
  {
    final int           bufsize= this.bufsiz;
    int                 abufsize= this.abufsiz;
    final int           matchstart= this.matchstart;

    // if the buffer is not full, we fill it */
    if (abufsize < bufsize)
      return rgc_size_fill_con_buffer( abufsize, bufsize-abufsize );

    if (0 < matchstart)
    {
      // we shift the buffer left and we fill the buffer */
      final byte[]      buffer= this.buffer;
      final int         movesize= abufsize - matchstart;

      for ( int i= 0 ; i < movesize ; ++i )
        buffer[i]= buffer[matchstart+i];
      abufsize-= matchstart;

      this.matchstart = 0;
      this.matchstop-= matchstart;
      this.forward-= matchstart;
      this.lastchar= buffer[matchstart-1];

      return rgc_size_fill_con_buffer( abufsize, bufsize-abufsize );
    }
    // we current token is too large for the buffer */
    // we have to enlarge it.                       */
    rgc_double_buffer();

    return rgc_fill_buffer();
  }

  final boolean rgc_size_fill_con_buffer( int        abufsize,
                                          final int  size )
    throws IOException
  {
    final byte[]        buffer= this.buffer;

    // we start reading at ABUFSIZE - 1 because we have */
    // to remove the '\0' sentinel that ends the buffer */
    final int           nbread= in.read( buffer, abufsize-1, size );

    if (nbread == -1)
      eof= true;
    else
      abufsize+= nbread;

    buffer[abufsize-1]= (byte)'\0';
    this.abufsiz= abufsize;
    return (0 < this.abufsiz);
  }
}
