/*  The Blue Mango Quest
 *  Copyright (c) Clément 'phneutre' Bourdarias (code)
 *                   email: phneutre@users.sourceforge.net
 *                Guillaume 'GuBuG' Burlet (graphics)
 *                   email: gubug@users.sourceforge.net
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifdef WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include <SDL/SDL.h>

#ifdef HAVE_SDL_MIXER
# include <SDL/SDL_mixer.h>
# include "sounds.h"
#endif

#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include "font.h"


#include "world_geometry.h"
#include "world_building.h"
#include "map.h"
#include "timers.h"
#include "hut.h"
#include "bonus.h"
#include "mango.h"
#include "game_loop.h"
#include "system_gl.h"
#include "map_seeking.h"
#include "menus.h"


#ifndef WIN32
#   include <unistd.h>
#   include <sys/types.h>
#   include <pwd.h>
#   include <dirent.h>
#   include <sys/time.h>
#   include <sys/types.h>
#   include <dirent.h>
#endif

#include "file_utils.h"
#include "config_file.h"

char *filename = 0;
extern options_t *options;
extern game_data_t *world;
char is_filename_given=0;
int nosound_flag=0;

void clean_exit(void);
void initialize_system();
void analyze_args();

void usage_error(void)
{
  fprintf(stderr, "Usage:  shmixman3d [file] ..\n\n");
  /* fprintf(stderr,"Options:\n" " -w force world (0/1/2/3)\n\n"); */
  exit(1);
}

#define GET_NUMBER(flag,num)	num = 0; \
				if (!*p && argc && isdigit(**argv)) \
					p = *argv++, --argc; \
				while (isdigit(*p)) { \
					flag = 1; \
					num = (num * 10) + (*p++ - '0'); \
				}

void analyze_args(int argc, char *argv[])
{
  char c, *p;

  ++argv;

  if (!--argc)
    {
      /* no argument given */
      //filename = new char[MAX_PATH];
    }

  while (argc--)
    {
      p = *argv++;

      if (*p == '-') {
	if (strlen(p) > 2) {
	  /* big argument */
	  if (strcmp(p,"--version")==0) {
	    fprintf(stdout, "The Blue Mango Quest version %s built on %s, %s --\n", VERSION, __DATE__, __TIME__);
	    exit(1);
	  }
	  
	  if ( (strcmp(p,"--nosound")==0)||( (strcmp(p,"-nosound")==0))) {
	    nosound_flag=1;
	    fprintf(stdout, "Sound disabled by request.\n");
	  }
	}      
	
	else {
	  /* small argument */

	  if (!*++p)                /* incomplete argument */
	    usage_error();
	  while ((c = *p++))
	    {
	      switch (c)
		{
		    
		case 'v':
		  fprintf(stdout, "The Blue Mango Quest version %s built on %s, %s --\n", VERSION, __DATE__, __TIME__);
		  exit(0);
		  break;

		case 'h':

		default:
		  usage_error();
		}
	    }
	  //if (!argc)
	    //{
	      /* no filename given */
	      //filename = new char[MAX_PATH];
	      //printf("Using default map %s.\n", filename);
        
	    //}

	}
      }
    
      else
	{
	  filename = new char[MAX_PATH];
	  is_filename_given=1;
	  if (search_map_file(filename, p, MAX_PATH)) 
	    {
	      fprintf(stderr,"Error: couldn't find map\n");
	      exit(1);
	    }
	}
      
    }

  if (is_filename_given == 0)
    filename = new char[MAX_PATH];
}

int main(int argc, char *argv[])
{

#ifdef WIN32
  if (!getenv("SDL_VIDEODRIVER"))
    putenv("SDL_VIDEODRIVER=windib");
#endif

  atexit(clean_exit);
  printf("\n-- The Blue Mango Quest version %s --\n", VERSION);
  printf
    ("(c) 2000-2001 Clément Bourdarias (code), Guillaume Burlet (graphics)\n\n");

  check_private_dir();
  analyze_args(argc, argv);
  printf("\n-- STEP 1: Initialization --\n");

  register_map_names();
  register_world();

  read_config_file();
  initialize_system();

  init_GL();  
  load_shared_objects();

  /* shortcut */
  if (is_filename_given) {
    while (world->need_to_restart_map) {
      load_map(filename);
      mainLoop();
      unload_map();
    }
  }

  else {
    printf("\n-- STEP 3: Falling into the menus loop --\n");
    main_menu_loop();
    printf("-- Exiting from the menus loop --\n");
  }

  unload_shared_objects();
  return 0;
}

void clean_exit()
{
  fprintf(stderr, "Exiting via clean_exit()\n");

#ifdef HAVE_SDL_MIXER
  //if (options->use_sound) Mix_CloseAudio();
#endif

  SDL_Quit();
  printf("\n");
}

void initialize_system()
{
  SDL_Surface *icone=0;
  int audio_rate;
  Uint16 audio_format;
  int audio_channels;

  world->screen = NULL;

  printf("Initializing video and timer... ");

  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_CDROM | SDL_INIT_TIMER) < 0)
  {
    fprintf(stderr, "\nFatal Error : %s\n", SDL_GetError());
    exit(MAX_PATH);
  }

  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);

  world->videoFlags  = SDL_OPENGL;
  world->videoFlags |= SDL_GL_DOUBLEBUFFER;
  world->videoFlags_fs=world->videoFlags | SDL_FULLSCREEN;

#ifndef WIN32
  if (options->fullscreen) 
    world->screen=SDL_SetVideoMode(800, 600, 16, world->videoFlags_fs);
  else 
    world->screen=SDL_SetVideoMode(800, 600, 16, world->videoFlags);

#else
  world->screen=SDL_SetVideoMode(800, 600, 16, world->videoFlags_fs);
#endif  
  if  (world->screen == NULL)
  {
    fprintf(stderr, "\nError (OpenGL) : %s\n", SDL_GetError());
    SDL_Quit();
    exit(2);
  }

  SDL_WM_SetCaption("The Blue Mango Quest v." VERSION, NULL);

  SDL_ShowCursor(SDL_DISABLE);
  SDL_WM_GrabInput(SDL_GRAB_ON);

  icone = SDL_LoadBMP(SHXMAN_DATA "icone.bmp");
  SDL_WM_SetIcon(icone, NULL);

#ifdef WIN32
  srand(time(NULL));
#else
  srandom(time(NULL));
#endif

  printf("done!\n");

#ifdef HAVE_SDL_MIXER
  if (options->use_sound) {
    printf("Audio: ");
    audio_rate = MIX_DEFAULT_FREQUENCY;
    audio_format = MIX_DEFAULT_FORMAT;
    audio_channels = 2;
    
    if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, 1024) < 0) {
      fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
      exit(1);
    }
    else {
      Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
      printf("opened audio at %d Hz %d bit %s", audio_rate,
	     (audio_format&0xFF),
	     (audio_channels > 1) ? "stereo" : "mono");
      putchar('\n');
    }

    Mix_ReserveChannels(4);
  }
  else fprintf(stderr,"NOT initializing sound\n");
#endif
}
