#include "Table_from_file.h"

#include "User.h"

#include <string>
#include <fstream>
#include <sstream>

namespace MM
{
Table_from_file::
Table_from_file (Text const & filename, Line * prototype)
:
    Table_impl (prototype)
{
    using namespace std;
    string      line;
    ifstream    file (filename.c_str());

    if (file.fail())
    {
        Text message ("Cannot open file ");
        message += filename;
        to_user(). error (message);
        throw message;
    }

    while (getline (file, line))
    {
        istringstream   in_line (line);
        string          substr;
        Line *          record = create_line();
        Own <Line>      janitor (record);
    
        for (int i=0;  i<width();  ++i)
        {
            getline (in_line, substr, '\t');
            istringstream   in (substr);

            Any                  &  cell = (*record)[i];
            const std::type_info &  type = cell.type();

            if (type == typeid (Text) ||
                type == typeid (char *))
            {
                cell = substr.c_str();
            }
            else if (type == typeid (string))
            {
                cell = substr;
            }
            else if (type == typeid (int))
            {
                int value;
                in >> value;
                cell = value;
            }
            else if (type == typeid (double))
            {
                double value;
                in >> value;
                cell = value;
            }
            else if (type == typeid (long))  
            {
                long value;
                in >> value;
                cell = value;
            }
            else if (type == typeid (float)) 
            {
                float value;
                in >> value;
                cell = value;
            }
            else ;
        }

        janitor.orphan();
        adopt (record);
    }
}

}//MM
