// File: C_ACM_input.c
// Date: 11/05/2001

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#ifndef M_PI
#define M_PI            3.14159265358979323846
#endif

// - Useful Macros -----------------------------------------------------
#define isNumber( c )  ( (c) >= '0' && (c) <= '9' )
#define toNumber( c )  ( (c) - '0' )
#define abs( x )       ( (x) < 0 ? -(x) : (x) )

#ifndef min
#define min( a, b )   ( (a) < (b) ? (a) : (b) )
#define max( a, b )   ( (a) > (b) ? (a) : (b) )
#endif

#define strcompare( str1, str2 )  ( strcmp( (str1), (str2) )
#define strequal( str1, str2 )    ( strcmp( (str1), (str2) ) == 0 )

#define deg( rad )    ( ( (rad) * 180.0 ) / (M_PI) )  /* Rad to Deg. */
#define rad( deg )    ( ( (deg) / 180.0 ) * (M_PI) )  /* Deg to Rad. */

#define dist2d( x1, y1, x2, y2 )  \
     ( sqrt( ( ( (x1) - (x2) ) * ( (x1) - (x2) ) ) + \
             ( ( (y1) - (y2) ) * ( (y1) - (y2) ) ) ) )
#define dist3d( x1, y1, z1, x2, y2, z2 )  \
     ( sqrt( ( ( (x1) - (x2) ) * ( (x1) - (x2) ) ) + \
             ( ( (y1) - (y2) ) * ( (y1) - (y2) ) ) + \
             ( ( (z1) - (z2) ) * ( (z1) - (z2) ) ) ) )

// Bit Tests: Returns 1 if bit 'b' is set (clear) in integer 'i'.
#define bit_set( i, b )    ( ( (i) & ( 1 << (b) ) ) >> (b) )
#define bit_clear( i, b )  (!bit_set( (i), (b) ))

// Bit Sets: Returns 'i' with bit 'b' set (clear).
#define set_bit( i, b )    ( (i) | ( 1 << (b) ) )
#define clear_bit( i, b )  ( (i) & ~( 1 << (b) ) )
#define toggle_bit( i, b ) ( (i) ^ ( 1 << (b) ) )

// - Input Routines ----------------------------------------------------

const char *DELIM = " \t\r\n";
char *tLine = 0;

void chompLine( char *line )  {
  int lastChar = strlen( line ) - 1;
  while( ( line[lastChar] == '\r' ) ||
         ( line[lastChar] == '\n' ) )  {
    line[lastChar--] = 0;
  }
}

int getLine( FILE *fp, char *line, int len )  {
  do  {
    if( fgets( line, len, fp ) == NULL ) return( 0 );
  } while( strlen( line ) == 0 );
  chompLine( line );
  tLine = ( char * )malloc( strlen( line ) + 1 );
  strcpy( tLine, line );
  return( 1 );
}

char *nextToken( void )  {
  char *tok = strtok( tLine, DELIM );
  tLine = NULL;
  return( tok );
}

// These are the routine you want to use.
// Each takes in a buffer of a given type, and returns whether it filled
// it or not.

int getInt( int &buf )  {
  char *tok = nextToken( );
  if( tok == NULL )  {
    return( 0 );
  }
  buf = atoi( tok );
  return( 1 );
}

int getFloat( float &buf )  {
  char *tok = nextToken( );
  if( tok == NULL )  {
    return( 0 );
  }
  buf = atof( tok );
  return( 1 );
}

int getStr( char *buf )  {
  char *tok = nextToken( );
  if( tok == NULL )  {
    return( 0 );
  }
  strcpy( buf, tok );
  return( 1 );
}

int getChar( char &buf ) {
  char *tok = nextToken( );
  if( tok == NULL )  {
    return( 0 );
  }
  buf = *tok;
  return( 1 );
}

void reset( char *line )  {
  tLine = ( char * )malloc( strlen( line ) + 1 );
  strcpy( tLine, line );
}

