// BlinkenSisters - Hunt for the Lost Pixels
//     Bringing back the fun of the 80s
//
// (C) 2005-07 Rene Schickbauer, Wolfgang Dautermann
//
// See LICENSE for licensing information
//


#include <SDL.h>
#include <stdlib.h>
#include <string.h>
#include "../globals.h"
#include "../sound.h"
#include "../showtext.h"
#include "../debug.h"
#include "../errorhandler.h"
#include "guihandler.h"
#include "../cmdopts.h"

// Screen surface
SDL_Surface *gScreen = 0;

// Last iteration's tick value
#include <SDL_types.h>
Uint32 gLastTick;
bool soundOK;
char * playlist = NULL ;

/* global variable. declared as extern in cmdopts.cpp */
CMD_OPTS cmd_opt_data[] = {
/* {short option name, long option name, description, is_boolean, defaultvalue_boolean, defaultvalue_string} */
{"-v", "--version", "Print version information and exit", true, 0, NULL},
{"-h", "--help", "Command-line help", true, 0, NULL},
{"-p", "--playlist", "Filename of a m3u - playlist.", false, 0, NULL},
CMD_OPTS_END /* {"END", "END", "END", false, 0, "END"} */
};



// Entry point
int main(int ARGC, char*ARGV[])
{
        // Parse command-line options
        int numoptions ;
        if(!initCmdOpt(ARGC, ARGV)) {
                helpCmdOpt(ARGV[0]);
                exit(1);
        }
        numoptions = getCmdOptBool((char*)"-h");
        if (numoptions < 0) { helpCmdOpt(ARGV[0]) ; exit(1); } /* Error */
        if (numoptions > 0) { helpCmdOpt(ARGV[0]) ; exit(0); }

        playlist = getCmdOptString((char*)"-p"); /* Playlist */
        if (playlist != NULL ) {
                if (strlen(playlist) >=255) {  /* NOTE: Probably use a errormacro or something  similiar? */
                        fprintf(stderr,"Error. The playlist filename must be < 255 Characters. \n");
                        exit(1);
                }
        } ;


        numoptions = getCmdOptBool((char*)"-v");
        if (numoptions < 0) { exit(1); } /* Error */
        if (numoptions > 0) {
                printf("Blinkenplayer Version: " VERSION "\n");
                exit(0);
        }
        // END processing command-line arguments

	// Basic configuration init
	configInit(false);

	// Initialize SDL's subsystems
	Uint32 SDLinitflags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ;
	SDLinitflags = SDLinitflags | SDL_INIT_AUDIO ;
#ifndef CAVAC_RELEASEMODE
		SDLinitflags = SDLinitflags |SDL_INIT_NOPARACHUTE;
#endif // CAVAC_RELEASEMODE

	if ( SDL_Init(SDLinitflags) < 0 ) {
		fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
		exit(1);
	}

	// Initialize sound subsystem
	initSound();

	// Register SDL_Quit to be called at exit; makes sure things are
	// cleaned up when we quit.
	atexit(deInitGUI);
	atexit(deInitSound);
	atexit(SDL_Quit);

	// Attempt to create a SCR_WIDTHxSCR_HEIGHT window with 32bit pixels.

	gScreen = SDL_SetVideoMode(SCR_WIDTH, SCR_HEIGHT, 32, SDL_SWSURFACE);

	SDL_WM_SetCaption("BlinkenSisters Music Player", "BS Player"); // Window title: blinkensisters, Icon title: none
	SDL_WM_SetIcon(IMG_Load(configGetPath("lostpixels.png")), NULL); // Program icon for Window manager

	// Inits that need an initialized screen
	initShowText();
	initFPSCounter();
	initGUI(playlist);

	// If we fail, return error.
	if ( gScreen == NULL )
	{
		fprintf(stderr, "Unable to set %d x %d videomode: %s\n", SCR_WIDTH, SCR_HEIGHT, SDL_GetError());
		exit(1);
	}

	runGUI();

//	SDL_Delay(5000);

	return 0;
}

#if WIN32

#include <windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <fstream>

void RedirectIOToConsole()
{
	int hConHandle;
	long lStdHandle;
	CONSOLE_SCREEN_BUFFER_INFO coninfo;
	FILE *fp;

	// allocate a console for this app

	AllocConsole();
	// set the screen buffer to be big enough to let us scroll text

	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&coninfo);
	coninfo.dwSize.Y = 40;
	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),	coninfo.dwSize);

	// redirect unbuffered STDOUT to the console

	lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen( hConHandle, "w" );

	*stdout = *fp;
	setvbuf( stdout, NULL, _IONBF, 0 );

	// redirect unbuffered STDIN to the console
	lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen( hConHandle, "r" );
	*stdin = *fp;
	setvbuf( stdin, NULL, _IONBF, 0 );

	// redirect unbuffered STDERR to the console

	lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
	fp = _fdopen( hConHandle, "w" );
	*stderr = *fp;
	setvbuf( stderr, NULL, _IONBF, 0 );
}

void RedirectIOToFiles()
{
	FILE *fp;

	// allocate a console for this app


	// redirect unbuffered STDOUT to the console

	fp = fopen( "stdoutstderr_bp.txt", "w" );

	*stdout = *fp;
	setvbuf( stdout, NULL, _IONBF, 0 );

	// redirect unbuffered STDERR to the console
	*stderr = *fp;
	setvbuf( stderr, NULL, _IONBF, 0 );
}


int WINAPI WinMain(  HINSTANCE hInstance,      // handle to current instance
  HINSTANCE hPrevInstance,						// handle to previous instance
  LPSTR lpCmdLine,								// command line
  int nCmdShow									// show state
  )
{
	int argc = 0;
	int i=0;

    // Avoid some "unused parameter" warnings from gcc
    if(hInstance || hPrevInstance || hPrevInstance || nCmdShow) {
        argc = 0;
    }

	if (lpCmdLine[0]) // at least one paramteter
		argc = 1;
	while (lpCmdLine[i])
	{
		if (lpCmdLine[i] == ' ')
			argc++;
		i++;
	}
	argc++;  // add app name

	char** argv = (char**)malloc(argc*sizeof(char*));
	char appName[500];
	GetModuleFileNameA(0, appName, sizeof(appName));
	char* p;

	while((p= strrchr(appName,'\\')))
		*p= '/';
	p= argv[0] = (char*)malloc(strlen(appName)+10);
	strcpy(p,appName);

	i = argc-1;
	char* strptr = strrchr(lpCmdLine, ' ');
	while (strptr)
	{
		p=argv[i] = (char*)malloc(strlen(strptr+1)+10);
		strcpy( p,strptr+1);
		*strptr = '\0';
		i--;
		strptr = strrchr(lpCmdLine, ' ');
	}
	if (lpCmdLine[0])
	{
		p=argv[1] = (char*)malloc(strlen(lpCmdLine)+1);
		strcpy(p,lpCmdLine);
	}
	//RedirectIOToConsole();
	RedirectIOToFiles();

	return main(argc, argv);
}
#endif // WIN32

