// Copyright (c) 1996-2002 Brian D. Carlstrom

package bdc.scheme.procedure;

import bdc.scheme.Scheme;
import bdc.scheme.SchemeException;
import bdc.scheme.Stack;
import bdc.scheme.exception.PrimitiveException;
import bdc.scheme.expression.Procedure1;
import java.io.IOException;

/**
    Primitive for Runtime.exec
*/
public class Exec extends Procedure1
{
    public Object apply1 (Stack stack) throws SchemeException
    {
        try {
            stack.addElement(stack.array[stack.inUse-1]);
            stack.array[stack.inUse-2] = Scheme.Null;
            return apply2(stack);
        }
        finally {
            stack.inUse -= 1;
        }
    }

    public Object apply2 (Stack stack) throws SchemeException
    {
        Object o1 = stack.array[stack.inUse-1];
        Object o2 = stack.array[stack.inUse-2];
        Object cmd[] = Scheme.list(o1, this).toArray();
        for (int i = 0; i < cmd.length; i++) {
            cmd[i] = Scheme.string(cmd[i], this);
        }
        String cmdArray[] = new String[cmd.length];
        System.arraycopy(cmd, 0, cmdArray, 0, cmd.length);


        String envArray[];
        if (o2 == Scheme.Null) {
            envArray = null;
        }
        else {
            Object env[] = Scheme.list(o2, this).toArray();
            for (int i = 0; i < env.length; i++) {
                env[i] = Scheme.string(env[i], this);
            }
            envArray = new String[env.length];
            System.arraycopy(env, 0, envArray, 0, env.length);
        }

        try {
            return Runtime.getRuntime().exec(cmdArray, envArray);
        }
        catch (IOException e) {
            throw new PrimitiveException(e);
        }
    }
}
