/* io.C
 *
 * Some I/O routines
 *
 * Modified to used <stdio.h> instead of C++ iostreams, which seem to be buggy
 * on some machines.
 */


#include <stdio.h>
#include <ctype.h>
#include "seq.h"
#include "xy.h"


int lineNum = 0;


/* Read and collect text until the next blank line, skipping comments
 * and collapsing white space.  Return the text in a string.
 */

char *collectText( FILE *f )

{
  seq<char> buffer;
  int countNewlines = 0;
  bool readSpace = false;
  char c, *str;
  int i, j;

  while (isspace(c=getc(f)))
    ;

  if (feof(f) || c == EOF)
    return NULL;
  
  do {

    if (c == '#')
      while (c != '\n'  &&  (c=getc(f)) != EOF)
	;
    if (isspace(c)) {
      if (!readSpace) {
	buffer.add( ' ' );
	readSpace = true;
      }
    } else {
      buffer.add( c );
      readSpace = false;
    }
    if (c == '\n') {
      countNewlines++;
      lineNum++;
    } else
      countNewlines = 0;

  } while (countNewlines < 2  &&  (c=getc(f)) != EOF);

  // Skip initial white space

  for (i=0; i<buffer.size(); i++)
    if (buffer[i] != ' ')
      break;

  // Don't return an empty string

  if (i == buffer.size())
    return collectText(f);

  // Copy into a string to return

  str = new char[ buffer.size()-i+1 ];
  j = 0;
  while (i<buffer.size())
    str[j++] = buffer[i++];
  str[j] = '\0';

  return str;
}
