/*
  crossword -- a crossword game
  Copyright (C) 2000 Falk Hueffner

  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

  $Id: Rules.cc,v 1.8 2000/11/29 00:03:42 falk Exp $
*/

#include <assert.h>
#ifdef HAVE_SSTREAM
# include <sstream>
#else
# include <strstream>
#endif

#include "Rules.hh"

using namespace std;

int Rules::_xsize;
int Rules::_ysize;
int Rules::_numFields;
int Rules::_maxRackTiles;
Pos Rules::_startPos;
vector<unsigned int> Rules::frequencies;
vector<unsigned int> Rules::scores;
vector<unsigned int> Rules::letterMultipliers;
vector<unsigned int> Rules::wordMultipliers;

void Rules::readRules(istream& in) {
    string line;
    assert(getLine(in, line));	// read number of tiles in rack
#ifdef HAVE_SSTREAM
    istringstream lineStream(line);
#else
    istrstream lineStream(line.c_str());
#endif
    lineStream >> _maxRackTiles;

    frequencies = vector<unsigned int>(NUM_CHARS);
    scores  = vector<unsigned int>(NUM_CHARS);

    while (getLine(in, line)) {
#ifdef HAVE_SSTREAM
	istringstream lineStream(line);
#else
	istrstream lineStream(line.c_str());
#endif
	unsigned char c;
	int f, s;
	lineStream >> c >> f >> s;
	frequencies[c] = f;
	scores[c] = s;
    }
}

void Rules::readLayout(istream& in) {
    string line;
    _xsize = _ysize = 0;
    wordMultipliers.clear();
    letterMultipliers.clear();
    Pos pos = 0;
    while (getline(in, line)) {
	++_ysize;
	if (_xsize == 0)
	    _xsize = line.length();
	else
	    assert(_xsize == line.length());

	for (int i = 0; i < line.length(); ++i) {
	    int w = 1, l = 1;
	    switch(line[i]) {
	    case '+':
		l = 2; break;
	    case '#':
		l = 3; break;
	    case '2':
		w = 2; break;
	    case '3':
		w = 3; break;
	    case '*':
		_startPos = pos; w = 2; break;
	    }
	    wordMultipliers.push_back(w);
	    letterMultipliers.push_back(l);
	    ++pos;
	}
    }

    _numFields = _xsize * _ysize;
}


bool Rules::getLine(istream& in, string& line) {
    while (true) {
	if (!getline(in, line))
	    return false;
	if (line.find('#') != string::npos)
	    line = line.substr(0, line.find('#'));
	//cout << line << endl;
	if (line.find_first_not_of(" \t") != string::npos)
	    return true;
    }

}

