// Copyright (c) 1996-2002 Brian D. Carlstrom

package bdc.scheme.procedure;

import bdc.scheme.Scheme;
import bdc.scheme.Stack;
import bdc.scheme.Writer;
import bdc.scheme.exception.ArgumentTypeException;
import bdc.scheme.expression.Procedure1;
import java.io.PrintWriter;

/**
    (display x) (display x y)
*/
public class Display extends Procedure1
{

    public Object apply1 (Stack stack) throws ArgumentTypeException
    {
        try {
            stack.addElement(stack.array[stack.inUse-1]);
            stack.array[stack.inUse-2] = stack.currentOutputPort;
            return apply2(stack);
        }
        finally {
            stack.inUse -= 1;
        }
    }

    public Object apply2 (Stack stack) throws ArgumentTypeException
    {
        Object o1 = stack.array[stack.inUse-1];
        Object o2 = stack.array[stack.inUse-2];

        PrintWriter port = Scheme.printWriter(o2, this);

        if (o1 instanceof char[]) {
            port.print((char[])o1);
        }
        else if (o1 instanceof String) {
            port.print((String)o1);
        }
        else if (o1 instanceof Character) {
            port.print(((Character)o1).charValue());
        }
        else {
            port.print(Writer.write(o1));
        }
        return Scheme.Unspecified;
    }
}
