/*

Copyright (C) 2009 VZLU Prague, a.s., Czech Republic

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.

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. See the GNU General Public License for more
details.

You should have received a copy of the GNU General Public License along with
this program; if not, see <http://www.gnu.org/licenses/>.

*/

// Author: Jaroslav Hajek <highegg@gmail.com>

#include <octave/oct.h>
#include <octave/load-save.h>

#include "minimal-load-save.h"

DEFUN_DLD (fload, args, ,
  "-*- texinfo -*-\n\
@deftypefn {Loadable Function} {@var{var} =} fload (@var{fid})\n\
Loads a single variable of any type from a binary stream, where it was previously\n\
saved with fsave.\n\
@end deftypefn")
{
  octave_value retval;
  int nargin = args.length ();

  if (nargin == 1)
    {
      int fid = OCTAVE__INTERPRETER__STREAM_LIST__GET_FILE_NUMBER (args (0));

      OCTAVE__STREAM octs = OCTAVE__INTERPRETER__STREAM_LIST__LOOKUP
        (fid, "fload");
      std::istream *is = octs.input_stream ();

      if (is)
        {
          bool swap;
          OCTAVE__MACH_INFO::float_format flt_fmt;

          // This wouldn't be necessary within the local machine, but
          // fload may be used outside parcellfun and the current
          // version of parcellfun will become deprecated anyway since
          // it forkes Octave.
          if (minimal_read_header (*is, swap, flt_fmt))
            {
              error ("fload: could not read binary header");

              return retval;
            }

          if (minimal_read_data (*is, retval, swap, flt_fmt))
            {
              error ("fload: failed to extract value");

              return retval;
            }
        }
      else
        error ("fload: stream not opened for reading.");
    }
  else
    print_usage ();

  return retval;
}
