// ----------------------------------------------------------------------------
//
// Copyright (C) Columbia University, 1994. All Rights Reserved.
// Sameer A. Nene, Shree K. Nayar, Hiroshi Murase
//
// See file LICENSE for details of software license agreement.
//
// ----------------------------------------------------------------------------
//
// fitbspl.C
//
// Author:               Sameer Nene
// Date:                 06/07/94
// Version:              1.0.0
// Modification History:
//
// Classes:
//
// Notes:
//   This command is used for fitting a quadratic bspline to a projected set of
//   points. See the man page for more details.
//   
// ----------------------------------------------------------------------------

#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include "errorscope.h"
#include "parser.h"
#include "dataset.h"
#include "bsplinecurve.h"
#include "bsplinesurface.h"
#include "bsplinevolume.h"
#include "ioutil.h"
#include "stringary.h"

int main(int argc, char **argv)
{
  int l, m;
  char buf[1024], *p;
  CommandParser cp(argc, argv, "V");
  ErrorScope::Error error;
  
  if((error = cp.error()) != ErrorScope::OK) {
    cerr << error << endl << "Exiting" << endl;
    exit(1);
  }
  
  StringAry &sa = cp.getObjectList();

  if(cp.getVerboseFlag() != 0)
    cerr << "Copyright \xA9 Columbia University, 1994. All Rights Reserved." << endl << "Sameer Nene, Shree Nayar, Hiroshi Murase" << endl << endl << "Doing BSpline fit..." << endl;
  
  for(l = 0, m = sa.getSize(); l < m; ++l) {
    DataSet ds;
    
    if((p = strrchr(strcpy(buf, sa[l]), '.')) != 0)
      *p = 0;

    if((error = IOUtil::get(&ds, sa[l])) != ErrorScope::OK) {
      cerr << error << ": " << sa[l] << endl << "Exiting" << endl;
      exit(1);
    }
    
    switch(ds.getSize()) {
    case 1:
      {
	BSplineCurve spl(ds.getSize(0));
	spl.fit(ds());
	if((error = IOUtil::put(spl, strcat(buf, ".spc"))) != ErrorScope::OK) {
	  cerr << error << ": " << buf << endl << "Exiting" << endl;
	  exit(1);
	}
      }
      break;
    case 2:
      {
	BSplineSurface spl(ds.getSize(0), ds.getSize(1));
	spl.fit(ds());
	if((error = IOUtil::put(spl, strcat(buf, ".sps"))) != ErrorScope::OK) {
	  cerr << error << ": " << buf << endl << "Exiting" << endl;
	  exit(1);
	}
      }
      break;
    case 3:
      {
	BSplineVolume spl(ds.getSize(0), ds.getSize(1), ds.getSize(2));
	spl.fit(ds());
	if((error = IOUtil::put(spl, strcat(buf, ".spv"))) != ErrorScope::OK) {
	  cerr << error << ": " << buf << endl << "Exiting" << endl;
	  exit(1);
	}
      }
      break;
    default:
      cerr << "Cannot fit " << ds.getSize() << " dimensional bsplines" << endl;
      exit(1);
    }
  }

  if(cp.getVerboseFlag() != 0)  
    cerr << endl << "Done" << endl;
  
  return 0;
}
