Esempio n. 1
0
McAccess::McAccess(int port, int slot) {
	_port = port;
	_slot = slot;
	ee_sema_t newSema;
	newSema.init_count = 1;
	newSema.max_count = 1;
	_sema = CreateSema(&newSema);

	assert(mcInit(MC_TYPE_MC) >= 0);
}
Esempio n. 2
0
void init_basic_modules(const char *path)
{

	char *gz;
	int gz_size;

	module_t basic_modules[7] =
	{
		{              "sio2man", "freesio2.irx", NULL, 0, 0 },
		{                "mcman",    "mcman.irx", NULL, 0, 0 },
		{               "mcserv",   "mcserv.irx", NULL, 0, 0 },
		{              "mtapman", "freemtap.irx", NULL, 0, 0 },
		{               "padman",  "freepad.irx", NULL, 0, 0 },
		{     "IOX/File_Manager",   "iomanX.irx", NULL, 0, 0 },
		{ "IOX/File_Manager_Rpc",  "fileXio.irx", NULL, 0, 0 }
	};

	gz = init_modules_tgz(path,&gz_size);

	init_load_irx(gz, gz_size, basic_modules, 7);

	// Init various libraries
	mcInit(MC_TYPE_MC);

	mtapInit();

	padInit(0);

	mtapPortOpen(0);
	mtapPortOpen(1);

	if (!basic_modules[6].result)
	{
		fileXioInit();
	}
	else
	{
		// Problem initializing fileXio modules
		fioInit();
	}

	if (gz != (char*)modules_tgz)
	{
		free(gz);
	}

}
Esempio n. 3
0
int main() {

	int fd, ret;
	int i;

	// Initialise
	SifInitRpc(0);
	LoadModules();
#ifdef TYPE_MC
	if(mcInit(MC_TYPE_MC) < 0) {
		printf("Failed to initialise memcard server!\n");
		SleepThread();
	}
#else
	if(mcInit(MC_TYPE_XMC) < 0) {
		printf("Failed to initialise memcard server!\n");
		SleepThread();
	}
#endif

	printf("\nMemory card library example code - by Sjeep\n\n");

	// int mcGetInfo(int port, int slot, int* type, int* free, int* format);
	//
	// mcGetInfo retrieves memcard state info, such as the memcard type, free blocks and
	// the format status.
	//
	// mcGetInfo is passed pointers to three variables, which are filled upon completion
	// of the getinfo rpc command. The mcGetInfo return values are as follows:
	//
	//  0 : The same memory card has been connected since the last mcGetInfo call.
	// -1 : Switched to a formatted memory card.
	// -2 : Switched to an unformatted memory card.
	// -10 or less : The memory card could not be detected.
	//
	// NOTE: With the MCMAN/MCSERV, *format is always returned as 0 regardless of if
	//       if the memcard is formatted or not.

	// Since this is the first call, -1 should be returned.
	mcGetInfo(0, 0, &mc_Type, &mc_Free, &mc_Format);
	mcSync(0, NULL, &ret);
	printf("mcGetInfo returned %d\n",ret);
	printf("Type: %d Free: %d Format: %d\n\n", mc_Type, mc_Free, mc_Format);

	// Assuming that the same memory card is connected, this should return 0
	mcGetInfo(0,0,&mc_Type,&mc_Free,&mc_Format);
	mcSync(0, NULL, &ret);
	printf("mcGetInfo returned %d\n",ret);
	printf("Type: %d Free: %d Format: %d\n\n", mc_Type, mc_Free, mc_Format);

	// int mcGetDir(int port, int slot, char *name, unsigned mode, int maxent, mcTable* table);
	//
	// mcGetDir retrieves the directory structure of a specific path on the memory card.
	//
	// The filename is relative to the root of the memory card. Wildcards such as '*' and '?'
	// may be used. "maxent" is the maximum number of mcTable elements your array specified
	// by "table" can hold. The mc_getdir return values are as follows:
	//
	// 0 or more : The number of file entries that were obtained.
	// -2 : The memory card is unformatted
	// -4 : A non-existant path was specified in the "name" parameter
	// -10 or less : The memory card could not be detected.

	mcGetDir(0, 0, "/*", 0, ARRAY_ENTRIES - 10, mcDir);
	mcSync(0, NULL, &ret);
	printf("mcGetDir returned %d\n\nListing of root directory on memory card:\n\n", ret);

	for(i=0; i < ret; i++)
	{
		if(mcDir[i].attrFile & MC_ATTR_SUBDIR)
			printf("[DIR] %s\n", mcDir[i].name);
		else
			printf("%s - %d bytes\n", mcDir[i].name, mcDir[i].fileSizeByte);
	}

	// Check if existing save is present
	fd = fioOpen("mc0:PS2DEV/icon.sys", O_RDONLY);
	if(fd <= 0) {

		printf("\nNo previous save exists, creating...\n");

		if((ret = CreateSave()) < 0) {

			printf("Failed to create save! Errorno: %d\n",ret);
			SleepThread();
		}

	} else {

		printf("\nPrevious save exists, listing directory\n\n");

		ret = mcGetDir(0, 0, "/PS2DEV/*", 0, ARRAY_ENTRIES, mcDir);
		printf("mcGetDir returned %d\n\n", ret);

		for(i=0; i < ret; i++)
		{
			if(mcDir[i].attrFile & MC_ATTR_SUBDIR)
				printf("[DIR] %s\n", mcDir[i].name);
			else
				printf("%s - %d bytes\n", mcDir[i].name, mcDir[i].fileSizeByte);
		}
	}

	// Return to the browser, so you can see the PS2Dev icon :)
	SifExitRpc();
	return 0;
}
Esempio n. 4
0
static void frontend_ps2_init(void *data)
{
   char cwd[FILENAME_MAX];
   int bootDeviceID;

   SifInitRpc(0);
#if !defined(DEBUG)
   /* Comment this line if you don't wanna debug the output */
   while(!SifIopReset(NULL, 0)){};
#endif

   while(!SifIopSync()){};
   SifInitRpc(0);
   sbv_patch_enable_lmb();

   /* I/O Files */
   SifExecModuleBuffer(&iomanX_irx, size_iomanX_irx, 0, NULL, NULL);
   SifExecModuleBuffer(&fileXio_irx, size_fileXio_irx, 0, NULL, NULL);
   SifExecModuleBuffer(&freesio2_irx, size_freesio2_irx, 0, NULL, NULL);

   /* Memory Card */
   SifExecModuleBuffer(&mcman_irx, size_mcman_irx, 0, NULL, NULL);
   SifExecModuleBuffer(&mcserv_irx, size_mcserv_irx, 0, NULL, NULL);

   /* Controllers */
   SifExecModuleBuffer(&freemtap_irx, size_freemtap_irx, 0, NULL, NULL);
   SifExecModuleBuffer(&freepad_irx, size_freepad_irx, 0, NULL, NULL);

   /* USB */
   SifExecModuleBuffer(&usbd_irx, size_usbd_irx, 0, NULL, NULL);
   SifExecModuleBuffer(&usbhdfsd_irx, size_usbhdfsd_irx, 0, NULL, NULL);

   /* Audio */
   SifExecModuleBuffer(&freesd_irx, size_freesd_irx, 0, NULL, NULL);
   SifExecModuleBuffer(&audsrv_irx, size_audsrv_irx, 0, NULL, NULL);

   /* CDVD */
   SifExecModuleBuffer(&cdvd_irx, size_cdvd_irx, 0, NULL, NULL);

   if (mcInit(MC_TYPE_XMC)) {
      RARCH_ERR("mcInit library not initalizated\n");
   }

   /* Initializes audsrv library */
   if (audsrv_init()) {
      RARCH_ERR("audsrv library not initalizated\n");
   }

   /* Initializes pad libraries
      Must be init with 0 as parameter*/
   if (mtapInit() != 1) {
      RARCH_ERR("mtapInit library not initalizated\n");
   }
   if (padInit(0) != 1) {
      RARCH_ERR("padInit library not initalizated\n");
   }
   if (mtapPortOpen(0) != 1) {
      RARCH_ERR("mtapPortOpen library not initalizated\n");
   }

   /* Initializes CDVD library */
   /* SCECdINoD init without check for a disc. Reduces risk of a lockup if the drive is in a erroneous state. */
   sceCdInit(SCECdINoD);
   if (CDVD_Init() != 1) {
      RARCH_ERR("CDVD_Init library not initalizated\n");
   }

   _init_ps2_io();

   /* Prepare device */
   getcwd(cwd, sizeof(cwd));
   bootDeviceID=getBootDeviceID(cwd);
   waitUntilDeviceIsReady(bootDeviceID);

#if defined(HAVE_FILE_LOGGER)
   retro_main_log_file_init("retroarch.log");
   verbosity_enable();
#endif
}
Esempio n. 5
0
void InitPS2()
{
    int i, sometime;
    static char hddarg[] = "-o" "\0" "4" "\0" "-n" "\0" "20";
    static char pfsarg[] = "-m" "\0" "4" "\0" "-o" "\0" "10" "\0" "-n" "\0" "40";

    SifInitRpc(0);
    // Reset IOP borrowed from uLaunchelf
    while (!SifIopReset(NULL, 0)){};
    while (!SifIopSync()){};
    SifInitRpc(0);

    sbv_patch_enable_lmb();

    SifExecModuleBuffer(&iomanX_irx, size_iomanX_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&fileXio_irx, size_fileXio_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&freesio2_irx, size_freesio2_irx, 0, NULL, NULL);

 /* SifLoadModule("rom0:XSIO2MAN", 0, NULL);
    SifLoadModule("rom0:XMCMAN", 0, NULL);
    SifLoadModule("rom0:XMCSERV", 0, NULL);
    SifLoadModule("rom0:XMTAPMAN", 0, NULL);
    SifLoadModule("rom0:XPADMAN", 0, NULL); */

    SifExecModuleBuffer(&mcman_irx, size_mcman_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&mcserv_irx, size_mcserv_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&freemtap_irx, size_freemtap_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&freepad_irx, size_freepad_irx, 0, NULL, NULL);

#ifdef SOUND_ON
    SifExecModuleBuffer(&freesd_irx, size_freesd_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&audsrv_irx, size_audsrv_irx, 0, NULL, NULL);
#endif
    SifExecModuleBuffer(&SMSUTILS_irx, size_SMSUTILS_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&usbd_irx, size_usbd_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&usbhdfsd_irx, size_usbhdfsd_irx, 0, NULL, NULL);
    for (i = 0; i < 3; i++) { // Taken from ulaunchelf
        sometime = 0x01000000;
        while (sometime--) asm("nop\nnop\nnop\nnop");
    }

    SifExecModuleBuffer(&poweroff_irx, size_poweroff_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&ps2dev9_irx, size_ps2dev9_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&ps2atad_irx, size_ps2atad_irx, 0, NULL, NULL);
    SifExecModuleBuffer(&ps2hdd_irx, size_ps2hdd_irx, sizeof(hddarg), hddarg, NULL);
    SifExecModuleBuffer(&ps2fs_irx, size_ps2fs_irx, sizeof(pfsarg), pfsarg, NULL);

    mcInit(MC_TYPE_XMC);

#ifdef CDSUPPORT
    SifExecModuleBuffer(&cdvd_irx, size_cdvd_irx, 0, NULL, NULL);
    cdInit(CDVD_INIT_INIT);
    CDVD_Init();
#endif

#ifdef SOUND_ON
    audsrv_init();
#endif

    mtapInit();
    padInit(0);
    mtapPortOpen(0);
}
Esempio n. 6
0
void mcMigrate (char const **paramFile, int *nrFiles, char const *inputDir, char const *outputDir)
{
    int     i, j, k, RepLoop, envChgStep, dispStep, loopID, simulTime,last, action;
    bool    advOutput, habIsSuitable, cellInDispDist, tempResilience, tail;
    char    fileName[128], simulName2[128];
    FILE   *fp = NULL, *fp2 = NULL;
    double  lddSeedProb;
    time_t  startTime;
    /*
    ** These variables are not (yet) used.
    **
    ** int vegResTime, seedBankResTime, *seedBank, tSinceDecol, tWhenCol;
    */

    /*
    ** Pixel counter variables. These variables allow us to record interesting
    ** values to be printed into the output file:
    **
    ** ==> Many of these aren't used yet. <==
    **
    **   - nrColonized:           The number of pixels in "Colonized" state at
    **                            any given time.
    **   - nrAbsent:              The number of pixels in "Absent" state at any
    **                            given time.
    **   - nrDecolonized:         The number of pixels in "Decolonized" state at
    **                            any given time.
    **   - nrTmpResilient:        The number of pixels that in "Temporary
    **                            Resilience" state at any given time.
    **   - nrVegResilient:        The number of pixels that are in "Vegetative
    **                            Resilience" state at any given time.
    **   - nrSeedBank:            The number of pixels that are in Seed Bank
    **                            Resilience state at any given time.
    **   - nrStepColonized:       The number of pixels which changed to
    **                            "Colonized" state during a given step.
    **   - nrStepDecolonized:     The number of pixels which changed to
    **                            "Decolonized" state during a given step.
    **   - nrStepTmpResilient:    The number of pixels that which changed to
    **                            "Temporary Resilience" state during a given
    **                            step.
    **   - nrStepVegResilient:    The number of pixels that are which changed to
    **                            "Vegetative Resilience" state during a given
    **                            step.
    **   - nrStepSeedBank:        The number of pixels that are which changed to
    **                            "Seed Bank Resilience" state during a given
    **                            step.
    **   - nrStepLostUnsuit:      The number of pixels that were lost due to
    **                            unsuitable habitat conditons during a given
    **                            dispersal step.
    **   - nrStepLostExtreme:     The number of pixels that were lost due to
    **                            "Extreme Event" during a given dispersal step.
    **   - nrStepLDDSuccess:      The number of LDD events that were successful
    **                            (can be any of a "normal" LDD or a River or
    **                            Road LDD).
    **   - nrStepVegResRecover:   The number of "Vegetative Resilience" recovery
    **                            events that occured within a given dispersal
    **                            step.
    **   - nrStepSeedBankRecover: The number of "Seed Bank Resilience" recovery
    **                            events that occured within a given dispersal
    **                            step.
    **   - nrTotColonized:        \
    **   - nrTotLostUnsuit:        |
    **   - nrTotLostExtreme:       |   Same as above but over the total
    **   - nrTotLostNatural:        >  simulation instead of one step.
    **   - nrTotLDDSuccess:        |
    **   - nrTotVegResRecover:     |
    **   - nrTotSeedBankRecover:  /
    **   - nrInitial:             The number of initial pixels that are occupied
    **                            by the species.
    **   - nrNoDispersal:         The number of pixels that would be colonized at
    **                            the end of the simulation under the
    **                            "no-dispersal" hypothesis.
    **   - nrUnivDispersal:       The number of pixels that would be colonized
    **                            at the end of the simulation under the
    **                            "unlimited-dispersal" hypothesis.
    */
    int nrColonized, nrAbsent, nrStepColonized, nrStepDecolonized, nrStepLDDSuccess,
        nrTotColonized, nrTotLDDSuccess, nrInitial, nrNoDispersal, nrUnivDispersal, nrTotDecolonized;

    /* As of yet unused count variables:
    ** int nrTotVegResRecover, nrTotSeedBankRecover, nrStepVegResilient,
    **     nrStepSeedBank, nrVegResilient, nrStepSeedBankRecover,
    **     nrStepVegResRecover, nrSeedBank, nrDecolonized; */


    /* Matrices:
    **   - currentState:   Values in [-32768;32767]. NoData values are represented by -9999
    **   - habSuitability: Values in [0;1000].
    **   - barriers:       Values in [0;255].
    **   - pixelAge:       Values in [0;255].
    **   - noDispersal:    Values in [0;255].
    */
    int **currentState, **habSuitability, **barriers, **pixelAge, **noDispersal;


    /* Initialize the variables. */
    advOutput = false;
    currentState = NULL;
    habSuitability = NULL;
    barriers = NULL;
    pixelAge = NULL;
    noDispersal = NULL;
    propaguleProd = NULL;
    dispKernel = NULL;
    if (mcInit(*paramFile) == -1) /* Reads the "_param.txt" file */
    {
        *nrFiles = -1;
        goto End_of_Routine;
    }

    /* We'll use 'srand' and 'rand' here, as 'srandom' and 'random' do not work on Windows :-( */
    srand (time (NULL)+procID);

    /* Allocate the necessary memory. */
    currentState = (int **)malloc (nrRows * sizeof (int *));
    habSuitability = (int **)malloc (nrRows * sizeof (int *));
    barriers = (int **)malloc (nrRows * sizeof (int *));
    pixelAge = (int **)malloc (nrRows * sizeof (int *));
    noDispersal = (int **)malloc (nrRows * sizeof (int *));
    for (i = 0; i < nrRows; i++)
    {
        currentState[i] = (int *)malloc (nrCols * sizeof (int));
        habSuitability[i] = (int *)malloc (nrCols * sizeof (int));
        barriers[i] = (int *)malloc (nrCols * sizeof (int));
        pixelAge[i] = (int *)malloc (nrCols * sizeof (int));
        noDispersal[i] = (int *)malloc (nrCols * sizeof (int));
    }



    clock_t begin, end, total_begin, total_end;
    double time_spent;
    double total_time_spent;

    total_begin = clock();


    /* Replicate the simulation replicateNb times. If replicateNb > 1 then the
    ** simulation's output names are "simulName1", "simulName2", etc... */
    for (RepLoop = 1; RepLoop <= replicateNb; RepLoop++)
    {

        /* Remember the current time */
        startTime = time(NULL);

        /* If replicateNb > 1 then we need to change the simulation name */
        if (replicateNb == 1)
        {
            strcpy(simulName2, simulName);
        }
        else if (replicateNb > 1)
        {
            sprintf(simulName2, "%s%d", simulName, RepLoop);           /* sprinf(): puts a string into variable simulName2 */
        }


        /* Load and prepare the data. */

        /* Species initial distribution */
        sprintf(fileName, "%s%s.tif", inputDir, iniDist);                        /* sprinf(): puts a string into variable fileName */
        printf("%s", fileName);
        if (readMat(fileName, currentState) == -1)
        {
            *nrFiles = -1;
            goto End_of_Routine;
        }

        //remove initial occurences
        /*removeInitial(currentState);*/

        /* Barrier options */
        for (i = 0; i < nrRows; i++)
        {
            for (j = 0; j < nrCols; j++)
            {
                barriers[i][j] = 0;
            }
        }
        if (useBarrier)
        {
            sprintf(fileName, "%s.tif", barrier);
            if (readMat(fileName, barriers) == -1)
            {
                *nrFiles = -1;                                           /* if readMat() return -1, an error occured  */
                goto End_of_Routine;
            }
        }
        /* Filter the barrier matrix in two ways:
        **  -> reclass any value < 0 as 0 (this is to remove NoData values of -9999).
        **  -> set the cells with NoData in 'currentState' to NoData in 'barriers'
        **     so that the NoData in 'currentState' and 'barriers' are identical */
        mcFilterMatrix(barriers, currentState, true, false, true);

        /* Filter the values of current state matrix by the barriers matrix
        ** (when barriers = 1 we set currentState = 0) */
        if (useBarrier) mcFilterMatrix(currentState, barriers, false, true, false);



        /* Time to reach dispersal maturity.
        **
        ** Before a pixel (= a population) can disperse, it needs to reach a certain
        ** user-defined age. The "age" is a matrix that keeps track of the age
        ** of all pixels:
        **   0 = pixel is not colonized.
        **   1 = pixel is colonized since 1 "dispersal event".
        **   2 = pixel is colonized since 2 "dispersal event".
        **   3 = etc...
        ** Fill the "age" to reflect the initial distribution of the species:
        ** where the species is present, pixels get a value of 'FullMaturity', where
        ** the species is absent, pixels get a value of 0. */
        for (i = 0; i < nrRows; i++)
        {
            for (j = 0; j < nrCols; j++)
            {
                if (currentState[i][j] == 1)
                {
                    pixelAge[i][j] = fullMatAge;
                }
                else
                {
                    pixelAge[i][j] = 0;
                }
            }
        }


        /* The "no dispersal" matrix.
        ** This Matrix will keep track of the species distribution under the
        ** "no dispersal" scenario. */
        for (i = 0; i < nrRows; i++)
        {
            for (j = 0; j < nrCols; j++)
            {
                noDispersal[i][j] = currentState[i][j];
            }
        }


        /* Initialize counter variables.
        ** Reset pixel counters to zero before we start the dispersal simulation. */
        nrInitial = 0;
        nrColonized = 0;
        nrAbsent = 0;
        nrNoDispersal = 0;
        nrUnivDispersal = 0;
        nrTotColonized = 0;
        nrTotDecolonized = 0;
        nrTotLDDSuccess = 0;
        tempResilience = true;
        nrStepColonized = 0;
        nrStepDecolonized = 0;
        nrStepLDDSuccess = 0;
        /* Currently unused counters:
        ** nrVegResilient = 0;
        ** nrSeedBank = 0;
        ** nrTotVegResRecover = 0;
        ** nrTotSeedBankRecover = 0; */


        /* Count the number of initially colonized pixels (i.e. initial species distribution)
        ** as well as the number of empty (absence) cells. */
        for (i = 0; i < nrRows; i++)
        {
            for (j = 0; j < nrCols; j++)
            {
                if (currentState[i][j] == 1) nrInitial++;
                if (currentState[i][j] == 0) nrAbsent++;
            }
        }
        nrColonized = nrInitial;
        nrNoDispersal = nrInitial;
        nrUnivDispersal = nrInitial;


        /* Write the initial state to the data file. */
        sprintf(fileName, "%s/%s_stats%d.txt", outputDir, simulName2,procID);
        if ((fp = fopen (fileName, "w")) != NULL)
        {
            fprintf (fp, "envChgStep\tdispStep\tstepID\tunivDispersal\tNoDispersal\toccupied\tabsent\tstepColonized\tstepDecolonized\tstepLDDsuccess\n");
            fprintf (fp, "0\t0\t1\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", nrUnivDispersal, nrNoDispersal,
                     nrColonized, nrAbsent, nrStepColonized, nrStepDecolonized, nrStepLDDSuccess);
        }
        else
        {
            *nrFiles = -1;
            printf ("Could not open statistics file for writing.\n");
            goto End_of_Routine;
        }



        /* **************************************************************** */
        /* Simulate plant dispersal and migration (the core of the method). */
        /* **************************************************************** */
        printf("Running MigClim simulation %s.\n", simulName2);

        /* Start of environmental change step loop (if simulation is run without change in environment this loop runs only once). */
        for (envChgStep = 1; envChgStep <= envChgSteps; envChgStep++)
        {

            /* Print the current environmental change iteration. */
            printf ("  %d...\n", envChgStep);

            /* Load the habitat suitability layer for the current envChgStep. */
            sprintf (fileName, "%s%s%d.tif", inputDir, hsMap, envChgStep);
            if (readMat (fileName, habSuitability) == -1)
            {
                *nrFiles = -1;
                goto End_of_Routine;
            }

            /* if the user chose a rcThreshold > 0, reclass the habitat suitability into 0 or 1000
            ** if rcThreshold == 0 then suitability values are left unchanged. */
            if (rcThreshold > 0)
            {
                for (i = 0; i < nrRows; i++)
                {
                    for (j = 0; j < nrCols; j++)
                    {
                        if (habSuitability[i][j] < rcThreshold)
                        {
                            habSuitability[i][j] = 0;
                        }
                        else
                        {
                            habSuitability[i][j] = 1000;
                        }
                    }
                }
            }

            /* Filter the habitat suitability matrix in three ways:
            **  -> replace any value < 0 by 0 (this removes NoData).
            **  -> set habitat suitability to 0 where barrier = 1.
            **  -> set habitat suitability values to NoData where barrier = NoData.
            ** and also  */
            mcFilterMatrix(habSuitability, barriers, true, true, true);


            /* Set the values that will keep track of pixels colonized during the next
            ** climate change loop.
            ** "loopID" is the value that will be given to the pixel colonized
            ** during the current loop. The pixels being decolonized during the
            ** current loop will be given a value of "-loopID". The limits in
            ** terms of number of dispersal events and environmental change
            ** events is the following:
            **  - Without environmental change, the maximum number of dispStep
            **    is 29'500.
            **  - With environmental change, the maximum number of dispStep is
            **    98, the number of environmental change loops is limited to 250.
            ** The coding for the loopID is as follows: envChgStep * 100 + dispStep. */
            if (envChgStep == 0)
            {
                loopID = 1;
            }
            else
            {
                loopID = envChgStep * 100;
            }


            /* "Unlimited" and "no dispersal" scenario pixel count. Here we compute the number of pixels
            ** that would be colonized if dispersal was unlimited or null. This is simply the sum of all
            ** potentially suitable habitats */
            nrUnivDispersal = mcUnivDispCnt(habSuitability);
            updateNoDispMat(habSuitability, noDispersal, &nrNoDispersal);

            /* Reset number of decolonized cells within current dispersal step pixel counter */
            nrStepDecolonized = 0;

            /* Update for temporarily resilient pixels. */
            for (i = 0; i < nrRows; i++)
            {
                for (j = 0; j < nrCols; j++)
                {

                    /* Udate non-suitable pixels. If a pixel turned unsuitable, we update its status to "Temporarily Resilient". */
                    if ((habSuitability[i][j] == 0) && (currentState[i][j] > 0))
                    {

                        /* If the user selected TemporaryResilience==T, then the pixel is set to "Temporary Resilient" status. */
                        if (tempResilience == true)
                        {
                            currentState[i][j] = 29900;
                        }
                        else
                        {
                            /* If not temporary resilience was specified, then the pixel is set to "decolonized" status. */
                            currentState[i][j] = -1 - loopID;
                            pixelAge[i][j] = 0;
                            /* NOTE: Later we can add "Vegetative" and "SeedBank" resilience options at this location. */
                        }

                        /* The number of decolonized cells within current step is increased by one */
                        nrStepDecolonized++;
                    }
                }
            }


            /* *************************************** */
            /* Dispersal event step loop starts here.  */
            /* *************************************** */
            for (dispStep = 1; dispStep <= dispSteps; dispStep++)
            {
                begin=clock();

                /* Set the value of "loopID" for the current iteration of the dispersal loop. */
                loopID++;

                /* Reset pixel counters that count pixels within the current loop. */
                nrStepColonized = 0;
                nrStepLDDSuccess = 0;
                if (dispStep > 1) nrStepDecolonized = 0;

                /* Currently unused variables:
                ** nrStepVegResilient = 0;
                ** nrStepSeedBank = 0;
                ** nrStepVegResRecover = 0;
                ** nrStepSeedBankRecover = 0; */

                removeInitial(currentState,dispStep);

                /* Source cell search: Can the sink pixel be colonized? There are four
                ** conditions to be met for a sink pixel to become colonized:
                **   1. Sink pixel is currently suitable and not already colonised.
                **   2. Sink pixel is within dispersal distance of an already colonised
                **      and mature pixel.
                **   3. Source pixel has reached dispersal maturity.
                **   4. There is no obstacle (barrier) between the pixel to be colonised
                **      (sink pixel) and the pixel that is already colonised (source
                **      pixel).
                **
                ** Loop through the cellular automaton. */
                for (i = 0; i < nrRows; i++)
                {
                    last = 0;
                    for (j = 0; j < nrCols; j++)
                    {

                        /* Reset variables. */
                        habIsSuitable = false;
                        cellInDispDist = false;

                        /* Remove mature cells for impact control */
                        if (pixelAge[i][j] >= iniMatAge) {
                          //determine the action for this cell
                          action = cellAction(i,j,dispStep);
                          if (action== IMPACT_CONTROL) {
                            //delete it?
                            double r = UNIF01;
                            if (r <= 0.7) {
                              currentState[i][j] = 0;
                              pixelAge[i][j] = 0;
                              if (aggregates[dispStep-1][i][j] > 0) {
                                aggregates[dispStep-1][i][j]--;
                              }
                              managementImpacts[dispStep-1][IMPACT_CONTROL][procID-1]++;
                            }
                          }
                        }

                        /* 1. Test whether the pixel is a suitable sink (i.e., its habitat
                        **    is suitable, it's unoccupied and is not on a barrier or filter
                        **    pixel). */
                        if ((habSuitability[i][j] > 0) && (currentState[i][j] <= 0) && checkSuitability(i,j,false)) habIsSuitable = true;

                        //set state from previous state
                        if (currentState[i][j] >= 1) {
                            aggregates[dispStep-1][i][j]++;
                        }

                        /* 2. Test whether there is a source cell within the dispersal
                        **    distance. To be more time efficient, this code runs only if
                        **    the answer to the first question is positive. Additionally,
                        **    if there is a source cell within dispersion distance and if
                        **    a barrier was asked for, then we also check that there is no
                        **    barrier between this source cell and the sink cell (this
                        **    verification is carried out in the "SearchSourceCell"
                        **    function). */
                        if (habIsSuitable)
                        {
                            /* Now we search if there is a suitable source cell to colonize the sink cell. */
                            if (mcSrcCell (i, j, currentState, pixelAge, loopID, habSuitability[i][j], barriers, &last)) {
                                cellInDispDist = true;
                                //last=0;
                            } else {
                                //last++;
                            }
                        }

                        /* Update pixel status. */
                        if (habIsSuitable && cellInDispDist)
                        {

                            /* Only if the 2 conditions are fullfilled the cell's status is set to colonised. */
                            currentState[i][j] = loopID;
                            nrStepColonized++;

                            //printf("Step: %d, i: %d, j: %d\n",dispStep-1, i, j);
                            aggregates[dispStep-1][i][j]++;

                            /* If the pixel was in seed bank resilience state, then we
                            ** update the corresponding counter. Currently not used.
                            ** if (pixelAge[i][j] == 255) nrStepSeedBank--; */

                            /* Update "age" value. We do this only now because we needed the old "age" value just before
                            ** to determine whether a pixel was in "Decolonized" or "SeedBank resilience" status. */
                            pixelAge[i][j] = 0;
                        }

                    }

                }

                /* If the LDD frequence is larger than zero, perform it. */
                if (lddFreq > 0.0)
                {

                    /* Loop through the entire cellular automaton. */
                    for (i = 0; i < nrRows; i++)
                    {
                        for (j = 0; j < nrCols; j++)
                        {

                            /* Check if the pixel is a source cell (i.e. is it colonised since at least 1 dispersal Loop)
                            ** and check if the pixel has reached dispersal maturity. */
                            if ((currentState[i][j]) > 0 && (currentState[i][j] != loopID))
                            {
                                if (pixelAge[i][j] >= iniMatAge)
                                {

                                    /* Set the probability of generating an LDD event. This
                                    ** probability is weighted by the age of the cell. */
                                    if (pixelAge[i][j] >= fullMatAge)
                                    {
                                        lddSeedProb = lddFreq;
                                    }
                                    else
                                    {
                                        lddSeedProb = lddFreq * propaguleProd[pixelAge[i][j] - iniMatAge];
                                    }

                                    /* Now we can try to generate a LDD event with the calculated probability. */
                                    if (UNIF01 < lddSeedProb || lddSeedProb == 1.0)
                                    {

                                        /* Randomly select a pixel within the distance "lddMinDist - lddMaxDist". */
                                        mcRandomPixel (&rndPixel);
                                        rndPixel.row = rndPixel.row + i;
                                        rndPixel.col = rndPixel.col + j;

                                        /* Now we check if this random cell is a suitable sink cell.*/
                                        if (mcSinkCellCheck (rndPixel, currentState, habSuitability) && srcPixel(i,j,rndPixel.row,rndPixel.col,dispStep,true))
                                        {

                                            /* if condition is true, the pixel gets colonized.*/
                                            currentState[rndPixel.row][rndPixel.col] = loopID;

                                            //include ldd state
                                            aggregates[dispStep-1][i][j]++;
                                            nrStepColonized++;
                                            nrStepLDDSuccess++;

                                            /* If the pixel was in seed bank resilience state, then we
                                            ** update the corresponding counter. Currently not used.
                                            ** if (pixelAge[rndPixel.row][rndPixel.col] == 255) nrStepSeedBank--;  */

                                            /* Reset pixel age. */
                                            pixelAge[rndPixel.row][rndPixel.col] = 0;
                                        }
                                    }

                                }
                            }
                        }
                    }
                }

                /* Update pixel age: At the end of a dispersal loop we want to
                ** increase the "age" of each colonized pixel.
                **
                ** Reminder: pixel "age" structure is as follows:
                **   0 = Pixel is either "Absent", "Decolonized" or has just been
                **       "Colonized" during this dispersal step.
                **   1 to 250 = Pixel is in "Colonized" or "Temporarily Resilient"
                **       status. The value indicates the number of "dispersal events
                **       (usually years) since when the pixel was colonized.
                **   255 = Pixel is in "SeedBank Resilience" state. */
                for (i = 0; i < nrRows; i++)
                {
                    for (j = 0; j < nrCols; j++)
                    {

                        /* If the pixel is in "Colonized" or "Temporarily Resilient" state, update it's age value. */
                        if (currentState[i][j] > 0) pixelAge[i][j] += 1;

                        /* If a pixel is in "Temporarily Resilient" state, we also increase its "currentState" value by 1
                        ** so that the pixels gains 1 year of "Temporarily Resilience" age. */
                        if (currentState[i][j] >= 29900) currentState[i][j] += 1;

                    }
                }

                /* Update pixel counters. */
                nrColonized = nrColonized + nrStepColonized - nrStepDecolonized;
                nrAbsent = nrAbsent - nrStepColonized + nrStepDecolonized;
                nrTotColonized += nrStepColonized;
                nrTotDecolonized += nrStepDecolonized;
                nrTotLDDSuccess += nrStepLDDSuccess;
                /* Currently unused variables:
                ** nrTotVegResRecover += nrStepVegResRecover;
                ** nrTotSeedBankRecover += nrStepSeedBankRecover; */

                /* Write current iteration data to the statistics file. */
                fprintf(fp, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", envChgStep, dispStep, loopID, nrUnivDispersal,
                        nrNoDispersal, nrColonized, nrAbsent, nrStepColonized, nrStepDecolonized, nrStepLDDSuccess);

                /* If the user has requested full output, also write the current state matrix to file. */
                /*if (fullOutput)
                {
                    sprintf (fileName, "%s/%s_step_%d.asc", outputDir, simulName2, loopID);
                    if (writeMat (fileName, currentState) == -1)
                    {
                        *nrFiles = -1;
                        goto End_of_Routine;
                    }
                }*/

                end = clock();
                time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
                //fprintf(f,"%lf\n",time_spent);
                //printf("Step %d completed by proc(%i) in %lf \n",dispStep,procID,time_spent);

                //increment step tracker
                if (incrementStepComplete(dispStep-1)) {
                  //print summary
                  int avgColonised = sum(dispStep-1);
                  int d_range=0, p_range=0, r_range=0, c_range=0, ic_range=0, ap_range=0;
                  int proc;

                  for (proc = 0; proc < NUMPROC; proc++) {
                    d_range += managementImpacts[dispStep-1][DELIMITATION][proc];
                    p_range += managementImpacts[dispStep-1][PREVENTION][proc];
                    r_range += managementImpacts[dispStep-1][REMOVAL][proc];
                    c_range += managementImpacts[dispStep-1][CONTAINMENT][proc];
                    ic_range += managementImpacts[dispStep-1][IMPACT_CONTROL][proc];
                    ap_range += managementImpacts[dispStep-1][ASSET_PROTECTION][proc];
                    //printf("IC%i: %i\n",proc,managementImpacts[dispStep-1][ASSET_PROTECTION][proc]);
                  }

                  d_range = d_range / NUMPROC;
                  p_range = p_range / NUMPROC;
                  r_range = r_range / NUMPROC;
                  c_range = c_range / NUMPROC;
                  ic_range = ic_range / NUMPROC;
                  ap_range = ap_range / NUMPROC;

                  //printf("IC: %i : %i\n",managementImpacts[dispStep-1][IMPACT_CONTROL][procID-1], procID-1);
                  //printf("IC Averaged: %i\n",ic_range);

                  char impactStr[128];
                  sprintf(impactStr,"\"d_range\":%i,\"p_range\":%i,\"r_range\":%i,\"c_range\":%i,\"ic_range\":%i,\"ap_range\":%i",d_range,p_range,r_range,c_range,ic_range,ap_range);
                  //printf("%s",impactStr);
                  printf("StepComplete %i : {\"time\":%lf,\"occupied\":%i,\"new\":%i,%s}\n",dispStep,time_spent,avgColonised,nrStepColonized,impactStr);
                }


            } /* END OF: dispStep */


            /* Update temporarily resilient pixels.
            ** Temporarily resilient pixels can be distinguished by:
            **   -> CurrentState_Matrix = 29'900 to 29'999. Increases by 1 at each year.
            **   -> Age_Matrix has a positive value. */
            for (i = 0; i < nrRows; i++)
            {
                for (j = 0; j < nrCols; j++)
                {
                    if (currentState[i][j] >= 29900)
                    {
                        currentState[i][j] = dispSteps - loopID - 1;
                        pixelAge[i][j] = 0;
                    }
                }
            }

        } /* END OF: envChgStep loop */
        printf("All dispersal steps completed. Final output in progress...\n");


        /* Update currentState matrix for pixels that are suitable but
        ** could not be colonized due to dispersal limitations.
        ** These pixels are assigned a value of 30'000 */
        for (i = 0; i < nrRows; i++)
        {
            for (j = 0; j < nrCols; j++)
            {
                if ((habSuitability[i][j] > 0) && (currentState[i][j] <= 0)) currentState[i][j] = 30000;
            }
        }

        /* Write the final state matrix to file. */
       /* sprintf(fileName, "%s/%s_raster.asc", simulName, simulName2);
        if (writeMat (fileName, currentState) == -1)
        {
            *nrFiles = -1;
            goto End_of_Routine;
        }*/

        /* Write summary output to file. */
        simulTime = time (NULL) - startTime;
        total_end = clock();
        time_spent = (double)(total_end - total_begin) / CLOCKS_PER_SEC;
        printf("Process Completed after %lf \n",time_spent);

        sprintf(fileName, "%s/%s_summary.txt", outputDir, simulName2);
        if ((fp2 = fopen (fileName, "w")) != NULL)
        {
            fprintf(fp2, "simulName\tiniCount\tnoDispCount\tunivDispCount\toccupiedCount\tabsentCount\ttotColonized\ttotDecolonized\ttotLDDsuccess\trunTime\n");
            fprintf(fp2, "%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", simulName2, nrInitial, nrNoDispersal, nrUnivDispersal,
                    nrColonized, nrAbsent, nrTotColonized, nrTotDecolonized, nrTotLDDSuccess, simulTime);
            fclose (fp2);
        }
        else
        {
            *nrFiles = -1;
            printf ("Could not write summary output to file.\n");
            goto End_of_Routine;
        }

        /* Close the data file. */
        if (fp != NULL) fclose (fp);
        fp = NULL;

    } /* end of "RepLoop" */


    /* Set the number of output files created. */
    *nrFiles = envChgSteps;



End_of_Routine:

    /* Close the data file. */
    if (fp != NULL) fclose (fp);

    //fclose(f);

    /* Free the allocated memory. */
    if (currentState != NULL)
    {
        for (i = 0; i < nrRows; i++) free(currentState[i]);
        free(currentState);
    }
    if (habSuitability != NULL)
    {
        for (i = 0; i < nrRows; i++) free(habSuitability[i]);
        free(habSuitability);
    }
    if (barriers != NULL)
    {
        for (i = 0; i < nrRows; i++) free(barriers[i]);
        free(barriers);
    }
    if (pixelAge != NULL)
    {
        for (i = 0; i < nrRows; i++) free(pixelAge[i]);
        free(pixelAge);
    }
    if (noDispersal != NULL)
    {
        for (i = 0; i < nrRows; i++) free(noDispersal[i]);
        free(noDispersal);
    }
    if (dispKernel != NULL) free(dispKernel);
    if (propaguleProd != NULL) free(propaguleProd);


    /* If an error occured, display failure message to the user... */
    if (*nrFiles == -1) printf("MigClim simulation aborted...\n");

}