/// GetDtiRbHandler.cpp
/**
*/ 

#include <wx/filename.h>
#include <wx/stdpaths.h>

#include <algorithm>
#include <set>
#include <math.h>

#include "Dictionary.h"
#include "DicomFile.h"
#include "StringConvert.h"
#include "Volume.h"
#include "SeriesHandler.h"
#include "GeDtiRbHandler.h"

using namespace jcs;

///
/**
*/ 
GeDtiRbHandler::GeDtiRbHandler(const std::string& seriesUid)
: SeriesHandler(seriesUid)
{
}


///
/**
*/ 
SeriesHandler::VolListType
GeDtiRbHandler::ReadVolIds(DicomFile& file)
{ 
  VolListType v = SeriesHandler::ReadVolIds(file);
  // Can't call default ReadVolId because of problem with trigger time.

  std::string acquisition_number;
  if (!file.Find("AcquisitionNumber", acquisition_number)) {
    wxLogError(_("Acquisition number not found"));
  }
  v.front().ids.push_back(acquisition_number);

  int image_number, number_of_slices;
  if (!file.Find("InstanceNumber", image_number)) {
    wxLogError(_("Instance number not found"));
  }

  Dictionary* Excite = Excite_Dictionary::Instance();
  if (!file.Find(Excite->Lookup("Locations_in_acquisition"), number_of_slices)) {
    wxLogError(_("Locations_in_acquisition not found"));
  }

  int vol_no = static_cast<int>(floor(static_cast<double>((image_number - 1))/number_of_slices) + 1);

  v.front().ids.push_back(itos(vol_no, 3));

  return v;

}


///
/**
*/ 
GradientInfo
GeDtiRbHandler::GetGradientInfo()
{
  GradientInfo info;

  int gradfileno;
  Dictionary* Excite = Excite_Dictionary::Instance();

  double bvalue;
  Find(Excite->Lookup("User_data_9"), bvalue);

  if (Find(Excite->Lookup("User_data_11"), gradfileno)) {
    wxString gradfilename = wxString::Format(_T("dwepi.%d.grads"), gradfileno);
    
    wxFileName gradfile(wxStandardPaths::Get().GetDataDir());
    gradfile.SetFullName(gradfilename);

    std::ifstream input((const char *) gradfile.GetFullPath());

    double value;
    input >> value;
    while (input.good()) {
      info.xGrads.push_back(value);
      input >> value;
      info.yGrads.push_back(value);
      input >> value;
      info.zGrads.push_back(value);
      info.values.push_back(bvalue);
      input >> value;
    }

    // GE -- do not correct
    // assuming one orientation in series
    //std::vector<double> r = orientations.at(0);
    //RotateGradInfo(info, r);

  }

  return info;
}
