#include "predictresidual.h"

#include "sisco.h"

using casacore::BitFloat;
using casacore::sisco::CompressorState;

namespace algorithms {

void PredictResidual(TimeFrequencyData& data) {
  CompressorState state;
  std::vector<uint32_t> mantissa_data(data.ImageWidth());
  std::vector<int8_t> exponent_data(data.ImageWidth());
  for (size_t image_index = 0; image_index != data.ImageCount();
       ++image_index) {
    Image2D image(*data.GetImage(image_index));

    for (size_t y = 0; y != image.Height(); ++y) {
      std::span row_data(image.ValuePtr(0, y), image.Width());
      std::span mantissa_span(
          reinterpret_cast<std::byte*>(mantissa_data.data()),
          image.Width() * sizeof(uint32_t));
      std::span exponent_span(
          reinterpret_cast<std::byte*>(exponent_data.data()),
          image.Width() * sizeof(int8_t));
      QuadraticCompress2D(state, row_data, mantissa_span, exponent_span);
      for (size_t x = 0; x != image.Width(); ++x) {
        const float residual =
            BitFloat::FromCompressed(mantissa_data[x], exponent_data[x])
                .ToFloat();
        row_data[x] = residual;  // BitFloat::FromCompressed(mantissa_data[x],
                                 // exponent_data[x]).Mantissa();
      }
    }
    data.SetImage(image_index, Image2D::MakePtr(image));
  }
}

}  // namespace algorithms
