
//
// Scilab startup script for the MuPAD<->Scilab link 
// using the UDX protocoll
//    The part for loading the UDX module inside Scilab is from
//    Eric Fleury  (Eric.Fleury@loria.fr) Small changes are made
//    here by Torsten Metzner.
//    The other stuff is from Torsten Metzner (tom@mupad.de)
//

//-------------------------------------------------------------------
// Defintion des variables d'environnement pour scilab//
//-------------------------------------------------------------------

// MuPAD_SCI is set by the Scilab Module of MuPAD
SCIP_ROOT  = getenv('MuPAD_SCI','NULL');
SCIP_ROOT  = SCIP_ROOT + "Scilab_modules";


// very important line DO NOT change otherwise the Scilab
// client is not started correctly in the background
lines(0);

// Setting the Scilab stack size to 8*5MB=40MB
stacksize(5000000) ;

// This is also necessary for UDX otherwise the libraries are not found
// SCI_ARCH is set in the script scilab_udx which starts Scilab
SCI_ARCH = getenv('SCI_ARCH','NULL') ;

//
// Avec UDX
//
exec(SCIP_ROOT + "/src-intersci/sce/udx.sce") ;
getf(SCIP_ROOT + "/src-intersci/macros/getcomname.sci") ;

// Important line for initializing the Scilab UDX module, so that
// some arguments are passed by reference saving stack space
intppty(int(funptr('udx_exit')/100)) ;

// Starting scilab as a client
global _MUP_port_ ;
_MUP_port_      =  udx_get_comname() ; 

global _MUP_channel_ ;
//_MUP_channel_   = udx_new("UNICAST_TCP_CLIENT", "NULL", _MUP_hostname_,                                   _MUP_port_, 0) ;
if SCI_ARCH == "windows" then
_MUP_channel_   = udx_new("UNICAST_SHARED_MEMORY_CLIENT", _MUP_port_, "NULL",                                      0, 0) ;
else
_MUP_channel_   = udx_new("UNICAST_UNIXDOMAIN_CLIENT", _MUP_port_, "NULL",                                      0, 0) ;
end;

udx_init(_MUP_channel_, "UDX_NEGOC_MODE") ;

// Define Status variables
global _MUPREQ_ ;   _MUPREQ_   = -2.0 ;
global _MUPANS_ ;   _MUPANS_   = -3.0 ;
global _MUPISERR_ ; _MUPISERR_ = -4.0 ;

// Global variables we need
global _MUP_ierr_ ;  _MUP_ierr_ = 0;
global _MUP_fail_ ;  _MUP_fail_ = 0;
global _MUP_vars_ ;  _MUP_vars_ = list();
global _MUP_incremental_stacksize_ ;
   _MUP_incremental_stacksize_ = 1000000 ;
global _MUP_action_ ; _MUP_action_ = 0 ;
global _MUP_mode_ ;
global _MUP_isSendError_ ; _MUP_isSendError_ = 0 ;
global _MUP_prog_ ;
global _MUP_FatalError_ ; _MUP_FatalError_ = -1111 ;

// Some useful global functions because of the stacksize error management
function _MUP_sendInternal_(channel, val, tag)
   err = execstr("udx_send(channel, val, tag)", 'errcatch') ;
   // If we have a stacksize error try to handle it
   if err == 17 then 
      incr = max(_MUP_incremental_stacksize_, length(val) + 1000) ;
      curr = stacksize() ;
      stacksize(curr(1)+incr);
      err = execstr("udx_send(channel, val, tag)", 'errcatch') ;
      // See if we have a strange problem
      if err <> 0 then
         error(err);
      end;
    else
      if err <> 0 then
         error(err) ;
      end;     
    end;
endfunction;

function _MUP_send_(channel, val, tag)
   err = execstr("_MUP_sendInternal_(channel, val, tag)", 'errcatch') ;
   if err <> 0 then
      // We have a real problem sending the result 
      // So we try to send at least the error code to MuPAD
      // if this fails, the link hangs. But we can't do more
      udx_send(channel, err, _MUPANS_);
      udx_send(channel, _MUPISERR_, _MUPISERR_);   
   else
     udx_send(channel, _MUPANS_, _MUPANS_);
   end;
endfunction;

// Handles the case for scilab::func() because it is important that the
// correct number of arguments are send back to MuPAD
function _MUP_sendE_(channel, val, tag)
   global _MUP_isSendError_ ;
   err = execstr("_MUP_sendInternal_(channel, val, tag)", 'errcatch') ;
   if err <> 0 then
      if _MUP_isSendError_ <> 0
         _MUP_isSendError_ = err ;
      end;
      // We have a real problem sending the result 
      // So we try to send at least the error code to MuPAD
      // if this fails, the link hangs. But we can't do more
      udx_send(channel, err, _MUPANS_);
   end;
endfunction;

function _MUP_RecvMupadData()
   global _MUP_prog_ ;
   global _MUP_action_ ; 
   global _MUP_ierr_ ;
   global _MUP_mode_ ;   
   global _MUP_vars_ ; 
   global _MUP_flag_ ;
   // receive the number of arguments
   // The following call must succeed otherwise we have a problem
   _MUP_flag_ = udx_recv(_MUP_channel_, _MUPREQ_ ) ;
   _MUP_args_ = udx_recv(_MUP_channel_, _MUPREQ_) ;

   // receive the mode: 
   // 0 = normal mode
   // 1 = func   mode
   _MUP_flag_ = udx_recv(_MUP_channel_, _MUPREQ_ ) ;
   _MUP_mode_ = udx_recv(_MUP_channel_, _MUPREQ_) ;

   // Receive the arguments:
   //  If there are errors while receiving the arguments handle this
   for _MUP_i_ = 1:_MUP_args_
      // Receive an action flag for the received MuPAD object
      // 0 : Do nothing with the received data
      // 1 : Convert the data to a full matrix      
      _MUP_fail_ = execstr('_MUP_flag_(_MUP_i_) = udx_recv(_MUP_channel_, _MUPREQ_ ) ; ', 'errcatch') ;      
      _MUP_fail_ = execstr('_MUP_vars_(_MUP_i_) = udx_recv(_MUP_channel_, _MUPREQ_ ) ; ', 'errcatch') ;
      // If there are problems receiving the data remember this but 
      // continue to receive all the data to clean the 
      // communication channel but the first error is the error
      // which is returned to MuPAD
      if _MUP_fail_ <> 0 then
         if _MUP_ierr_ == 0 then
            _MUP_ierr_ = _MUP_fail_ ;
         end;
      end;
   end;

   // Convert the complex numbers
   if _MUP_ierr_ == 0 then
      // Normally the following calls can't fail
      if SCI_ARCH == "windows" then
         udx_f772sci(_MUP_vars_) ;
      else
         pvm_f772sci(_MUP_vars_) ;
      end;
   end;
   // Convert sparse matrices to matrices
   for _MUP_i_ = 1:_MUP_args_
      if _MUP_flag_(_MUP_i_) == 1 then
         _MUP_vars_(_MUP_i_) = full(_MUP_vars_(_MUP_i_)) ;
      end;
   end;

   _MUP_fail_ = execstr('_MUP_flag_ = udx_recv(_MUP_channel_, _MUPREQ_ ) ; ', 'errcatch') ;
   _MUP_fail_ = execstr('_MUP_prog_ = udx_recv(_MUP_channel_, _MUPREQ_) ;',  'errcatch') ;

   // Only the first error is returned to MuPAD
   if _MUP_fail_ <> 0 then
      if _MUP_ierr_ == 0 then
         _MUP_ierr_ = _MUP_fail_ ;
      end;
   end;

   // Receive the kind of action
   // 0 = Do nothing because there was an error sending the data
   // 1 = compute the program
   _MUP_flag_ = udx_recv(_MUP_channel_, _MUPREQ_ ) ;
   _MUP_action_ = udx_recv(_MUP_channel_, _MUPREQ_) ;

endfunction;

// The following is necessary for sychronizing the shared memory interface
// if it is used. In all cases it signals the server (MuPAD) that
// everything is fine
udx_send(_MUP_channel_, _MUP_ierr_, _MUPANS_); 
 
// Execute the commands comeing from MuPAD
while 1 do
   _MUP_fail_ = execstr("_MUP_RecvMupadData();", 'errcatch' ) ;
      if _MUP_fail_ <> 0 then
        // We have a fatal error while receiving the data
        udx_send(_MUP_channel_, _MUPISERR_, _MUPISERR_);
        udx_send(_MUP_channel_, _MUP_FatalError_, _MUPANS_); 
   else
      if _MUP_action_ == 1 then
         if _MUP_ierr_ == 0 then
            // Execute the program
            _MUP_ierr_ = execstr(_MUP_prog_,'errcatch');
         end;
         // Handle the error case
         if _MUP_ierr_ <> 0 then
            udx_send(_MUP_channel_, _MUPISERR_, _MUPISERR_);
            udx_send(_MUP_channel_, _MUP_ierr_, _MUPISERR_);
            _MUP_ierr_=0;
         else
            // In the "func" mode the result is sended by the program
            // if there was no error
            if _MUP_mode_ == 0 then
               udx_send(_MUP_channel_, _MUPANS_, _MUPANS_);
               _MUP_send_(_MUP_channel_, _MUP_result_, _MUPANS_ ) ;
            else
               // scilab::func() fails while sending the result
               if _MUP_isSendError_ <> 0 then
                  udx_send(_MUP_channel_, _MUPISERR_, _MUPISERR_);
                  udx_send(_MUP_channel_, _MUP_isSendError_, _MUPANS_ ) ; 
               else
                  udx_send(_MUP_channel_, _MUPANS_, _MUPANS_);
               end;
            end;
         end;
      end;
   end;
end;
