class AppleScript {

    public static boolean execute(String appleScript, StringBuilder outputBuffer) {
        // No point in going any further if the current OS is not Mac OS X
        if(!OsFamily.MAC_OS_X.isCurrent())
            return false;

        LOGGER.debug("Executing AppleScript: "+appleScript);

        // Use the 'osascript' command to execute the AppleScript. The '-s o' flag tells osascript to print errors to
        // stdout rather than stderr. The AppleScript is piped to the process instead of passing it as an argument
        // ('-e' flag), for better control over the encoding and to remove any limitations on the maximum script size.
        String tokens[] = new String[] {
            "osascript",
            "-s",
            "o",
        };

        OutputStreamWriter pout = null;
        try {
            // Execute the osascript command.
            AbstractProcess process = ProcessRunner.execute(tokens, outputBuffer==null?null:new ScriptOutputListener(outputBuffer, AppleScript.getScriptEncoding()));

            // Pipe the script to the osascript process.
            pout = new OutputStreamWriter(process.getOutputStream(), getScriptEncoding());
            pout.write(appleScript);
            pout.close();

            // Wait for the process to die
            int returnCode = process.waitFor();

            LOGGER.debug("osascript returned code="+returnCode+", output="+ outputBuffer);

            if(returnCode!=0) {
            	LOGGER.debug("osascript terminated abnormally");
                return false;
            }

            return true;
        }
        catch(Exception e) {        // IOException, InterruptedException
            // Shouldn't normally happen
        	LOGGER.debug("Unexcepted exception while executing AppleScript", e);

            try {
                if(pout!=null)
                    pout.close();
            }
            catch(IOException e1) {
                // Can't do much about it
            }

            return false;
        }
    }

}