// compile using: g++ -o pm3d pm3d.cpp 

#include <fstream>
#include <iostream>
#include <sstream>
#include <stdlib.h>

using namespace std;

void help(){
  cout<<"Usage: pm3d INPUT OUTPUT"<<endl;
}

int main(int argc, char* argv[]){
  // opening the input file
  // hopefully a pgm image from gimp!
  if(argc<=1){
    cout<<"No input and or output file supplied!"<<endl;
    help();
    return 1;
  }    
  ifstream in (argv[1]);
  if(!in){
    cout<<"Cannot open input file!"<<endl;
    help();
    return 1;
  }

  // reading the header
  const int buffersize=100;
  char buffer[buffersize];
  stringstream buffer2;
  int sizey;
  int sizex;
  int i=0;
  while (!in.eof() )
  {
    in.getline(buffer,buffersize);
    if(i==2){
      // determining the image size
      buffer2<<buffer;
      buffer2>>sizex>>sizey;
    }
    if(i==3){
      // the first value does not belong to the image
      break;
    }
    i++;
  }

  // reading the image
  int data[sizey*sizex];
  i=0;
  while(!in.eof())
  {
    in.getline (buffer,buffersize);
    data[i] = atoi(buffer);
    i++;
  }

  // creating the output
  ofstream out(argv[2]);
  if(!out){
    cout<<"Cannot open output file!"<<endl;
    help();
    return 1;
  }
  for(int y=0; y<sizey; y++){
    for(int x=0; (x<sizex && y>0); x++){
      out << x << "\t" << sizey-y << "\t" << data[(y-1)*sizex+x] << endl;
      out << x+1 << "\t" << sizey-y << "\t" << data[(y-1)*sizex+x] << endl;      
    }
    out << endl;
    for(int x=0; x<sizex; x++){
      out << x << "\t" << sizey-y << "\t" << data[y*sizex+x] << endl;
      out << x+1 << "\t" << sizey-y << "\t" << data[y*sizex+x] << endl;      
    }
    out << endl;
  }
  // the last row
  for(int x=0; x<sizex; x++){
    out << x << "\t" << 0 << "\t" << data[(sizey-1)*sizex+x] << endl;
    out << x+1 << "\t" << 0 << "\t" << data[(sizey-1)*sizex+x] << endl;      
  }
  out.close();
  
  return 0;
}

