#############################################################################
##
#W  omget.g             OpenMath Package         Andrew Solomon
##
#H  @(#)$Id: omget.g,v 1.13 2006/01/03 14:40:42 gap Exp $
##
#Y  Copyright (C)  1997,  Lehrstuhl D fuer Mathematik,  RWTH Aachen,  Germany
#Y  (C) 1998 School Math and Comp. Sci., University of St.  Andrews, Scotland
##
##  Reads an XML encoded object from an input stream and returns
##  a GAP object.
##
##


# create a temporary directory that will be used by OMGetObject

BindGlobal( "OMDirectoryTemporary", DirectoryTemporary() );


#############################################################################
##
#F  OMGetObject 
##
##  <stream> is an input stream with an OpenMath object on it.
##  Takes precisely one object off <stream> (using pipeobj)
##  and puts it onto an output stream connected to a named
##  pipe (from.gap) to gpipe, which parses the object into
##  a byte stream and returns it on "to.gap". 
##  From there the byte stream is turned into a GAP object
##  by OMgetObjectByteStream.
##

InstallGlobalFunction("OMGetObject",
function(stream)
  local
    instream, outstream, # streams from gpipe and to gpipe
    fromgap, togap, # named pipes 
		gpipe_exec, # filename of gpipe executable
		success, # whether PipeOpenMathObject worked
		r;

  gpipe_exec := Filename(DirectoriesPackagePrograms("openmath"), "gpipe");

  if gpipe_exec = fail  then
      Error( "package ``openmath'': the program `gpipe' is not compiled;\n",
      "see the README file or the dvi/ps/pdf manual of the package ``openmath''.\n",
      "Without this program, conversion from OpenMath to GAP cannot be performed.\n" );
  fi;

  
  # make names for the named pipes: pout: GAP->gpipe, pin: gpipe->GAP
  fromgap := Filename( OMDirectoryTemporary, "from.gap" );
  togap := Filename( OMDirectoryTemporary, "to.gap" );

  # remove pipes, in case they exist from a previous call of OMGetObject
  RemoveFile(fromgap);
  RemoveFile(togap);
  
  # create the pipes
  Exec(Concatenation(["mkfifo ",fromgap]));
  Exec(Concatenation(["mkfifo ",togap]));

  # now run gpipe in the background
  Exec(Concatenation(["cat ",fromgap," | ",gpipe_exec," -u -  ",togap," &"]));

  instream := InputTextFile(togap);
  outstream := OutputTextFile(fromgap, false);
  SetPrintFormattingStatus(outstream, false);
  success := PipeOpenMathObject(stream, outstream);
  CloseStream( outstream );
  if success <> true  then
    CloseStream( instream );
    Error( "OpenMath object not retrieved" );
  fi;

  # feed in the object to outstream
  r := OMgetObjectByteStream(instream);
  CloseStream( instream );
  return r;

end);



