
if  $platform == 'windows'

  require 'Win32API'

  # code by Hee-Sob Park - posted here:
  # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/10006
  def system(command)
    $system_return_code= Win32API.new("crtdll", "system", ['P'], 'L').Call(command)
  end

  # code by Hee-Sob Park - posted here:
  # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/10006

  def `(command)
    popen = Win32API.new("crtdll", "_popen", ['P','P'], 'L')
    pclose = Win32API.new("crtdll", "_pclose", ['L'], 'L')
    fread = Win32API.new("crtdll", "fread", ['P','L','L','L'], 'L')
    feof = Win32API.new("crtdll", "feof", ['L'], 'L')
    saved_stdout = $stdout.clone
    psBuffer = " " * 128
    rBuffer = ""
    f = popen.Call(command,"r")
    while feof.Call( f )==0
      l = fread.Call( psBuffer,1,128,f )
      rBuffer += psBuffer[0..l]
    end
    pclose.Call f
    $stdout.reopen(saved_stdout)
    rBuffer
  end

  SND_MEMORY   = 0x00000004   # from "mmsystem.h"
  SND_FILENAME = 0x00020000
  PlaySound = Win32API.new("winmm", "PlaySound", ['P', 'L', 'L'], 'I')


  def playsound(name)

    if $dsp
      PlaySound.call(Defaults::SOUNDS[name], 0, SND_MEMORY)
    end
  end

  def close_sound
    playsound('SoundOff.wav')
    $dsp=nil
  end

  def open_sound
    $dsp= 'ok'
    playsound('SoundOn.wav')
  end

else
  #  powerpc-darwin5.3
  #  i686-linux
  # sparc-solaris2.8

  def system(command)
    super(command)
    $system_return_code= $?
  end

  SNDCTL_DSP_SPEED = 0xc0045002
  SNDCTL_DSP_CHANNELS =  0xc0045006
  SNDCTL_DSP_SETFMT = 0xc0045005

  if $cmd_audio=IO.popen("which artsplay"){|r| r.gets}
	$cmd_audio.strip!
    $stderr.puts "  using artsd (KDE)"
    def open_sound
      $dsp=true
      playsound('SoundOn.wav')
    end
    def close_sound
      playsound('SoundOff.wav')
      $dsp=false
    end
    def playsound(name,force=nil)
      #debug "#$cmd_audio #{Defaults::DEFS['sounds_path']+name} 2>/dev/null"
      system("#$cmd_audio #{Defaults::DEFS['sounds_path']+name} 2>/dev/null") if $dsp
    end

  else # use raw dsp device (oss-alsa)
$stderr.puts "  using raw device for sound"
    def open_sound

      begin
	$dsp=File.new(Defaults::DEFS['sound_device'],File::WRONLY|File::NONBLOCK)

	format=[8].pack("l")
	$dsp.ioctl(SNDCTL_DSP_SETFMT,format)

	#debug format.unpack("l")[0]

	channels=[1].pack("l")
	$dsp.ioctl(SNDCTL_DSP_CHANNELS,channels)

	#debug channels.unpack("l")[0]

	speed=[11025].pack("l")
	$dsp.ioctl(SNDCTL_DSP_SPEED,speed)

	#debug speed.unpack("l")[0]

	playsound('SoundOn.wav')
      rescue
	$stderr.puts("Cannot play sounds: #{$!}")
	$dsp=nil
      end

    end

    def close_sound

      return unless $dsp
      playsound('SoundOff.wav')
      sleep 1
      $dsp.close
      $dsp=nil
    end

    def playsound(name,force=nil)
      begin
	if $dsp
	  $dsp.syswrite(Defaults::SOUNDS[name] )
	  $dsp.flush
	end
      rescue
      end
    end

  end

end

