#include <iostream>
#include <cstring>
#include <cstdlib>
#include <windows.h>
#include <mmsystem.h>
#include "str.h"

using namespace std;
using namespace string_tools;

class sndplay {
public:
   int run(int argc, char ** argv) {
      int rc = 0;
      if(argc != 2) {
         cout << "usage: sndplay <file>.wav | <file>.mp3" << endl;
         rc  = 1;
      }
      else {
         char soundfile[MAX_PATH];
         memset(soundfile, 0, MAX_PATH);
         size_t size = strlen(argv[1]);
         if(size >= MAX_PATH) {
            cerr << "file name too long..." << endl;
            rc = 1;
         }
         else {
            strncpy(soundfile, argv[1], size);
            if(ends_with(soundfile, ".mp3")) {
               string temp = "Open \"" + string(soundfile) + "\" Type MPEGVideo Alias myMp3";
               mciSendString(temp.c_str(), NULL, 0, NULL);
               mciSendString("Play myMp3 Wait", NULL, 0, NULL);
               mciSendString("Close myMp3", NULL, 0, NULL);
            }
            else if(ends_with(soundfile, ".wav")) {
               if(PlaySound(soundfile, NULL, SND_SYNC) == FALSE) {
                  cerr << "unable to play .wav file..." << endl;
                  rc = 1;
               }
            }
         }
      }
      return rc;
   }
};

#ifdef NO_MAIN
extern "C" {
extern int sndplay_main(int argc, char ** argv);
}
int sndplay_main(int argc, char ** argv)
#else
int main(int argc, char ** argv) 
#endif
{
   sndplay sound_player;
   int rc = sound_player.run(argc,argv);
   return rc;
}

