/* RawStreamSequence.java
 *
 * created: Mon Jun 14 1999
 *
 * This file is part of Artemis
 * 
 * Copyright (C) 1999  Genome Research Limited
 * 
 * This program 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
 * of the License, or (at your option) any later version.
 * 
 * This program 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 program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Header: /nfs/disk222/yeastpub/Repository/powmap/uk/ac/sanger/pathogens/embl/RawStreamSequence.java,v 1.5 2000/10/06 10:16:08 kmr Exp $
 */

package uk.ac.sanger.pathogens.embl;

import java.io.IOException;
import java.io.Writer;

/**
 *  This is a subclass of StreamSequence containing raw sequence.
 *
 *  @author Kim Rutherford
 *  @version $Id: RawStreamSequence.java,v 1.5 2000/10/06 10:16:08 kmr Exp $
 **/

public class RawStreamSequence extends StreamSequence {
  /**
   *  Create a new RawStreamSequence object from a stream containing raw
   *  bases.
   *  @param in_stream The stream to read from.  When the constructor returns
   *    the stream will at the next line after the sequence.
   **/
  public RawStreamSequence (final LinePushBackReader in_stream)
      throws IOException {
    super (in_stream);
  }

  /**
   *  Make a new RawStreamSequence containing the same sequence as the given
   *  Sequence.
   **/
  public RawStreamSequence (final Sequence sequence) {
    this (sequence.toString ());
  }

  /**
   *  Make a new RawStreamSequence containing the same sequence as the given
   *  String 
   **/
  public RawStreamSequence (final String sequence_string) {
    setFromString (sequence_string);
  }

  /**
   *  Return a new StreamSequence object that is a copy of this one.
   **/
  public StreamSequence copy () {
    return new RawStreamSequence (this);
  }

  /**
   *  Return the sequence type (RAW_FORMAT for this class).
   **/
  public int getFormatType () {
    return StreamSequenceFactory.RAW_FORMAT;
  }

  /**
   *  Read the header for this sequence (if any).
   **/
  protected void readHeader (final LinePushBackReader in_stream)
      throws IOException {
    // no header for raw sequence
  }

  /**
   *  This method will read raw sequence from the stream in this object
   *  removing whitespace as it goes.  No checks are made on the format of the
   *  sequence, apart from checking that the stream contains only letters.
   **/
  protected void readSequence (final LinePushBackReader in_stream)
      throws IOException {

    final int buffer_capacity = 50000;

    // we buffer up the sequence bases then assign them to sequence once all
    // bases are read
    StringBuffer sequence_buffer = new StringBuffer (buffer_capacity);

    while (true) {
      // temporary storage for reading lines
      String line = in_stream.readLine ();

      if (line == null) {
        // we have reached the end of file - break out of loop
        break;
      }

      line = line.toLowerCase ();
      
      if (line.equals ("*")) {
        // end of the sequence
        break;
      }

      if (line.startsWith (">")) {
//        sequence_buffer.append ('@');

        // ignore header lines
        continue;
      }
      
      for (int i = 0 ; i < line.length () ; ++i) {
        final char this_char = line.charAt (i);

        if (Character.isLetter (this_char) ||
            this_char == '.' ||
            this_char == '-' ||
            this_char == '*') {
          sequence_buffer.append (this_char);
        } else {
          if (Character.isSpaceChar (this_char)) {
            // just ignore it
          } else {
            throw new ReadFormatException ("sequence file contains a " +
                                           "character that is not a letter: " +
                                           this_char,
                                           in_stream.getLineNumber ());
          }
        }
      }
    }
    
    setFromString (sequence_buffer.toString ());
  }

  /**
   *  This is used by writeToStream (), writeRaw (), etc as temporary storage.
   *  It is a class member rather than a local variable so that we don't need
   *  to allocate a object for each call.
   **/
  final private StringBuffer line_buffer = new StringBuffer (90);

  /**
   *  Write this Sequence to the given stream.
   *  @param writer The stream to write to.
   **/
  public void writeToStream (final Writer writer)
      throws IOException {
    final String sequence = toString ();

    final int SEQUENCE_LINE_BASE_COUNT = 60;

    for (int i = 0 ; i < sequence.length () ; i += SEQUENCE_LINE_BASE_COUNT) {

      // get the bases in chunks of at most 60

      final int this_line_length;

      if (sequence.length () - i < SEQUENCE_LINE_BASE_COUNT) {
        this_line_length = sequence.length () - i;
      } else {
        this_line_length = SEQUENCE_LINE_BASE_COUNT;
      }

      line_buffer.setLength (0);
      line_buffer.ensureCapacity (60);

      line_buffer.append (sequence.substring (i, i + this_line_length));

      line_buffer.append ("\n");

      writer.write (line_buffer.toString ());

      if ((i / SEQUENCE_LINE_BASE_COUNT) % 100 == 0) {
        Thread.yield ();
      }
    }
  }
}
