<?php

  // Copyright (C) 2012 Dmitry Smirnov

  if($argc < 2)
    exit('Usage: '.$argv[0].' <path>');

  define('PATH', $argv[1]);
  define('ENDL', "\n");
  define('TAB', "\t");

  $commonPacks = array();
  $levelsPacks = array();
  $mapPacks = array();
  $sounds = scandir(PATH);

  function saveSoundPacks($name, $packs)
  {
    foreach($packs as $level => $pack)
    {
      $fp = fopen($name.$level.'.xml', 'wt');
      if($fp === false)
        continue;

      fwrite($fp, '<?xml version="1.0"?>'.ENDL);
      fwrite($fp, '<SoundPack>'.ENDL);

      foreach($pack as $sound)
      {
        if(!preg_match('/(.*)\.ogg$/', $sound, $matches))
          continue;

        fwrite($fp, TAB.'<SoundCue Name="'.$matches[1].'" GroupID="3" TrackPlayStates="true">'.ENDL);
        fwrite($fp, TAB.TAB.'<Sound Filename="'.PATH.'/'.$sound.'" />'.ENDL);
        fwrite($fp, TAB.'</SoundCue>'.ENDL);
      }

      fwrite($fp, '</SoundPack>'.ENDL);
      fclose($fp);
    }
  }

  function saveCommonSoundPack($name, $pack)
  {
    $fp = fopen($name.'.xml', 'wt');
    if($fp === false)
      continue;

    fwrite($fp, '<?xml version="1.0"?>'.ENDL);
    fwrite($fp, '<SoundPack>'.ENDL);

    foreach($pack as $sound)
    {
      if(!preg_match('/(.*)\.ogg$/', $sound, $matches))
        continue;

      fwrite($fp, TAB.'<SoundCue Name="'.$matches[1].'" GroupID="3" TrackPlayStates="true">'.ENDL);
      fwrite($fp, TAB.TAB.'<Sound Filename="'.PATH.'/'.$sound.'" />'.ENDL);
      fwrite($fp, TAB.'</SoundCue>'.ENDL);
    }

    fwrite($fp, '</SoundPack>'.ENDL);
    fclose($fp);
  }

  foreach($sounds as $sound)
  {
    if(preg_match('/^L(\d+)_Map_/', $sound, $matches))
    {
      $levelNum = $matches[1];
      $mapPacks[$levelNum][] = $sound;
    }
    else if(preg_match('/^L(\d+)_/', $sound, $matches))
    {
      $levelNum = $matches[1];
      $levelsPacks[$levelNum][] = $sound;
    }
    else
    {
      $commonPacks[] = $sound;
    }
  }

  saveSoundPacks('SoundPackLevel', $levelsPacks);
  saveSoundPacks('SoundPackMapLevel', $mapPacks);
  saveCommonSoundPack('CommonPhrases', $commonPacks);

?>
