#include <iostream>
#include <fstream>

int main( int argc, char** argv)
{
  /*-----------------------------------------------------------------------
   *  size of 3D data
   *-----------------------------------------------------------------------*/
  const int nLevels = 129;
  const int nRows   = 227;
  const int nCols   = 198;

  /*-----------------------------------------------------------------------
   *  allocate memory for volume
   *-----------------------------------------------------------------------*/
  int nVoxels = nLevels * nRows * nCols;
  unsigned char* volume = new unsigned char[nVoxels];
  
  /*-----------------------------------------------------------------------
   *   read volume from disk
   *-----------------------------------------------------------------------*/
  std::ifstream inFile( "whatisit_129x227x198_8bit.raw", std::ifstream::binary);
  inFile.read( reinterpret_cast<char*>(volume), nVoxels);

  
  /*-----------------------------------------------------------------------
   *  slice with maximum intensity projection
   *-----------------------------------------------------------------------*/
  int slice_nRows = nRows;
  int slice_nCols = nCols;
  
  unsigned char* slice = new unsigned char[ slice_nRows * slice_nCols];
  
  for( int row = 0; row < nRows; ++row)
  {
    for( int col = 0; col < nCols; ++col)
    {
      unsigned char maxVal = 0;
      for( int lev = 0; lev < nLevels; ++lev)
      {
        unsigned char current = volume[ lev * nRows * nCols 
                                        + row * nCols 
                                        + col];
        if( current > maxVal)
        {
          maxVal = current;
        }
        
      }
      int trgRow = row;
      int trgCol = col;
      slice[ trgRow * slice_nCols + trgCol] = maxVal;
            
    }
  }
  
  /*-----------------------------------------------------------------------
   *  save xy slice and free its  memory
   *-----------------------------------------------------------------------*/
  std::ofstream outFileXY( "mip.pgm", std::ofstream::binary);
  outFileXY << "P5\n"
          << slice_nCols << " " << slice_nRows << " 255\n";
  outFileXY.write( reinterpret_cast<char*>(slice), slice_nRows * slice_nCols);

  delete[] slice;
  
  /*-----------------------------------------------------------------------
   *  and finally free volume memory
   *-----------------------------------------------------------------------*/
  delete[] volume;
 

  return 0;
  
}
