// Copyright (c) 1996-2002 Brian D. Carlstrom

package bdc.scheme.procedure;

import bdc.scheme.Scheme;
import bdc.scheme.Stack;
import bdc.scheme.exception.ArgumentTypeException;
import bdc.scheme.expression.Procedure1;
import java.io.PrintWriter;

/**
    (write-char x) (write-char x y)
*/
public class WriteChar 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];

        char        ch   = Scheme.character(o1, this);
        PrintWriter port = Scheme.printWriter(o2, this);

        if (ch == '\n') {
            port.println();
        }
        else {
            port.print(ch);
        }
        return Scheme.Unspecified;
    }
}
