#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <libspe2.h>

#include "iolaos.h"
#include "hello.h"

extern spe_program_handle_t hello;

globals_t globals __attribute__((aligned (16)));
locals_t *locals;

void show_help(void)
{
   printf("\nUsage: hello [OPTION] [NAME]\n"\
          "If you give your NAME, you are welcomed personaly...\n"\
          "Options:\n\n"\
          "\t-n  number of SPEs\n"\
          "\t-h  this text\n\n");
}

int main(int argc, char** argv)
{
	int i, spes = 1, c;

	spe_handle_t *spe_handle;

   opterr = 0;
     
   while ((c = getopt (argc, argv, "hn:")) != -1)
         switch (c)
           {
				case 'h':
				show_help();	
					break;
           case 'n':
             spes = atoi(optarg);
             break;
           case '?':
             if (optopt == 'n')
               fprintf (stderr, "Option -%c requires an argument.\n", optopt);
             else if (isprint (optopt))
               fprintf (stderr, "Unknown option `-%c'.\n", optopt);
             else
               fprintf (stderr,
                        "Unknown option character `\\x%x'.\n",
                        optopt);
             return 1;
           default:
             abort ();
           }
     
	if (optind < argc)
		strcpy(globals.name, argv[optind]);
	else
		strcpy(globals.name, "stranger");

	
	posix_memalign((void**)&locals, 16, sizeof(locals_t) * spes);

	for (i = 0; i < spes; i++)
		locals[i].some_data = spes - i;

	spe_handle = init_spes(&hello, spes, (void*)&globals, sizeof(globals_t), 
												 (void*)locals, sizeof(locals_t));

	start_spes(spe_handle);

	join_spes(spe_handle);

	free_spes(spe_handle);

	return 0;
}

