/*-----------------------------------------------------------------------------

Copyright (C) 2005, 2006, 2007.

A. Ronald Gallant
Post Office Box 659
Chapel Hill NC 27514-0659
USA   

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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

-----------------------------------------------------------------------------*/

#include "libsnp.h"
#include "libsmm.h"
#include "snpusr.h"
#include "snp.h"
#include "emm.h"

using namespace scl;
using namespace libsnp;
using namespace libsmm;
using namespace snp;
using namespace emm;
using namespace std;


bool emm::datblock::read_data(realmat& data)
{
   string pathname = "";
   return this->read_data(pathname,data);
}

bool emm::datblock::read_data(const string& pathname, realmat& data)
{
  data.resize(M, n);

  ifstream* dat_ifs_ptr;

  if (dsn[0] == '/') {
    dat_ifs_ptr = new ifstream(dsn.c_str());
    if (dat_ifs_ptr == 0 || !*dat_ifs_ptr) return false;
  }
  else {
    string filename = pathname + dsn;
    dat_ifs_ptr = new ifstream(filename.c_str());
    if (dat_ifs_ptr == 0 || !*dat_ifs_ptr) return false;
  }
  
  ifstream& dat_ifs = *dat_ifs_ptr;

  INTEGER max=0; 
  for (INTEGER i=1; i<=fields.size(); ++i) {
    max = fields[i] > max ? fields[i] : max ;
  }
  intvec idx(max,0);
  for (INTEGER i=1; i<=fields.size(); ++i) idx[fields[i]] = i;
  
  string discard;

  for (INTEGER t=1; t<=n; ++t) {
    for (INTEGER j=1; j<=max; ++j) {
      if (idx[j]==0) {
        dat_ifs >> discard;
      }
      else {
        dat_ifs >> data(idx[j],t);
      }
    }
    getline(dat_ifs,discard);
  }

  return dat_ifs.good();
}

