/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#include "board.h"
#include <fstream>
#include <istream>
#include <stdio.h>
#include <algorithm>
#include <iterator>
#include <utility>
#include <ctype.h>

Board::Board():
	m_board(0), m_blocks(0)
{
}

Board::Board(const char* filename):
	m_board(0), m_blocks(0)
{
	load(filename);
}

Board::~Board()
{
	clear();
}

void Board::load(const char* filename)
{
	clear();
	
	std::ifstream in(filename);
	if (!in.is_open()) {
		fprintf(stderr, "Couldn't open board file %s\n", filename);
		return;
	}
	in >> m_y >> m_x;
	in.ignore();
	m_board = new char[m_y*m_x+1];
	for(int i=0; i<m_y; ++i) {
		in.getline(m_board+i*m_x, m_x+1);
	}
	// change characters to hex digits; like '0' -> 0 and 'a' -> 10
	for(int i=0; i<m_y*m_x; ++i) {
		if (isdigit(m_board[i]))
			m_board[i] -= '0';
		else
			m_board[i] = tolower(m_board[i])-'a' + 10;
	}
	
	// allow empty lines etc. between tables
	while(!isdigit(in.peek()))
		in.ignore();
	
	char buf [1<<20];
	m_blocks = new BlockT[m_y*m_x+1];
	for(int i=0; i<m_y; ++i) {
		in.getline(buf+i*m_x, m_x+1);
	}
	for(int i=0; i<m_x*m_y; ++i) {
		m_blocks[i] = BlockT(buf[i]-'0');
		if (m_blocks[i] == START)
			m_startPlace = Coord2(i%m_x, i/m_x);
	}
	if (!in || !(in >> m_minTime))
		m_minTime = -1;
	
	if (!(in >> m_noTopView))
		m_noTopView = 0;
}

void Board::clear()
{
	delete[] m_board;
	delete[] m_blocks;
	m_board = 0;
	m_blocks = 0;
}
