#import "MLController.h"
#include <mathlink/mathlink.h>

@implementation MLController

- (IBAction) calculate : (id) sender
{
    float sum = 0;
    int argc = 4;
    char *argv[5] = {"-linkname",
                     " '/Applications/Mathematica 4.2.app/Contents/MacOS/MathKernel' -mathlink",
                     "-linkmode",
                     "launch",
                     NULL};
    MLINK lp;
    MLEnvironment env;
    char *expr;
        
    expr = [[equationField stringValue] cString];
    
    env = MLInitialize(NULL);
    
    if (env == NULL)
    {
        NSBeep();
        NSRunAlertPanel(@"Error", @"MathLink Environment could not be initialized.", @"OK", nil, nil);
        [NSApp terminate:self];
    }
    
    lp = MLOpen(argc, argv);
    
    if (lp == NULL)
    {
        NSBeep();
        NSRunAlertPanel(@"Error", @"MathLink could not be opened.", @"OK", nil, nil);
        [NSApp terminate:self];
    }

    MLPutFunction(lp, "EvaluatePacket", 1);
    MLPutFunction(lp, "ToExpression", 1);
    MLPutString(lp, expr);
    MLEndPacket(lp);

    while (MLNextPacket(lp) != RETURNPKT) MLNewPacket(lp);

    MLGetFloat(lp, &sum);

    MLClose(lp);
    MLDeinitialize(env);
                                                       
    [answerField setFloatValue: sum];
}

@end
