// ---------------------------------------------------------------------------
// - SpsCalls.cpp                                                            -
// - afnix:sps module - function calls implementation                        -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - This program  is  distributed in  the hope  that it will be useful, but -
// - without  any  warranty;  without  even   the   implied    warranty   of -
// - merchantability or fitness for a particular purpose.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2011 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Vector.hpp"
#include "SpsCalls.hpp"
#include "InputFile.hpp"
#include "Exception.hpp"

namespace afnix {

  // read a spreadsheet object by deserialization

  Object* sps_read (Runnable* robj, Nameset* nset, Cons* args) {
    // get the arguments
    Vector* argv = Vector::eval (robj, nset, args);
    long    argc = (argv == nilp) ? 0 : argv->length ();
    if (argc != 1) {
      delete argv;
      throw Exception ("argument-error", 
		       "invalid number of arguments with sps read");
    }
    try {
      Object* obj = argv->get (0);
      // check for an input stream
      InputStream* is = dynamic_cast <InputStream*> (obj);
      if (is != nilp) {
	Object* result = Serial::deserialize (*is);
	delete argv;
	return result;
      }
      // check for a string
      String* name = dynamic_cast <String*> (obj);
      if (name != nilp) {
	InputFile is (*name);
	Object* result = Serial::deserialize (is);
	delete argv;
	return result;
      }
      throw Exception ("type-error", "invalid object with sps read",
		       Object::repr (obj));
    } catch (...) {
      delete argv;
      throw;
    }
  }
}
