test scalar global constants

test scalar global constants

a test case was updated, to test not only constant arrays,
but also constant scalar.

Signed-off-by: Homer Hsing <f17cb7083eb6a94c3fb9d8f09ceefa518f721ab2@intel.com>
Reviewed-by: Zhigang Gong <e04a7b9b70b1e4c6318cf117dcd1a9056e14b97a@linux.intel.com>

constant int m[3] = {71,72,73};
constant int n = 1;

__kernel void
compiler_global_constant(__global int *dst, int e, int r)
{
  int id = (int)get_global_id(0);
  dst[id] = m[id%3] * n + e + r;
}

constant int m[3] = {71,72,73};

__kernel void
compiler_global_constant(__global int *dst, int e, int r)
{
  int id = (int)get_global_id(0);
  dst[id] = m[id%3] + e + r;
}


Made it more likely (but no guarantees) for amax/amin to return the first index

// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file contains the Xamax kernel. It implements index of (absolute) min/max computation using
// reduction kernels. Reduction is split in two parts. In the first (main) kernel the X vector is
// loaded, followed by a per-thread and a per-workgroup reduction. The second (epilogue) kernel
// is executed with a single workgroup only, computing the final result.
//
// =================================================================================================

// Enables loading of this file using the C++ pre-processor's #include (C++11 standard raw string
// literal). Comment-out this line for syntax-highlighting when developing.
R"(

// Parameters set by the tuner or by the database. Here they are given a basic default value in case
// this kernel file is used outside of the CLBlast library.
#ifndef WGS1
  #define WGS1 64     // The local work-group size of the main kernel
#endif
#ifndef WGS2
  #define WGS2 64     // The local work-group size of the epilogue kernel
#endif

// =================================================================================================

// The main reduction kernel, performing the loading and the majority of the operation
__kernel __attribute__((reqd_work_group_size(WGS1, 1, 1)))
void Xamax(const int n,
           const __global real* restrict xgm, const int x_offset, const int x_inc,
           __global singlereal* maxgm, __global unsigned int* imaxgm) {
  __local singlereal maxlm[WGS1];
  __local unsigned int imaxlm[WGS1];
  const int lid = get_local_id(0);
  const int wgid = get_group_id(0);
  const int num_groups = get_num_groups(0);

  // Performs loading and the first steps of the reduction
  #if defined(ROUTINE_MAX) || defined(ROUTINE_MIN) || defined(ROUTINE_AMIN)
    singlereal max = SMALLEST;
  #else
    singlereal max = ZERO;
  #endif
  unsigned int imax = 0;
  int id = wgid*WGS1 + lid;
  while (id < n) {
    const int x_index = id*x_inc + x_offset;
    #if PRECISION == 3232 || PRECISION == 6464
      singlereal x = xgm[x_index].x;
    #else
      singlereal x = xgm[x_index];
    #endif
    #if defined(ROUTINE_MAX) // non-absolute maximum version
      // nothing special here
    #elif defined(ROUTINE_MIN) // non-absolute minimum version
      x = -x;
    #elif defined(ROUTINE_AMIN) // absolute minimum version
      x = -fabs(x);
    #else
      x = fabs(x);
    #endif
    if (x > max) {
      max = x;
      imax = id*x_inc + x_offset;
    }
    id += WGS1*num_groups;
  }
  maxlm[lid] = max;
  imaxlm[lid] = imax;
  barrier(CLK_LOCAL_MEM_FENCE);

  // Performs reduction in local memory
  for (int s=WGS1/2; s>0; s=s>>1) {
    if (lid < s) {
      if (maxlm[lid + s] > maxlm[lid]) {
        maxlm[lid] = maxlm[lid + s];
        imaxlm[lid] = imaxlm[lid + s];
      }
    }
    barrier(CLK_LOCAL_MEM_FENCE);
  }

  // Stores the per-workgroup result
  if (lid == 0) {
    maxgm[wgid] = maxlm[0];
    imaxgm[wgid] = imaxlm[0];
  }
}

// =================================================================================================

// The epilogue reduction kernel, performing the final bit of the operation. This kernel has to
// be launched with a single workgroup only.
__kernel __attribute__((reqd_work_group_size(WGS2, 1, 1)))
void XamaxEpilogue(const __global singlereal* restrict maxgm,
                   const __global unsigned int* restrict imaxgm,
                   __global unsigned int* imax, const int imax_offset) {
  __local singlereal maxlm[WGS2];
  __local unsigned int imaxlm[WGS2];
  const int lid = get_local_id(0);

  // Performs the first step of the reduction while loading the data
  if (maxgm[lid + WGS2] > maxgm[lid]) {
    maxlm[lid] = maxgm[lid + WGS2];
    imaxlm[lid] = imaxgm[lid + WGS2];
  }
  else {
    maxlm[lid] = maxgm[lid];
    imaxlm[lid] = imaxgm[lid];
  }
  barrier(CLK_LOCAL_MEM_FENCE);

  // Performs reduction in local memory
  for (int s=WGS2/2; s>0; s=s>>1) {
    if (lid < s) {
      if (maxlm[lid + s] > maxlm[lid]) {
        maxlm[lid] = maxlm[lid + s];
        imaxlm[lid] = imaxlm[lid + s];
      }
    }
    barrier(CLK_LOCAL_MEM_FENCE);
  }

  // Stores the final result
  if (lid == 0) {
    imax[imax_offset] = imaxlm[0];
  }
}

// =================================================================================================

// End of the C++11 raw string literal
)"

// =================================================================================================

// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file contains the Xamax kernel. It implements index of (absolute) min/max computation using
// reduction kernels. Reduction is split in two parts. In the first (main) kernel the X vector is
// loaded, followed by a per-thread and a per-workgroup reduction. The second (epilogue) kernel
// is executed with a single workgroup only, computing the final result.
//
// =================================================================================================

// Enables loading of this file using the C++ pre-processor's #include (C++11 standard raw string
// literal). Comment-out this line for syntax-highlighting when developing.
R"(

// Parameters set by the tuner or by the database. Here they are given a basic default value in case
// this kernel file is used outside of the CLBlast library.
#ifndef WGS1
  #define WGS1 64     // The local work-group size of the main kernel
#endif
#ifndef WGS2
  #define WGS2 64     // The local work-group size of the epilogue kernel
#endif

// =================================================================================================

// The main reduction kernel, performing the loading and the majority of the operation
__kernel __attribute__((reqd_work_group_size(WGS1, 1, 1)))
void Xamax(const int n,
           const __global real* restrict xgm, const int x_offset, const int x_inc,
           __global singlereal* maxgm, __global unsigned int* imaxgm) {
  __local singlereal maxlm[WGS1];
  __local unsigned int imaxlm[WGS1];
  const int lid = get_local_id(0);
  const int wgid = get_group_id(0);
  const int num_groups = get_num_groups(0);

  // Performs loading and the first steps of the reduction
  #if defined(ROUTINE_MAX) || defined(ROUTINE_MIN) || defined(ROUTINE_AMIN)
    singlereal max = SMALLEST;
  #else
    singlereal max = ZERO;
  #endif
  unsigned int imax = 0;
  int id = wgid*WGS1 + lid;
  while (id < n) {
    const int x_index = id*x_inc + x_offset;
    #if PRECISION == 3232 || PRECISION == 6464
      singlereal x = xgm[x_index].x;
    #else
      singlereal x = xgm[x_index];
    #endif
    #if defined(ROUTINE_MAX) // non-absolute maximum version
      // nothing special here
    #elif defined(ROUTINE_MIN) // non-absolute minimum version
      x = -x;
    #elif defined(ROUTINE_AMIN) // absolute minimum version
      x = -fabs(x);
    #else
      x = fabs(x);
    #endif
    if (x >= max) {
      max = x;
      imax = id*x_inc + x_offset;
    }
    id += WGS1*num_groups;
  }
  maxlm[lid] = max;
  imaxlm[lid] = imax;
  barrier(CLK_LOCAL_MEM_FENCE);

  // Performs reduction in local memory
  for (int s=WGS1/2; s>0; s=s>>1) {
    if (lid < s) {
      if (maxlm[lid + s] >= maxlm[lid]) {
        maxlm[lid] = maxlm[lid + s];
        imaxlm[lid] = imaxlm[lid + s];
      }
    }
    barrier(CLK_LOCAL_MEM_FENCE);
  }

  // Stores the per-workgroup result
  if (lid == 0) {
    maxgm[wgid] = maxlm[0];
    imaxgm[wgid] = imaxlm[0];
  }
}

// =================================================================================================

// The epilogue reduction kernel, performing the final bit of the operation. This kernel has to
// be launched with a single workgroup only.
__kernel __attribute__((reqd_work_group_size(WGS2, 1, 1)))
void XamaxEpilogue(const __global singlereal* restrict maxgm,
                   const __global unsigned int* restrict imaxgm,
                   __global unsigned int* imax, const int imax_offset) {
  __local singlereal maxlm[WGS2];
  __local unsigned int imaxlm[WGS2];
  const int lid = get_local_id(0);

  // Performs the first step of the reduction while loading the data
  if (maxgm[lid + WGS2] >= maxgm[lid]) {
    maxlm[lid] = maxgm[lid + WGS2];
    imaxlm[lid] = imaxgm[lid + WGS2];
  }
  else {
    maxlm[lid] = maxgm[lid];
    imaxlm[lid] = imaxgm[lid];
  }
  barrier(CLK_LOCAL_MEM_FENCE);

  // Performs reduction in local memory
  for (int s=WGS2/2; s>0; s=s>>1) {
    if (lid < s) {
      if (maxlm[lid + s] >= maxlm[lid]) {
        maxlm[lid] = maxlm[lid + s];
        imaxlm[lid] = imaxlm[lid + s];
      }
    }
    barrier(CLK_LOCAL_MEM_FENCE);
  }

  // Stores the final result
  if (lid == 0) {
    imax[imax_offset] = imaxlm[0];
  }
}

// =================================================================================================

// End of the C++11 raw string literal
)"

// =================================================================================================


INTEGRATION: CWS changefileheader (1.3.330); FILE MERGED 2008/03/31 17:13:24 rt 1.3.330.1: #i87441# Change license header to LPGL v3.

/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dfa.cl,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

/* static char datefunc_Id[]="@(#) StarCalc Datefunc AddIn (c) 1998-2000 Sun Microsystems, Inc."; */

#include <string.h>
#include <stdlib.h>
#include <math.h>

#include <xlang.h>
#include <addin.h>
#include <dfa.hrc>

/**
 * the current language the Addin is using
 */
static USHORT _nLanguage=LANGUAGE_ENGLISH;

/**
 * StarCalc calls this function to set a new current Language for the Addin
 *
 * @param *nLanguage
 *
 */
void CALLTYPE SetLanguage( USHORT* nLanguage )
{
	_nLanguage = GetNeutralLanguage( *nLanguage );
}

/**
 * Null Date, initialized in GetFunctionCount
 *
 * StarCalc uses a BaseDate 12/30/1899
 * If not specified otherwise in the Settings for the Spreedsheet Document.
 *
 * There's no way to get the Spreadsheet settings from whithin a simple addin,
 * so this Addin can only be used by documents using the default BaseDate setting.
 *
 * The functions in this Addin use a BaseDate 01/01/0001
 * The nNullDate Variable is the StarCalc BaseDate converted to
 * this internal date representation.
 *
 * @see #GetFunctionCount
 *
 */

static ULONG nNullDate=0;

#define NULLDATE_Year  1899
#define NULLDATE_Month 12
#define NULLDATE_Day   30

/**
 * Array holding values for month length, used in DaysInMonth() function
 *
 * @see #DaysInMonth
 *
 */
static USHORT aDaysInMonth[12] = { 31, 28, 31, 30, 31, 30,
                                   31, 31, 30, 31, 30, 31 };

/**
 * Check if a year is a leap year in the Gregorian calendar
 *
 * @param nYear the year which should be checked
 * @return true if the year is a leap year, false otherwise.
 *
 * @see #DaysInMonth, #IsLeapYear,
 * @see #ScDate_DaysInMonth, #ScDate_IsLeapYear, #ScDate_WeeksInYear
 *
 */
static BOOL IsLeapYear( USHORT nYear )
{
    return (BOOL)((((nYear % 4) == 0) && ((nYear % 100) != 0)) || ((nYear % 400) == 0));
}

/**
 * Get the number of days in a specified month
 *
 * @param nMonth the number of the Month
 * @param nYear the year
 * @return number of days
 *
 */
static USHORT DaysInMonth( USHORT nMonth, USHORT nYear )
{
    if ( nMonth != 2 )
        return aDaysInMonth[nMonth-1];
    else
    {
        if ( IsLeapYear(nYear) )
            return aDaysInMonth[nMonth-1] + 1;
        else
            return aDaysInMonth[nMonth-1];
    }
}

/**
 * Convert a date to a count of days starting from 01/01/0001
 *
 * The internal representation of a Date used in this Addin
 * is the number of days between 01/01/0001 and the date
 * this function converts a Day , Month, Year representation
 * to this internal Date value.
 *
 * @param nDay the day of the Month
 * @param nMonth the number of the Month
 * @param nYear the Year
 * @return count of days from 01/01/0001 to the date specified
 *
 */
static long DateToDays( USHORT nDay, USHORT nMonth, USHORT nYear )
{
    long nDays;
    USHORT i;

    nDays = ((ULONG)nYear-1) * 365;
    nDays += ((nYear-1) / 4) - ((nYear-1) / 100) + ((nYear-1) / 400);

    for( i = 1; i < nMonth; i++ )
        nDays += DaysInMonth(i,nYear);
    nDays += nDay;

    return nDays;
}

/**
 * Convert a count of days starting from 01/01/0001 to a date
 *
 * The internal representation of a Date used in this Addin
 * is the number of days between 01/01/0001 and the date
 * this function converts this internal Date value
 * to a Day , Month, Year representation of a Date.
 *
 * @param nDay count of days from 01/01/0001
 * @param *pDay pointer to a variable for the day of the month
 * @param *pMonth pointer to a variable for the month
 * @param *pYear pointer to a variable for the year
 *
 */
static void DaysToDate( long nDays,
                        USHORT *pDay, USHORT *pMonth, USHORT *pYear )
{
    long    nTempDays;
    long    i = 0;
    BOOL    bCalc;

    do
    {
        nTempDays = (long)nDays;
        *pYear = (USHORT)((nTempDays / 365) - i);
        nTempDays -= ((ULONG) *pYear -1) * 365;
        nTempDays -= (( *pYear -1) / 4) - (( *pYear -1) / 100) + ((*pYear -1) / 400);
        bCalc = FALSE;
        if ( nTempDays < 1 )
        {
            i++;
            bCalc = TRUE;
        }
        else
        {
            if ( nTempDays > 365 )
            {
                if ( (nTempDays != 366) || !IsLeapYear( *pYear ) )
                {
                    i--;
                    bCalc = TRUE;
                }
            }
        }
    }
    while ( bCalc );

    *pMonth = 1;
    while ( (ULONG)nTempDays > DaysInMonth( *pMonth, *pYear ) )
    {
        nTempDays -= DaysInMonth( *pMonth, *pYear );
        (*pMonth)++;
    }
    *pDay = (USHORT)nTempDays;
}

/**
 * Get week difference between 2 dates
 *
 * new Weeks(date1,date2,mode) function for StarCalc
 *
 * Two modes of operation are provided.
 * The first is just a simple division by 7 calculation.
 *
 * The second calculates the diffence by week of year.
 *
 * The International Standard IS-8601 has decreed that Monday
 * shall be the first day of the week.
 *
 * A week that lies partly in one year and partly in annother
 * is assigned a number in the the year in which most of its days lie.
 *
 * That means that week 1 of any year is the week that contains the 4. January
 *
 * The internal representation of a Date used in the Addin is the number of days based on 01/01/0001
 *
 * A WeekDay can be then calculated by substracting 1 and calculating the rest of
 * a division by 7, which gives a 0 - 6 value for Monday - Sunday
 *
 * Using the 4. January rule explained above the formula
 *
 *	nWeek1= ( nDays1 - nJan4 + ( (nJan4-1) % 7 ) ) / 7 + 1;
 *
 * calculates a number between 0-53 for each day which is in the same year as nJan4
 * where 0 means that this week belonged to the year before.
 *
 * If a day in the same or annother year is used in this formula this calculates
 * an calendar week offset from a given 4. January
 *
 *	nWeek2 = ( nDays2 - nJan4 + ( (nJan4-1) % 7 ) ) / 7 + 1;
 *
 * The 4.January of first Date Argument can thus be used to calculate
 * the week difference by calendar weeks which is then nWeek = nWeek2 - nWeek1
 *
 * which can be optimized to
 *
 * nWeek = ( (nDays2-nJan4+((nJan4-1)%7))/7 ) - ( (nDays1-nJan4+((nJan4-1)%7))/7 )
 *
 * Note: All calculations are operating on the long integer data type
 * % is the modulo operator in C which calculates the rest of an Integer division
 *
 *
 * @param *r - return value for the StarCalc function
 * @param d1 - date value (in StarCalc representation based 12/30/1899), usually the older date
 * @param d2 - date value (in StarCalc representation based 12/30/1899), usually the younger date
 * @param dMode - mode of operation
 *
 * mode 0 is the interval between the dates in month, that is days / 7
 *
 * mode 1 is the difference by week of year
 *
 */
void CALLTYPE ScDate_GetDiffWeeks(double *r, double *d1, double *d2, double *dMode)
{
  long nDays1=0;
  long nDays2=0;
  int nMode=0;

  if ( d1 ) nDays1=(long)floor(*d1)+nNullDate;
  if ( d2 ) nDays2=(long)floor(*d2)+nNullDate;

  if ( dMode) nMode=(int)*dMode;

  if ( nMode == 1 ) {

	USHORT nDay,nMonth,nYear;
	long nJan4;

	DaysToDate(nDays1,&nDay,&nMonth,&nYear);
	nJan4=DateToDays(4,1,nYear);

	*r=(double) ( ( (nDays2-nJan4+((nJan4-1)%7))/7 ) - ( (nDays1-nJan4+((nJan4-1)%7))/7 ) );

  } else {

	*r= (double) ( (nDays2 - nDays1) / 7 ) ;
  }

}

/**
 * Get month difference between 2 dates
 * =Month(start, end, mode) Function for StarCalc
 *
 * two modes are provided
 *
 * @param *r - return value for the StarCalc function
 * @param d1 - date value, start date
 * @param d2 - date value, end date
 * @param dMode - mode of operation
 *
 * mode 0 is the interval between the dates in month
 *
 * mode 1 is the difference in calendar month
 *
 */
void CALLTYPE ScDate_GetDiffMonths(double *r, double *d1, double *d2, double *dMode)
{
  USHORT nDay1,nMonth1,nYear1;
  USHORT nDay2,nMonth2,nYear2;
  long nDays1=0;
  long nDays2=0;
  int nMode=0;

  if ( dMode) nMode=(int)*dMode;

  if ( d1 ) nDays1=(long)floor(*d1)+nNullDate;
  if ( d2 ) nDays2=(long)floor(*d2)+nNullDate;

  DaysToDate(nDays1,&nDay1,&nMonth1,&nYear1);
  DaysToDate(nDays2,&nDay2,&nMonth2,&nYear2);

  *r=(double) ( nMonth2 - nMonth1 + (nYear2 - nYear1) * 12 );
  if ( nMode == 1 || nDays1 == nDays2 ) return;

  if ( nDays1 < nDays2 ) {
	if ( nDay1 > nDay2 ) {
		*r -= 1;
	}
  } else {
	if ( nDay1 < nDay2 ) {
		*r += 1;
	}
  }

}

/**
 * Get Year difference between 2 dates
 *
 * two modes are provided
 *
 * @param *r - return value for the StarCalc function
 * @param d1 - date value, start date
 * @param d2 - date value, end date
 * @param dMode - mode of operation
 *
 * mode 0 is the interval between the dates in years
 *
 * mode 1 is the difference in calendar years
 *
 */
void CALLTYPE ScDate_GetDiffYears(double *r, double *d1, double *d2, double *dMode)
{
  USHORT nDay1,nMonth1,nYear1;
  USHORT nDay2,nMonth2,nYear2;
  long nDays1=0;
  long nDays2=0;
  int nMode=0;

  if ( dMode) nMode=(int)*dMode;

  if ( d1 ) nDays1=(long)floor(*d1)+nNullDate;
  if ( d2 ) nDays2=(long)floor(*d2)+nNullDate;

  DaysToDate(nDays1,&nDay1,&nMonth1,&nYear1);
  DaysToDate(nDays2,&nDay2,&nMonth2,&nYear2);
  if ( nMode != 1 ) {
	ScDate_GetDiffMonths(r,d1,d2,dMode);
	*r= (double) ( ((int) *r) / 12 );
  } else {
	  *r=(double) ( nYear2 - nYear1 );
  }
}

/**
 * Check if a Date is in a leap year in the Gregorian calendar
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc representation based 12/30/1899)
 *
 */
void CALLTYPE ScDate_IsLeapYear(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);

  *r=(double) ( IsLeapYear(nYear) );

}

/**
 * Get the Number of Days in the month for a date
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc representation based 12/30/1899)
 *
 */
void CALLTYPE ScDate_DaysInMonth(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);
  *r=(double) ( DaysInMonth( nMonth, nYear) );

}

/**
 * Get number of weeks in the year for a date
 *
 * Most years have 52 weeks, but years that start on a Thursday
 * and leep years that start on a Wednesday have 53 weeks
 *
 * The International Standard IS-8601 has decreed that Monday
 * shall be the first day of the week.
 *
 * A WeekDay can be calculated by substracting 1 and calculating the rest of
 * a division by 7 from the internal date represention
 * which gives a 0 - 6 value for Monday - Sunday
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc represantaion based 30.12.1899)
 *
 * @see #IsLeapYear #WeekNumber
 *
 */
void CALLTYPE ScDate_WeeksInYear(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;
  long nJan1WeekDay;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);

  nJan1WeekDay= ( DateToDays(1,1,nYear) - 1) % 7;

  if ( nJan1WeekDay == 3 ) { /* Thursday */
	*r=(double) 53;
	return;
  } else if ( nJan1WeekDay == 2 ) { /* Wednesday */
	*r= (double) ( IsLeapYear(nYear) ? 53 : 52 );
  } else {
	*r= (double) 52;
  }
}

/**
 * Get number of days in the year of a date specified
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc represantaion based 30.12.1899)
 *
 */
void CALLTYPE ScDate_DaysInYear(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);
  *r=(double) ( IsLeapYear(nYear) ? 366 : 365 );

}

/**
 * Tell StarCalc how many new functions this Addin provides.
 *
 * It's called before any of these new functions is actually
 * executed and is also used to initialize the NullDate here.
 *
 * StarCalc uses a Date Base 12/30/1899
 * If not specified otherwise in the Options for the Spreedsheet Document
 *
 *
 * @param *nCount - returns the number of functions which are exported to StarCalc
 *
 */
void CALLTYPE GetFunctionCount( USHORT *nCount )
{

  /* initialize nNullDate Value 0 is 12/30/1899 */
  nNullDate=DateToDays(NULLDATE_Day, NULLDATE_Month, NULLDATE_Year);

  *nCount = 7;
}

/**
 * Provides neccessary data for each new function to StarCalc
 *
 * @param *nNo Input: Function number between 0 and nCount - 1
 * @param *pFuncName Output: Functionname which should be called in the AddIn-DLL
 * @param *nParamCount Output: Number of Parameter. Must be greater than 0, because there's always a return-Value. Maximum is 16.
 * @param *peType Output: Pointer to arrray with exactly 16 variables of typ Paramtype. nParamCount Entries are set to the type of the corresponding Parameters.
 * @param *pInternalName Output: Functionname as seen by the Spreadsheet user
 *
 * @see #GetFunctionCount, #GetParameterDescription
 *
 */
void CALLTYPE GetFunctionData( USHORT *    nNo,
                               char *      pFuncName,
                               USHORT *    nParamCount,
                               ParamType * peType,
                               char *      pInternalName )
{

	 switch( *nNo ) {
	 case 0:
	 SO_StringCopy( pInternalName, getText(DFA_WEEK_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_GetDiffWeeks" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 peType[2] = PTR_DOUBLE;
	 peType[3] = PTR_DOUBLE;
	 *nParamCount=4;
	 break;

	 case 1:
	 SO_StringCopy( pInternalName, getText(DFA_MONTHS_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_GetDiffMonths" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 peType[2] = PTR_DOUBLE;
	 peType[3] = PTR_DOUBLE;
	 *nParamCount=4;
	 break;

	 case 2:
	 SO_StringCopy( pInternalName, getText(DFA_YEARS_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_GetDiffYears" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 peType[2] = PTR_DOUBLE;
	 peType[3] = PTR_DOUBLE;
	 *nParamCount=4;
	 break;

	 case 3:
	 SO_StringCopy( pInternalName, getText(DFA_ISLEAPYEAR_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_IsLeapYear" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 case 4:
	 SO_StringCopy( pInternalName, getText(DFA_DAYSINMONTH_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_DaysInMonth" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 case 5:
	 SO_StringCopy( pInternalName, getText(DFA_DAYSINYEAR_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_DaysInYear" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 case 6:
	 SO_StringCopy( pInternalName, getText(DFA_WEEKSINYEAR_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_WeeksInYear" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 default:
            *nParamCount    = 0;
            *pFuncName     = 0;
            *pInternalName = 0;
            break;
    }
}

/**
 * Provides descriptions for each new function to StarCalc
 * which are shown is the autopilot
 *
 * @param *nNo Input Parameter, Function number between 0 and nCount - 1
 * @param *nParam Parameter Number
 * @param *pName Output: Name of the parameter
 * @param *pDesc Output: Description of the parameter
 *
 * @see #GetFunctionCount, #GetParameterDescription
 */
void CALLTYPE GetParameterDescription( USHORT* nNo, USHORT* nParam,
char* pName, char* pDesc )
{
	*pName = 0;
	*pDesc = 0;

	switch ( *nNo ) {
	case 0:	/* Weeks */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_WEEK_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE1_NAME));
			SO_StringCopy(pDesc,getText(DFA_WEEK_PAR1_DESC));
			break;
		case 2:
			SO_StringCopy(pName,getText(DFA_PAR_DATE2_NAME));
			SO_StringCopy(pDesc,getText(DFA_WEEK_PAR2_DESC));
			break;
		case 3:
			SO_StringCopy(pName,getText(DFA_PAR_MODE_NAME));
			SO_StringCopy(pDesc,getText(DFA_WEEK_PAR3_DESC));
			break;
		}
		break;
	case 1: /* Months */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_MONTHS_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE1_NAME));
			SO_StringCopy(pDesc,getText(DFA_MONTHS_PAR1_DESC));
			break;
		case 2:
			SO_StringCopy(pName,getText(DFA_PAR_DATE2_NAME));
			SO_StringCopy(pDesc,getText(DFA_MONTHS_PAR2_DESC));
			break;
		case 3:
			SO_StringCopy(pName,getText(DFA_PAR_MODE_NAME));
			SO_StringCopy(pDesc,getText(DFA_MONTHS_PAR3_DESC));
			break;
		}
		break;
	case 2: /* Years */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_YEARS_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE1_NAME));
			SO_StringCopy(pDesc,getText(DFA_YEARS_PAR1_DESC));
			break;
		case 2:
			SO_StringCopy(pName,getText(DFA_PAR_DATE2_NAME));
			SO_StringCopy(pDesc,getText(DFA_YEARS_PAR2_DESC));
			break;
		case 3:
			SO_StringCopy(pName,getText(DFA_PAR_MODE_NAME));
			SO_StringCopy(pDesc,getText(DFA_YEARS_PAR3_DESC));
			break;
		}
	   break;
	case 3:	/* IsLeapYear */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_ISLEAPYEAR_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;
	case 4:	/* DaysInMonth */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_DAYSINMONTH_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;
	case 5:	/* DaysInYear */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_DAYSINYEAR_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;

	case 6:	/* WeeksInYear */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_WEEKSINYEAR_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;
	}

}

/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dfa.cl,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 11:51:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

/* static char datefunc_Id[]="@(#) StarCalc Datefunc AddIn (c) 1998-2000 Sun Microsystems, Inc."; */

#include <string.h>
#include <stdlib.h>
#include <math.h>

#include <xlang.h>
#include <addin.h>
#include <dfa.hrc>

/**
 * the current language the Addin is using
 */
static USHORT _nLanguage=LANGUAGE_ENGLISH;

/**
 * StarCalc calls this function to set a new current Language for the Addin
 *
 * @param *nLanguage
 *
 */
void CALLTYPE SetLanguage( USHORT* nLanguage )
{
	_nLanguage = GetNeutralLanguage( *nLanguage );
}

/**
 * Null Date, initialized in GetFunctionCount
 *
 * StarCalc uses a BaseDate 12/30/1899
 * If not specified otherwise in the Settings for the Spreedsheet Document.
 *
 * There's no way to get the Spreadsheet settings from whithin a simple addin,
 * so this Addin can only be used by documents using the default BaseDate setting.
 *
 * The functions in this Addin use a BaseDate 01/01/0001
 * The nNullDate Variable is the StarCalc BaseDate converted to
 * this internal date representation.
 *
 * @see #GetFunctionCount
 *
 */

static ULONG nNullDate=0;

#define NULLDATE_Year  1899
#define NULLDATE_Month 12
#define NULLDATE_Day   30

/**
 * Array holding values for month length, used in DaysInMonth() function
 *
 * @see #DaysInMonth
 *
 */
static USHORT aDaysInMonth[12] = { 31, 28, 31, 30, 31, 30,
                                   31, 31, 30, 31, 30, 31 };

/**
 * Check if a year is a leap year in the Gregorian calendar
 *
 * @param nYear the year which should be checked
 * @return true if the year is a leap year, false otherwise.
 *
 * @see #DaysInMonth, #IsLeapYear,
 * @see #ScDate_DaysInMonth, #ScDate_IsLeapYear, #ScDate_WeeksInYear
 *
 */
static BOOL IsLeapYear( USHORT nYear )
{
    return (BOOL)((((nYear % 4) == 0) && ((nYear % 100) != 0)) || ((nYear % 400) == 0));
}

/**
 * Get the number of days in a specified month
 *
 * @param nMonth the number of the Month
 * @param nYear the year
 * @return number of days
 *
 */
static USHORT DaysInMonth( USHORT nMonth, USHORT nYear )
{
    if ( nMonth != 2 )
        return aDaysInMonth[nMonth-1];
    else
    {
        if ( IsLeapYear(nYear) )
            return aDaysInMonth[nMonth-1] + 1;
        else
            return aDaysInMonth[nMonth-1];
    }
}

/**
 * Convert a date to a count of days starting from 01/01/0001
 *
 * The internal representation of a Date used in this Addin
 * is the number of days between 01/01/0001 and the date
 * this function converts a Day , Month, Year representation
 * to this internal Date value.
 *
 * @param nDay the day of the Month
 * @param nMonth the number of the Month
 * @param nYear the Year
 * @return count of days from 01/01/0001 to the date specified
 *
 */
static long DateToDays( USHORT nDay, USHORT nMonth, USHORT nYear )
{
    long nDays;
    USHORT i;

    nDays = ((ULONG)nYear-1) * 365;
    nDays += ((nYear-1) / 4) - ((nYear-1) / 100) + ((nYear-1) / 400);

    for( i = 1; i < nMonth; i++ )
        nDays += DaysInMonth(i,nYear);
    nDays += nDay;

    return nDays;
}

/**
 * Convert a count of days starting from 01/01/0001 to a date
 *
 * The internal representation of a Date used in this Addin
 * is the number of days between 01/01/0001 and the date
 * this function converts this internal Date value
 * to a Day , Month, Year representation of a Date.
 *
 * @param nDay count of days from 01/01/0001
 * @param *pDay pointer to a variable for the day of the month
 * @param *pMonth pointer to a variable for the month
 * @param *pYear pointer to a variable for the year
 *
 */
static void DaysToDate( long nDays,
                        USHORT *pDay, USHORT *pMonth, USHORT *pYear )
{
    long    nTempDays;
    long    i = 0;
    BOOL    bCalc;

    do
    {
        nTempDays = (long)nDays;
        *pYear = (USHORT)((nTempDays / 365) - i);
        nTempDays -= ((ULONG) *pYear -1) * 365;
        nTempDays -= (( *pYear -1) / 4) - (( *pYear -1) / 100) + ((*pYear -1) / 400);
        bCalc = FALSE;
        if ( nTempDays < 1 )
        {
            i++;
            bCalc = TRUE;
        }
        else
        {
            if ( nTempDays > 365 )
            {
                if ( (nTempDays != 366) || !IsLeapYear( *pYear ) )
                {
                    i--;
                    bCalc = TRUE;
                }
            }
        }
    }
    while ( bCalc );

    *pMonth = 1;
    while ( (ULONG)nTempDays > DaysInMonth( *pMonth, *pYear ) )
    {
        nTempDays -= DaysInMonth( *pMonth, *pYear );
        (*pMonth)++;
    }
    *pDay = (USHORT)nTempDays;
}

/**
 * Get week difference between 2 dates
 *
 * new Weeks(date1,date2,mode) function for StarCalc
 *
 * Two modes of operation are provided.
 * The first is just a simple division by 7 calculation.
 *
 * The second calculates the diffence by week of year.
 *
 * The International Standard IS-8601 has decreed that Monday
 * shall be the first day of the week.
 *
 * A week that lies partly in one year and partly in annother
 * is assigned a number in the the year in which most of its days lie.
 *
 * That means that week 1 of any year is the week that contains the 4. January
 *
 * The internal representation of a Date used in the Addin is the number of days based on 01/01/0001
 *
 * A WeekDay can be then calculated by substracting 1 and calculating the rest of
 * a division by 7, which gives a 0 - 6 value for Monday - Sunday
 *
 * Using the 4. January rule explained above the formula
 *
 *	nWeek1= ( nDays1 - nJan4 + ( (nJan4-1) % 7 ) ) / 7 + 1;
 *
 * calculates a number between 0-53 for each day which is in the same year as nJan4
 * where 0 means that this week belonged to the year before.
 *
 * If a day in the same or annother year is used in this formula this calculates
 * an calendar week offset from a given 4. January
 *
 *	nWeek2 = ( nDays2 - nJan4 + ( (nJan4-1) % 7 ) ) / 7 + 1;
 *
 * The 4.January of first Date Argument can thus be used to calculate
 * the week difference by calendar weeks which is then nWeek = nWeek2 - nWeek1
 *
 * which can be optimized to
 *
 * nWeek = ( (nDays2-nJan4+((nJan4-1)%7))/7 ) - ( (nDays1-nJan4+((nJan4-1)%7))/7 )
 *
 * Note: All calculations are operating on the long integer data type
 * % is the modulo operator in C which calculates the rest of an Integer division
 *
 *
 * @param *r - return value for the StarCalc function
 * @param d1 - date value (in StarCalc representation based 12/30/1899), usually the older date
 * @param d2 - date value (in StarCalc representation based 12/30/1899), usually the younger date
 * @param dMode - mode of operation
 *
 * mode 0 is the interval between the dates in month, that is days / 7
 *
 * mode 1 is the difference by week of year
 *
 */
void CALLTYPE ScDate_GetDiffWeeks(double *r, double *d1, double *d2, double *dMode)
{
  long nDays1=0;
  long nDays2=0;
  int nMode=0;

  if ( d1 ) nDays1=(long)floor(*d1)+nNullDate;
  if ( d2 ) nDays2=(long)floor(*d2)+nNullDate;

  if ( dMode) nMode=(int)*dMode;

  if ( nMode == 1 ) {

	USHORT nDay,nMonth,nYear;
	long nJan4;

	DaysToDate(nDays1,&nDay,&nMonth,&nYear);
	nJan4=DateToDays(4,1,nYear);

	*r=(double) ( ( (nDays2-nJan4+((nJan4-1)%7))/7 ) - ( (nDays1-nJan4+((nJan4-1)%7))/7 ) );

  } else {

	*r= (double) ( (nDays2 - nDays1) / 7 ) ;
  }

}

/**
 * Get month difference between 2 dates
 * =Month(start, end, mode) Function for StarCalc
 *
 * two modes are provided
 *
 * @param *r - return value for the StarCalc function
 * @param d1 - date value, start date
 * @param d2 - date value, end date
 * @param dMode - mode of operation
 *
 * mode 0 is the interval between the dates in month
 *
 * mode 1 is the difference in calendar month
 *
 */
void CALLTYPE ScDate_GetDiffMonths(double *r, double *d1, double *d2, double *dMode)
{
  USHORT nDay1,nMonth1,nYear1;
  USHORT nDay2,nMonth2,nYear2;
  long nDays1=0;
  long nDays2=0;
  int nMode=0;

  if ( dMode) nMode=(int)*dMode;

  if ( d1 ) nDays1=(long)floor(*d1)+nNullDate;
  if ( d2 ) nDays2=(long)floor(*d2)+nNullDate;

  DaysToDate(nDays1,&nDay1,&nMonth1,&nYear1);
  DaysToDate(nDays2,&nDay2,&nMonth2,&nYear2);

  *r=(double) ( nMonth2 - nMonth1 + (nYear2 - nYear1) * 12 );
  if ( nMode == 1 || nDays1 == nDays2 ) return;

  if ( nDays1 < nDays2 ) {
	if ( nDay1 > nDay2 ) {
		*r -= 1;
	}
  } else {
	if ( nDay1 < nDay2 ) {
		*r += 1;
	}
  }

}

/**
 * Get Year difference between 2 dates
 *
 * two modes are provided
 *
 * @param *r - return value for the StarCalc function
 * @param d1 - date value, start date
 * @param d2 - date value, end date
 * @param dMode - mode of operation
 *
 * mode 0 is the interval between the dates in years
 *
 * mode 1 is the difference in calendar years
 *
 */
void CALLTYPE ScDate_GetDiffYears(double *r, double *d1, double *d2, double *dMode)
{
  USHORT nDay1,nMonth1,nYear1;
  USHORT nDay2,nMonth2,nYear2;
  long nDays1=0;
  long nDays2=0;
  int nMode=0;

  if ( dMode) nMode=(int)*dMode;

  if ( d1 ) nDays1=(long)floor(*d1)+nNullDate;
  if ( d2 ) nDays2=(long)floor(*d2)+nNullDate;

  DaysToDate(nDays1,&nDay1,&nMonth1,&nYear1);
  DaysToDate(nDays2,&nDay2,&nMonth2,&nYear2);
  if ( nMode != 1 ) {
	ScDate_GetDiffMonths(r,d1,d2,dMode);
	*r= (double) ( ((int) *r) / 12 );
  } else {
	  *r=(double) ( nYear2 - nYear1 );
  }
}

/**
 * Check if a Date is in a leap year in the Gregorian calendar
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc representation based 12/30/1899)
 *
 */
void CALLTYPE ScDate_IsLeapYear(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);

  *r=(double) ( IsLeapYear(nYear) );

}

/**
 * Get the Number of Days in the month for a date
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc representation based 12/30/1899)
 *
 */
void CALLTYPE ScDate_DaysInMonth(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);
  *r=(double) ( DaysInMonth( nMonth, nYear) );

}

/**
 * Get number of weeks in the year for a date
 *
 * Most years have 52 weeks, but years that start on a Thursday
 * and leep years that start on a Wednesday have 53 weeks
 *
 * The International Standard IS-8601 has decreed that Monday
 * shall be the first day of the week.
 *
 * A WeekDay can be calculated by substracting 1 and calculating the rest of
 * a division by 7 from the internal date represention
 * which gives a 0 - 6 value for Monday - Sunday
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc represantaion based 30.12.1899)
 *
 * @see #IsLeapYear #WeekNumber
 *
 */
void CALLTYPE ScDate_WeeksInYear(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;
  long nJan1WeekDay;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);

  nJan1WeekDay= ( DateToDays(1,1,nYear) - 1) % 7;

  if ( nJan1WeekDay == 3 ) { /* Thursday */
	*r=(double) 53;
	return;
  } else if ( nJan1WeekDay == 2 ) { /* Wednesday */
	*r= (double) ( IsLeapYear(nYear) ? 53 : 52 );
  } else {
	*r= (double) 52;
  }
}

/**
 * Get number of days in the year of a date specified
 *
 * @param *r - return value for the StarCalc function
 * @param d - date value (in StarCalc represantaion based 30.12.1899)
 *
 */
void CALLTYPE ScDate_DaysInYear(double *r, double *d)
{
  ULONG nDays;
  USHORT nDay, nMonth, nYear;
  double v=0.0;

  if ( d ) v=*d;
  nDays=(int) v + nNullDate;

  DaysToDate(nDays,&nDay,&nMonth,&nYear);
  *r=(double) ( IsLeapYear(nYear) ? 366 : 365 );

}

/**
 * Tell StarCalc how many new functions this Addin provides.
 *
 * It's called before any of these new functions is actually
 * executed and is also used to initialize the NullDate here.
 *
 * StarCalc uses a Date Base 12/30/1899
 * If not specified otherwise in the Options for the Spreedsheet Document
 *
 *
 * @param *nCount - returns the number of functions which are exported to StarCalc
 *
 */
void CALLTYPE GetFunctionCount( USHORT *nCount )
{

  /* initialize nNullDate Value 0 is 12/30/1899 */
  nNullDate=DateToDays(NULLDATE_Day, NULLDATE_Month, NULLDATE_Year);

  *nCount = 7;
}

/**
 * Provides neccessary data for each new function to StarCalc
 *
 * @param *nNo Input: Function number between 0 and nCount - 1
 * @param *pFuncName Output: Functionname which should be called in the AddIn-DLL
 * @param *nParamCount Output: Number of Parameter. Must be greater than 0, because there's always a return-Value. Maximum is 16.
 * @param *peType Output: Pointer to arrray with exactly 16 variables of typ Paramtype. nParamCount Entries are set to the type of the corresponding Parameters.
 * @param *pInternalName Output: Functionname as seen by the Spreadsheet user
 *
 * @see #GetFunctionCount, #GetParameterDescription
 *
 */
void CALLTYPE GetFunctionData( USHORT *    nNo,
                               char *      pFuncName,
                               USHORT *    nParamCount,
                               ParamType * peType,
                               char *      pInternalName )
{

	 switch( *nNo ) {
	 case 0:
	 SO_StringCopy( pInternalName, getText(DFA_WEEK_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_GetDiffWeeks" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 peType[2] = PTR_DOUBLE;
	 peType[3] = PTR_DOUBLE;
	 *nParamCount=4;
	 break;

	 case 1:
	 SO_StringCopy( pInternalName, getText(DFA_MONTHS_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_GetDiffMonths" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 peType[2] = PTR_DOUBLE;
	 peType[3] = PTR_DOUBLE;
	 *nParamCount=4;
	 break;

	 case 2:
	 SO_StringCopy( pInternalName, getText(DFA_YEARS_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_GetDiffYears" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 peType[2] = PTR_DOUBLE;
	 peType[3] = PTR_DOUBLE;
	 *nParamCount=4;
	 break;

	 case 3:
	 SO_StringCopy( pInternalName, getText(DFA_ISLEAPYEAR_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_IsLeapYear" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 case 4:
	 SO_StringCopy( pInternalName, getText(DFA_DAYSINMONTH_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_DaysInMonth" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 case 5:
	 SO_StringCopy( pInternalName, getText(DFA_DAYSINYEAR_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_DaysInYear" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 case 6:
	 SO_StringCopy( pInternalName, getText(DFA_WEEKSINYEAR_NAME) );
	 SO_StringCopy( pFuncName,     "ScDate_WeeksInYear" );
	 peType[0] = PTR_DOUBLE;
	 peType[1] = PTR_DOUBLE;
	 *nParamCount=2;
	 break;

	 default:
            *nParamCount    = 0;
            *pFuncName     = 0;
            *pInternalName = 0;
            break;
    }
}

/**
 * Provides descriptions for each new function to StarCalc
 * which are shown is the autopilot
 *
 * @param *nNo Input Parameter, Function number between 0 and nCount - 1
 * @param *nParam Parameter Number
 * @param *pName Output: Name of the parameter
 * @param *pDesc Output: Description of the parameter
 *
 * @see #GetFunctionCount, #GetParameterDescription
 */
void CALLTYPE GetParameterDescription( USHORT* nNo, USHORT* nParam,
char* pName, char* pDesc )
{
	*pName = 0;
	*pDesc = 0;

	switch ( *nNo ) {
	case 0:	/* Weeks */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_WEEK_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE1_NAME));
			SO_StringCopy(pDesc,getText(DFA_WEEK_PAR1_DESC));
			break;
		case 2:
			SO_StringCopy(pName,getText(DFA_PAR_DATE2_NAME));
			SO_StringCopy(pDesc,getText(DFA_WEEK_PAR2_DESC));
			break;
		case 3:
			SO_StringCopy(pName,getText(DFA_PAR_MODE_NAME));
			SO_StringCopy(pDesc,getText(DFA_WEEK_PAR3_DESC));
			break;
		}
		break;
	case 1: /* Months */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_MONTHS_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE1_NAME));
			SO_StringCopy(pDesc,getText(DFA_MONTHS_PAR1_DESC));
			break;
		case 2:
			SO_StringCopy(pName,getText(DFA_PAR_DATE2_NAME));
			SO_StringCopy(pDesc,getText(DFA_MONTHS_PAR2_DESC));
			break;
		case 3:
			SO_StringCopy(pName,getText(DFA_PAR_MODE_NAME));
			SO_StringCopy(pDesc,getText(DFA_MONTHS_PAR3_DESC));
			break;
		}
		break;
	case 2: /* Years */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_YEARS_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE1_NAME));
			SO_StringCopy(pDesc,getText(DFA_YEARS_PAR1_DESC));
			break;
		case 2:
			SO_StringCopy(pName,getText(DFA_PAR_DATE2_NAME));
			SO_StringCopy(pDesc,getText(DFA_YEARS_PAR2_DESC));
			break;
		case 3:
			SO_StringCopy(pName,getText(DFA_PAR_MODE_NAME));
			SO_StringCopy(pDesc,getText(DFA_YEARS_PAR3_DESC));
			break;
		}
	   break;
	case 3:	/* IsLeapYear */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_ISLEAPYEAR_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;
	case 4:	/* DaysInMonth */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_DAYSINMONTH_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;
	case 5:	/* DaysInYear */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_DAYSINYEAR_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;

	case 6:	/* WeeksInYear */
		switch ( *nParam ) {
		case 0:
			SO_StringCopy(pDesc,getText(DFA_WEEKSINYEAR_DESC));
			break;
		case 1:
			SO_StringCopy(pName,getText(DFA_PAR_DATE_NAME));
			SO_StringCopy(pDesc,getText(DFA_PAR_DATE_DESC)); /* StarCalc Value */
			break;
		}
		break;
	}

}


Remove local test

Remove local test

// #################### direct test
// test an address
// 68e23530deb6d5011ab56d8ad9f7b4a3b424f1112f08606357497495929f72dc
/*
k_local[0] = 0x68e23530;
k_local[1] = 0xdeb6d501;
k_local[2] = 0x1ab56d8a;
k_local[3] = 0xd9f7b4a3;
k_local[4] = 0xb424f111;
k_local[5] = 0x2f086063;
k_local[6] = 0x57497495;
k_local[7] = 0x929f72dc;
*/
// test an address up/down
// 68e23530deb6d5011ab56d8ad9f7b4a3b424f1112f08606357497495929f72dc
/*
k_local[7] = 0x68e23530;
k_local[6] = 0xdeb6d501;
k_local[5] = 0x1ab56d8a;
k_local[4] = 0xd9f7b4a3;
k_local[3] = 0xb424f111;
k_local[2] = 0x2f086063;
k_local[1] = 0x57497495;
k_local[0] = 0x929f72dc;
*/
// test an address swap endian
// 68e23530deb6d5011ab56d8ad9f7b4a3b424f1112f08606357497495929f72dc
/*
k_local[0] = 0x3035e268;
k_local[1] = 0x01d5b6de;
k_local[2] = 0x8a6db51a;
k_local[3] = 0xa3b4f7d9;
k_local[4] = 0x11f124b4;
k_local[5] = 0x6360082f;
k_local[6] = 0x95744957;
k_local[7] = 0xdc729f92;
*/
// ####################

// the base point G in compressed form
#define SECP256K1_G0 0x00000002
#define SECP256K1_G1 0x79be667e
#define SECP256K1_G2 0xf9dcbbac
#define SECP256K1_G3 0x55a06295
#define SECP256K1_G4 0xce870b07
#define SECP256K1_G5 0x029bfcdb
#define SECP256K1_G6 0x2dce28d9
#define SECP256K1_G7 0x59f2815b
#define SECP256K1_G8 0x16f81798

// the base point G in compressed form
// front align
/*
#define SECP256K1_G0 0x0279be66
#define SECP256K1_G1 0x7ef9dcbb
#define SECP256K1_G2 0xac55a062
#define SECP256K1_G3 0x95ce870b
#define SECP256K1_G4 0x07029bfc
#define SECP256K1_G5 0xdb2dce28
#define SECP256K1_G6 0xd959f281
#define SECP256K1_G7 0x5b16f817
#define SECP256K1_G8 0x98000000
*/

//
// swap endian
/*
#define SECP256K1_G0 0x66BE7902
#define SECP256K1_G1 0xBBDCF97E
#define SECP256K1_G2 0x62A055AC
#define SECP256K1_G3 0x0B87CE95
#define SECP256K1_G4 0xFC9B0207
#define SECP256K1_G5 0x28CE2DDB
#define SECP256K1_G6 0x81F259D9
#define SECP256K1_G7 0x17F8165B
#define SECP256K1_G8 0x00000098
*/

__kernel void generateKeysKernel_parse_public(__global u32 *r, __global const u32 *k)
{
    u32 g_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    u32 r_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    u32 k_local[PRIVATE_KEY_LENGTH];
    secp256k1_t g_xy_local;

    g_local[0] = SECP256K1_G0;
    g_local[1] = SECP256K1_G1;
    g_local[2] = SECP256K1_G2;
    g_local[3] = SECP256K1_G3;
    g_local[4] = SECP256K1_G4;
    g_local[5] = SECP256K1_G5;
    g_local[6] = SECP256K1_G6;
    g_local[7] = SECP256K1_G7;
    g_local[8] = SECP256K1_G8;

    // global to local
    k_local[0] = k[0];
    k_local[1] = k[1];
    k_local[2] = k[2];
    k_local[3] = k[3];
    k_local[4] = k[4];
    k_local[5] = k[5];
    k_local[6] = k[6];
    k_local[7] = k[7];

    parse_public(&g_xy_local, g_local);
    point_mul(r_local, k_local, &g_xy_local);

    // local to global
    r[0] = r_local[0];
    r[1] = r_local[1];
    r[2] = r_local[2];
    r[3] = r_local[3];
    r[4] = r_local[4];
    r[5] = r_local[5];
    r[6] = r_local[6];
    r[7] = r_local[7];
    r[8] = r_local[8];
}

__kernel void generateKeysKernel_transform_public(__global u32 *r, __global const u32 *k)
{
    u32 g_local[PUBLIC_KEY_LENGTH_WITHOUT_PARITY];
    u32 r_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    u32 k_local[PRIVATE_KEY_LENGTH];
    secp256k1_t g_xy_local;

    g_local[0] = SECP256K1_G1;
    g_local[1] = SECP256K1_G2;
    g_local[2] = SECP256K1_G3;
    g_local[3] = SECP256K1_G4;
    g_local[4] = SECP256K1_G5;
    g_local[5] = SECP256K1_G6;
    g_local[6] = SECP256K1_G7;
    g_local[7] = SECP256K1_G8;

    // global to local
    k_local[0] = k[0];
    k_local[1] = k[1];
    k_local[2] = k[2];
    k_local[3] = k[3];
    k_local[4] = k[4];
    k_local[5] = k[5];
    k_local[6] = k[6];
    k_local[7] = k[7];

    const u32 first_byte = SECP256K1_G0 & 0xff;
    transform_public(&g_xy_local, g_local, first_byte);
    point_mul(r_local, k_local, &g_xy_local);

    // local to global
    r[0] = r_local[0];
    r[1] = r_local[1];
    r[2] = r_local[2];
    r[3] = r_local[3];
    r[4] = r_local[4];
    r[5] = r_local[5];
    r[6] = r_local[6];
    r[7] = r_local[7];
    r[8] = r_local[8];
}

__kernel void test_convert_to_window_naf(__global u32 *wnaf_global, __global u32 *loop_start_global, __global const u32 *k_global)
{
    u32 wnaf_local[SECP256K1_NAF_SIZE];
    u32 k_local[PRIVATE_KEY_LENGTH];

    // global to local
    for(int i=0; i < PRIVATE_KEY_LENGTH; i++) {
        k_local[i] = k_global[i];
    }

    int loop_start_local = convert_to_window_naf(wnaf_local, k_local);

    // local to global
    loop_start_global[0] = loop_start_local;

    for(int i=0; i < SECP256K1_NAF_SIZE; i++) {
        wnaf_global[i] = wnaf_local[i];
    }
}

__kernel void test_parse_public_g(__global u32 *xy_global)
{
    u32 g_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    secp256k1_t xy_pre_computed_local;

    g_local[0] = SECP256K1_G0;
    g_local[1] = SECP256K1_G1;
    g_local[2] = SECP256K1_G2;
    g_local[3] = SECP256K1_G3;
    g_local[4] = SECP256K1_G4;
    g_local[5] = SECP256K1_G5;
    g_local[6] = SECP256K1_G6;
    g_local[7] = SECP256K1_G7;
    g_local[8] = SECP256K1_G8;

    parse_public(&xy_pre_computed_local, g_local);

    for(int i=0; i < SECP256K1_PRE_COMPUTED_XY_SIZE; i++) {
        xy_global[i] = xy_pre_computed_local.xy[i];
    }
}

__kernel void test_parse_public(__global u32 *xy_global, __global const u32 *public_address_global)
{
    u32 public_address_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    secp256k1_t xy_pre_computed_local;

    for(int i=0; i < PUBLIC_KEY_LENGTH_WITH_PARITY; i++) {
        public_address_local[i] = public_address_global[i];
    }

    /*
    g_local[0] = SECP256K1_G0;
    g_local[1] = SECP256K1_G1;
    g_local[2] = SECP256K1_G2;
    g_local[3] = SECP256K1_G3;
    g_local[4] = SECP256K1_G4;
    g_local[5] = SECP256K1_G5;
    g_local[6] = SECP256K1_G6;
    g_local[7] = SECP256K1_G7;
    g_local[8] = SECP256K1_G8;
    */

    parse_public(&xy_pre_computed_local, public_address_local);

    for(int i=0; i < SECP256K1_PRE_COMPUTED_XY_SIZE; i++) {
        xy_global[i] = xy_pre_computed_local.xy[i];
    }
}

// #################### direct test
// test an address
// 68e23530deb6d5011ab56d8ad9f7b4a3b424f1112f08606357497495929f72dc
/*
k_local[0] = 0x68e23530;
k_local[1] = 0xdeb6d501;
k_local[2] = 0x1ab56d8a;
k_local[3] = 0xd9f7b4a3;
k_local[4] = 0xb424f111;
k_local[5] = 0x2f086063;
k_local[6] = 0x57497495;
k_local[7] = 0x929f72dc;
*/
// test an address up/down
// 68e23530deb6d5011ab56d8ad9f7b4a3b424f1112f08606357497495929f72dc
/*
k_local[7] = 0x68e23530;
k_local[6] = 0xdeb6d501;
k_local[5] = 0x1ab56d8a;
k_local[4] = 0xd9f7b4a3;
k_local[3] = 0xb424f111;
k_local[2] = 0x2f086063;
k_local[1] = 0x57497495;
k_local[0] = 0x929f72dc;
*/
// test an address swap endian
// 68e23530deb6d5011ab56d8ad9f7b4a3b424f1112f08606357497495929f72dc
/*
k_local[0] = 0x3035e268;
k_local[1] = 0x01d5b6de;
k_local[2] = 0x8a6db51a;
k_local[3] = 0xa3b4f7d9;
k_local[4] = 0x11f124b4;
k_local[5] = 0x6360082f;
k_local[6] = 0x95744957;
k_local[7] = 0xdc729f92;
*/
// ####################

// the base point G in compressed form
#define SECP256K1_G0 0x00000002
#define SECP256K1_G1 0x79be667e
#define SECP256K1_G2 0xf9dcbbac
#define SECP256K1_G3 0x55a06295
#define SECP256K1_G4 0xce870b07
#define SECP256K1_G5 0x029bfcdb
#define SECP256K1_G6 0x2dce28d9
#define SECP256K1_G7 0x59f2815b
#define SECP256K1_G8 0x16f81798

// the base point G in compressed form
// front align
/*
#define SECP256K1_G0 0x0279be66
#define SECP256K1_G1 0x7ef9dcbb
#define SECP256K1_G2 0xac55a062
#define SECP256K1_G3 0x95ce870b
#define SECP256K1_G4 0x07029bfc
#define SECP256K1_G5 0xdb2dce28
#define SECP256K1_G6 0xd959f281
#define SECP256K1_G7 0x5b16f817
#define SECP256K1_G8 0x98000000
*/

//
// swap endian
/*
#define SECP256K1_G0 0x66BE7902
#define SECP256K1_G1 0xBBDCF97E
#define SECP256K1_G2 0x62A055AC
#define SECP256K1_G3 0x0B87CE95
#define SECP256K1_G4 0xFC9B0207
#define SECP256K1_G5 0x28CE2DDB
#define SECP256K1_G6 0x81F259D9
#define SECP256K1_G7 0x17F8165B
#define SECP256K1_G8 0x00000098
*/

__kernel void generateKeysKernel_parse_public(__global u32 *r, __global const u32 *k)
{
    u32 g_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    u32 r_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    u32 k_local[PRIVATE_KEY_LENGTH];
    secp256k1_t g_xy_local;

    g_local[0] = SECP256K1_G0;
    g_local[1] = SECP256K1_G1;
    g_local[2] = SECP256K1_G2;
    g_local[3] = SECP256K1_G3;
    g_local[4] = SECP256K1_G4;
    g_local[5] = SECP256K1_G5;
    g_local[6] = SECP256K1_G6;
    g_local[7] = SECP256K1_G7;
    g_local[8] = SECP256K1_G8;

    // global to local
    k_local[0] = k[0];
    k_local[1] = k[1];
    k_local[2] = k[2];
    k_local[3] = k[3];
    k_local[4] = k[4];
    k_local[5] = k[5];
    k_local[6] = k[6];
    k_local[7] = k[7];

    parse_public(&g_xy_local, g_local);
    point_mul(r_local, k_local, &g_xy_local);

    // local to global
    r[0] = r_local[0];
    r[1] = r_local[1];
    r[2] = r_local[2];
    r[3] = r_local[3];
    r[4] = r_local[4];
    r[5] = r_local[5];
    r[6] = r_local[6];
    r[7] = r_local[7];
    r[8] = r_local[8];
}

__kernel void generateKeysKernel_transform_public(__global u32 *r, __global const u32 *k)
{
    u32 g_local[PUBLIC_KEY_LENGTH_WITHOUT_PARITY];
    u32 r_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    u32 k_local[PRIVATE_KEY_LENGTH];
    secp256k1_t g_xy_local;

    g_local[0] = SECP256K1_G1;
    g_local[1] = SECP256K1_G2;
    g_local[2] = SECP256K1_G3;
    g_local[3] = SECP256K1_G4;
    g_local[4] = SECP256K1_G5;
    g_local[5] = SECP256K1_G6;
    g_local[6] = SECP256K1_G7;
    g_local[7] = SECP256K1_G8;

    // global to local
    k_local[0] = k[0];
    k_local[1] = k[1];
    k_local[2] = k[2];
    k_local[3] = k[3];
    k_local[4] = k[4];
    k_local[5] = k[5];
    k_local[6] = k[6];
    k_local[7] = k[7];

    k_local[7] = 0x68e23530;
    k_local[6] = 0xdeb6d501;
    k_local[5] = 0x1ab56d8a;
    k_local[4] = 0xd9f7b4a3;
    k_local[3] = 0xb424f111;
    k_local[2] = 0x2f086063;
    k_local[1] = 0x57497495;
    k_local[0] = 0x929f72dc;

    const u32 first_byte = SECP256K1_G0 & 0xff;
    transform_public(&g_xy_local, g_local, first_byte);
    point_mul(r_local, k_local, &g_xy_local);

    // local to global
    r[0] = r_local[0];
    r[1] = r_local[1];
    r[2] = r_local[2];
    r[3] = r_local[3];
    r[4] = r_local[4];
    r[5] = r_local[5];
    r[6] = r_local[6];
    r[7] = r_local[7];
    r[8] = r_local[8];
}

__kernel void test_convert_to_window_naf(__global u32 *wnaf_global, __global u32 *loop_start_global, __global const u32 *k_global)
{
    u32 wnaf_local[SECP256K1_NAF_SIZE];
    u32 k_local[PRIVATE_KEY_LENGTH];

    // global to local
    for(int i=0; i < PRIVATE_KEY_LENGTH; i++) {
        k_local[i] = k_global[i];
    }

    int loop_start_local = convert_to_window_naf(wnaf_local, k_local);

    // local to global
    loop_start_global[0] = loop_start_local;

    for(int i=0; i < SECP256K1_NAF_SIZE; i++) {
        wnaf_global[i] = wnaf_local[i];
    }
}

__kernel void test_parse_public_g(__global u32 *xy_global)
{
    u32 g_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    secp256k1_t xy_pre_computed_local;

    g_local[0] = SECP256K1_G0;
    g_local[1] = SECP256K1_G1;
    g_local[2] = SECP256K1_G2;
    g_local[3] = SECP256K1_G3;
    g_local[4] = SECP256K1_G4;
    g_local[5] = SECP256K1_G5;
    g_local[6] = SECP256K1_G6;
    g_local[7] = SECP256K1_G7;
    g_local[8] = SECP256K1_G8;

    parse_public(&xy_pre_computed_local, g_local);

    for(int i=0; i < SECP256K1_PRE_COMPUTED_XY_SIZE; i++) {
        xy_global[i] = xy_pre_computed_local.xy[i];
    }
}

__kernel void test_parse_public(__global u32 *xy_global, __global const u32 *public_address_global)
{
    u32 public_address_local[PUBLIC_KEY_LENGTH_WITH_PARITY];
    secp256k1_t xy_pre_computed_local;

    for(int i=0; i < PUBLIC_KEY_LENGTH_WITH_PARITY; i++) {
        public_address_local[i] = public_address_global[i];
    }

    /*
    g_local[0] = SECP256K1_G0;
    g_local[1] = SECP256K1_G1;
    g_local[2] = SECP256K1_G2;
    g_local[3] = SECP256K1_G3;
    g_local[4] = SECP256K1_G4;
    g_local[5] = SECP256K1_G5;
    g_local[6] = SECP256K1_G6;
    g_local[7] = SECP256K1_G7;
    g_local[8] = SECP256K1_G8;
    */

    parse_public(&xy_pre_computed_local, public_address_local);

    for(int i=0; i < SECP256K1_PRE_COMPUTED_XY_SIZE; i++) {
        xy_global[i] = xy_pre_computed_local.xy[i];
    }
}


new tests

new tests

kernel void label_with_id(global int *data, int w, int h) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int loc = w * y + x;
  if (data[loc] == 1) {
    data[loc] = loc + 2;
  }
}

kernel void neighbour_propagate(global int *data, int w, int h,
                                global char *changed) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int oldlabel = data[w * y + x];
  int curlabel = oldlabel;
  int otherlabel = 0;

  if (curlabel == 0) {
    return;
  }

  if (y + 1 < h) {
    otherlabel = data[w * (y + 1) + (x)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }
  if (y - 1 >= 0) {
    otherlabel = data[w * (y - 1) + (x)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }
  if (x + 1 < w) {
    otherlabel = data[w * (y) + (x + 1)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }
  if (x - 1 >= 0) {
    otherlabel = data[w * (y) + (x - 1)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }

  if (curlabel < oldlabel) {
    *changed = 1;
    data[w * y + x] = curlabel;
  }
}

kernel void plus_propagate(global int *data, int w, int h,
                           global char *changed) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int oldlabel = data[w * y + x];
  int curlabel = oldlabel;
  int otherlabel = 0;
  int diff;

  if (curlabel == 0) {
    return;
  }

  diff = 1;
  while (true) {
    if (y + diff < 0 || y + diff >= h) {
      break;
    }
    otherlabel = data[w * (y + diff) + (x)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }
  diff = 1;
  while (true) {
    if (y - diff < 0 || y - diff >= h) {
      break;
    }
    otherlabel = data[w * (y - diff) + (x)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }
  diff = 1;
  while (true) {
    if (x + diff < 0 || x + diff >= w) {
      break;
    }
    otherlabel = data[w * y + (x + diff)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }
  diff = 1;
  while (true) {
    if (x - diff < 0 || x - diff >= w) {
      break;
    }
    otherlabel = data[w * y + (x - diff)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }

  if (curlabel < oldlabel) {
    *changed = 1;
    data[w * y + x] = curlabel;
  }
}

int find_set(global int *data, int loc) {
  // All loc of found elements should be in range.
  // Also assuming there are no cycles in the links.
  while (loc != data[loc] - 2) {
    loc = data[loc] - 2;
  }

  // +2 is the correct LABEL of root at LOCATION loc
  return loc + 2;
}

kernel void union_find(global int *data, int w, int h, global char *changed) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int oldlabel = data[w * y + x];
  int lowest = oldlabel;

  if (oldlabel == 0) {
    return;
  }

  bool ok_N = y - 1 >= 0 && data[w * (y - 1) + (x)];
  bool ok_E = x + 1 < w && data[w * (y) + (x + 1)];
  bool ok_S = y + 1 < h && data[w * (y + 1) + (x)];
  bool ok_W = x - 1 >= 0 && data[w * (y) + (x - 1)];
  int root_N;
  int root_E;
  int root_S;
  int root_W;

  if (ok_N) {
    root_N = find_set(data, w * (y - 1) + (x));
    if (root_N < lowest) {
      lowest = root_N;
    }
  }
  if (ok_E) {
    root_E = find_set(data, w * (y) + (x + 1));
    if (root_E < lowest) {
      lowest = root_E;
    }
  }
  if (ok_S) {
    root_S = find_set(data, w * (y + 1) + (x));
    if (root_S < lowest) {
      lowest = root_S;
    }
  }
  if (ok_W) {
    root_W = find_set(data, w * (y) + (x - 1));
    if (root_W < lowest) {
      lowest = root_W;
    }
  }

  if (lowest < oldlabel) {
    *changed = 1;
    data[w * y + x] = lowest;
    if (ok_N && root_N > lowest) {
      data[root_N - 2] = lowest;
    }
    if (ok_E && root_E > lowest) {
      data[root_E - 2] = lowest;
    }
    if (ok_S && root_S > lowest) {
      data[root_S - 2] = lowest;
    }
    if (ok_W && root_W > lowest) {
      data[root_W - 2] = lowest;
    }
  }
}

kernel void lineedit_right(global int *data, int w, int h,
                           global char *changed) {
  int x = 0;
  int y = get_global_id(0);
  int lowest = 1 << 30;

  if (y >= h) {
    return;
  }

  while (x < w) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    ++x;
  }
}

kernel void lineedit_left(global int *data, int w, int h,
                          global char *changed) {
  int x = w - 1;
  int y = get_global_id(0);
  int lowest = 1 << 30;

  if (y >= h) {
    return;
  }

  while (x >= 0) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    --x;
  }
}

kernel void lineedit_up(global int *data, int w, int h, global char *changed) {
  int x = get_global_id(0);
  int y = 0;
  int lowest = 1 << 30;

  if (x >= w) {
    return;
  }

  while (y < h) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    ++y;
  }
}

kernel void lineedit_down(global int *data, int w, int h,
                          global char *changed) {
  int x = get_global_id(0);
  int y = h - 1;
  int lowest = 1 << 30;

  if (x >= w) {
    return;
  }

  while (y >= 0) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    --y;
  }
}

kernel void lines_up(global int *data, int w, int h, global char *changed) {
  int x = get_global_id(0);
  int y = 0;
  char localchanged = 0;

  if (x >= w) {
    return;
  }

  while (y < h) {
    if (!data[w * y + x]) {
      ++y;
      continue;
    }
    int i = y;
    int min = data[w * y + x];
    int tmpmin = min;

    while (i < h && (tmpmin = data[w * i + x])) {
      if (tmpmin != min) {
        localchanged = 1; // Not all equal, i.e. will have change
      }
      if (tmpmin < min) {
        min = tmpmin;
      }
      ++i;
    }

    while (y != i) {
      data[w * y + x] = min;
      ++y;
    }
  }

  if (localchanged) {
    *changed = localchanged;
  }
}

kernel void lines_right(global int *data, int w, int h, global char *changed) {
  int x = 0;
  int y = get_global_id(0);
  char localchanged = 0;

  if (y >= h) {
    return;
  }

  while (x < w) {
    if (!data[w * y + x]) {
      ++x;
      continue;
    }
    int i = x;
    int min = data[w * y + x];
    int tmpmin = min;

    while (i < w && (tmpmin = data[w * y + i])) {
      if (tmpmin != min) {
        localchanged = 1; // Not all equal, i.e. will have change
      }
      if (tmpmin < min) {
        min = tmpmin;
      }
      ++i;
    }

    while (x != i) {
      data[w * y + x] = min;
      ++x;
    }
  }

  if (localchanged) {
    *changed = localchanged;
  }
}

kernel void id_accessor(global int *data, int w) {
  unsigned int x = get_global_id(0);
  unsigned int y = get_global_id(1);

  int loc = w * y + x;
  data[loc] = data[loc];
}

// Can't allocate if not known at compile-time anyway
#define lw 32
#define lh 8

kernel void solve_locally_nprop(global int *data, int w, int h) {
  int lx = get_local_id(0);
  int ly = get_local_id(1);
  int x = get_global_id(0);
  int y = get_global_id(1);

  char valid = 1;
  local int buffer[lw * lh];
  local char changed;

  if (y >= h || x >= w) {
    valid = 0;
  }
  buffer[lw * ly + lx] = valid ? data[w * y + x] : 0;
  changed = 1;

  while (changed) {
    barrier(CLK_LOCAL_MEM_FENCE);
    changed = 0;
    barrier(CLK_LOCAL_MEM_FENCE);

    if (valid) {
      int min = 1 << 30;
      int tmp;
      if (lx > 0) {
        tmp = buffer[lw * (ly) + (lx - 1)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (lx < lw - 1) {
        tmp = buffer[lw * (ly) + (lx + 1)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (ly > 0) {
        tmp = buffer[lw * (ly - 1) + (lx)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (ly < lh - 1) {
        tmp = buffer[lw * (ly + 1) + (lx)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (min < buffer[lw * ly + lx]) {
        changed = 1;
        buffer[lw * ly + lx] = min;
      }
    }

    barrier(CLK_LOCAL_MEM_FENCE);
  }

  if (valid) {
    data[w * y + x] = buffer[lw * ly + lx];
  }
}

kernel void solve_locally_plus(global int *data, int w, int h) {
  int lx = get_local_id(0);
  int ly = get_local_id(1);
  int x = get_global_id(0);
  int y = get_global_id(1);

  char valid = 1;
  int diff;
  local int buffer[lw * lh];
  local char changed;

  if (y >= h || x >= w) {
    valid = 0;
  }
  buffer[lw * ly + lx] = valid ? data[w * y + x] : 0;
  changed = 1;

  while (changed) {
    barrier(CLK_LOCAL_MEM_FENCE);
    changed = 0;
    barrier(CLK_LOCAL_MEM_FENCE);

    if (valid) {
      int min = 1 << 30;
      int tmp;

      diff = 1;
      while (lx - diff >= 0) {
        tmp = buffer[lw * (ly) + (lx - diff)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }

      diff = 1;
      while (lx + diff < lw) {
        tmp = buffer[lw * (ly) + (lx + diff)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }

      diff = 1;
      while (ly - diff >= 0) {
        tmp = buffer[lw * (ly - diff) + (lx)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }

      diff = 1;
      while (ly + diff < lh) {
        tmp = buffer[lw * (ly + diff) + (lx)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }
      if (min < buffer[lw * ly + lx]) {
        changed = 1;
        buffer[lw * ly + lx] = min;
      }
    }

    barrier(CLK_LOCAL_MEM_FENCE);
  }

  if (valid) {
    data[w * y + x] = buffer[lw * ly + lx];
  }
}

#define BUFFS 512

#define NORTH (w * (y - 1) + (x))
#define EAST (w * (y) + (x + 1))
#define SOUTH (w * (y + 1) + (x))
#define WEST (w * (y) + (x - 1))
#define CENTER (w * y + x)

#define OK_NORTH (y > 0)
#define OK_EAST (x < w - 1)
#define OK_SOUTH (y < h - 1)
#define OK_WEST (x > 0)
#define VALID (x < w && y < h)

kernel void recursively_win(global int *data, int w, int h,
                            global char *changed) {
  int x, y;
  int lx = get_local_id(0);
  int ly = get_local_id(1);
  int tmp, thistmp;
  char eligible;

  local int lowest[1];
  local int stack_x[BUFFS];
  local int stack_y[BUFFS];
  local int stack_ptr[1];
  int own_pointer;

  while (1) {
    x = get_global_id(0);
    y = get_global_id(1);
    eligible = 0;

    if (lx == 0 && ly == 0) {
      *lowest = 1 << 30;
      *stack_ptr = 0;
    }

    // ELIGIBILITY PHASE
    // Only pick something as the label to handle if
    // values around it can be reduced to it
    barrier(CLK_LOCAL_MEM_FENCE);

    if (VALID && (thistmp = data[CENTER])) {
      if (OK_NORTH && data[NORTH] > thistmp) {
        eligible = 1;
      }
      if (OK_EAST && data[EAST] > thistmp) {
        eligible = 1;
      }
      if (OK_SOUTH && data[SOUTH] > thistmp) {
        eligible = 1;
      }
      if (OK_WEST && data[WEST] > thistmp) {
        eligible = 1;
      }

      if (eligible) {
        atomic_min(lowest, thistmp);
      }
    }

    barrier(CLK_LOCAL_MEM_FENCE);
    if (*lowest == 1 << 30) {
      // Found no label inside this region that can be improved upon
      return;
    } else if (lx == 0 && ly == 0) {
      // Found an improvement, so a change will be had
      *changed = 1;
    }

    // FIRST PUSH PHASE
    if (VALID && thistmp == *lowest) {

      if (OK_NORTH) {
        if (data[NORTH] > thistmp) {
          data[NORTH] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x;
            stack_y[own_pointer] = y - 1;
          }
        }
      }
      if (OK_EAST) {
        if (data[EAST] > thistmp) {
          data[EAST] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x + 1;
            stack_y[own_pointer] = y;
          }
        }
      }
      if (OK_SOUTH) {
        if (data[SOUTH] > thistmp) {
          data[SOUTH] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x;
            stack_y[own_pointer] = y + 1;
          }
        }
      }
      if (OK_WEST) {
        if (data[WEST] > thistmp) {
          data[WEST] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x - 1;
            stack_y[own_pointer] = y;
          }
        }
      }
    }

    thistmp = *lowest; // For unlucky threads to participate

    if (lx == 0 && ly == 0 && thistmp == 0) {
      *changed = 0;
      return;
    }
    while (1) {
      // Test-if-there's-work-at-all phase
      barrier(CLK_LOCAL_MEM_FENCE);
      if (*stack_ptr == 0) {
        break;
      }

      // POP PHASE
      barrier(CLK_LOCAL_MEM_FENCE);
      own_pointer = atomic_dec(stack_ptr) - 1;
      if (own_pointer < 0) {
        atomic_inc(stack_ptr);
      } else {
        x = stack_x[own_pointer];
        y = stack_y[own_pointer];
      }

      // PUSH PHASE
      barrier(CLK_LOCAL_MEM_FENCE);

      if (own_pointer >= 0) {
        // Not trash in x, y

        if (OK_NORTH) {
          if (data[NORTH] > thistmp) {
            data[NORTH] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x;
              stack_y[own_pointer] = y - 1;
            }
          }
        }
        if (OK_EAST) {
          if (data[EAST] > thistmp) {
            data[EAST] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x + 1;
              stack_y[own_pointer] = y;
            }
          }
        }
        if (OK_SOUTH) {
          if (data[SOUTH] > thistmp) {
            data[SOUTH] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x;
              stack_y[own_pointer] = y + 1;
            }
          }
        }
        if (OK_WEST) {
          if (data[WEST] > thistmp) {
            data[WEST] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x - 1;
              stack_y[own_pointer] = y;
            }
          }
        }
      }
    }
  }
}

kernel void label_with_id(global int *data, int w, int h) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int loc = w * y + x;
  if (data[loc] == 1) {
    data[loc] = loc + 2;
  }
}

kernel void neighbour_propagate(global int *data, int w, int h,
                                global char *changed) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int oldlabel = data[w * y + x];
  int curlabel = oldlabel;
  int otherlabel = 0;

  if (curlabel == 0) {
    return;
  }

  if (y + 1 < h) {
    otherlabel = data[w * (y + 1) + (x)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }
  if (y - 1 >= 0) {
    otherlabel = data[w * (y - 1) + (x)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }
  if (x + 1 < w) {
    otherlabel = data[w * (y) + (x + 1)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }
  if (x - 1 >= 0) {
    otherlabel = data[w * (y) + (x - 1)];
    if (otherlabel && otherlabel < curlabel) {
      curlabel = otherlabel;
    }
  }

  if (curlabel < oldlabel) {
    *changed = 1;
    data[w * y + x] = curlabel;
  }
}

kernel void plus_propagate(global int *data, int w, int h,
                           global char *changed) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int oldlabel = data[w * y + x];
  int curlabel = oldlabel;
  int otherlabel = 0;
  int diff;

  if (curlabel == 0) {
    return;
  }

  diff = 1;
  while (true) {
    if (y + diff < 0 || y + diff >= h) {
      break;
    }
    otherlabel = data[w * (y + diff) + (x)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }
  diff = 1;
  while (true) {
    if (y - diff < 0 || y - diff >= h) {
      break;
    }
    otherlabel = data[w * (y - diff) + (x)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }
  diff = 1;
  while (true) {
    if (x + diff < 0 || x + diff >= w) {
      break;
    }
    otherlabel = data[w * y + (x + diff)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }
  diff = 1;
  while (true) {
    if (x - diff < 0 || x - diff >= w) {
      break;
    }
    otherlabel = data[w * y + (x - diff)];
    if (otherlabel == 0) {
      break;
    }
    if (otherlabel < curlabel) {
      curlabel = otherlabel;
    }
    ++diff;
  }

  if (curlabel < oldlabel) {
    *changed = 1;
    data[w * y + x] = curlabel;
  }
}

int find_set(global int *data, int loc) {
  // All loc of found elements should be in range.
  // Also assuming there are no cycles in the links.
  while (loc != data[loc] - 2) {
    loc = data[loc] - 2;
  }

  // +2 is the correct LABEL of root at LOCATION loc
  return loc + 2;
}

kernel void union_find(global int *data, int w, int h, global char *changed) {
  int x = get_global_id(0);
  int y = get_global_id(1);
  if (x >= w || y >= h) {
    return;
  }

  int oldlabel = data[w * y + x];
  int lowest = oldlabel;

  if (oldlabel == 0) {
    return;
  }

  bool ok_N = y - 1 >= 0 && data[w * (y - 1) + (x)];
  bool ok_E = x + 1 < w && data[w * (y) + (x + 1)];
  bool ok_S = y + 1 < h && data[w * (y + 1) + (x)];
  bool ok_W = x - 1 >= 0 && data[w * (y) + (x - 1)];
  int root_N;
  int root_E;
  int root_S;
  int root_W;

  if (ok_N) {
    root_N = find_set(data, w * (y - 1) + (x));
    if (root_N < lowest) {
      lowest = root_N;
    }
  }
  if (ok_E) {
    root_E = find_set(data, w * (y) + (x + 1));
    if (root_E < lowest) {
      lowest = root_E;
    }
  }
  if (ok_S) {
    root_S = find_set(data, w * (y + 1) + (x));
    if (root_S < lowest) {
      lowest = root_S;
    }
  }
  if (ok_W) {
    root_W = find_set(data, w * (y) + (x - 1));
    if (root_W < lowest) {
      lowest = root_W;
    }
  }

  if (lowest < oldlabel) {
    *changed = 1;
    data[w * y + x] = lowest;
    if (ok_N && root_N > lowest) {
      data[root_N - 2] = lowest;
    }
    if (ok_E && root_E > lowest) {
      data[root_E - 2] = lowest;
    }
    if (ok_S && root_S > lowest) {
      data[root_S - 2] = lowest;
    }
    if (ok_W && root_W > lowest) {
      data[root_W - 2] = lowest;
    }
  }
}

kernel void lineedit_right(global int *data, int w, int h,
                           global char *changed) {
  int x = 0;
  int y = get_global_id(0);
  int lowest = 1 << 30;

  if (y >= h) {
    return;
  }

  while (x < w) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    ++x;
  }
}

kernel void lineedit_left(global int *data, int w, int h,
                          global char *changed) {
  int x = w - 1;
  int y = get_global_id(0);
  int lowest = 1 << 30;

  if (y >= h) {
    return;
  }

  while (x >= 0) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    --x;
  }
}

kernel void lineedit_up(global int *data, int w, int h, global char *changed) {
  int x = get_global_id(0);
  int y = 0;
  int lowest = 1 << 30;

  if (x >= w) {
    return;
  }

  while (y < h) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    ++y;
  }
}

kernel void lineedit_down(global int *data, int w, int h,
                          global char *changed) {
  int x = get_global_id(0);
  int y = h - 1;
  int lowest = 1 << 30;

  if (x >= w) {
    return;
  }

  while (y >= 0) {
    int curlabel = data[w * y + x];

    if (curlabel == 0) {
      lowest = 1 << 30;
    } else {
      if (curlabel < lowest) {
        lowest = curlabel;
      } else if (curlabel > lowest) {
        data[w * y + x] = lowest;
        *changed = 1;
      }
    }

    --y;
  }
}

kernel void lines_up(global int *data, int w, int h, global char *changed) {
  int x = get_global_id(0);
  int y = 0;
  char localchanged = 0;

  if (x >= w) {
    return;
  }

  while (y < h) {
    if (!data[w * y + x]) {
      ++y;
      continue;
    }
    int i = y;
    int min = data[w * y + x];
    int tmpmin = min;

    while (i < h && (tmpmin = data[w * i + x])) {
      if (tmpmin != min) {
        localchanged = 1; // Not all equal, i.e. will have change
      }
      if (tmpmin < min) {
        min = tmpmin;
      }
      ++i;
    }

    while (y != i) {
      data[w * y + x] = min;
      ++y;
    }
  }

  if (localchanged) {
    *changed = localchanged;
  }
}

kernel void lines_right(global int *data, int w, int h, global char *changed) {
  int x = 0;
  int y = get_global_id(0);
  char localchanged = 0;

  if (y >= h) {
    return;
  }

  while (x < w) {
    if (!data[w * y + x]) {
      ++x;
      continue;
    }
    int i = x;
    int min = data[w * y + x];
    int tmpmin = min;

    while (i < w && (tmpmin = data[w * y + i])) {
      if (tmpmin != min) {
        localchanged = 1; // Not all equal, i.e. will have change
      }
      if (tmpmin < min) {
        min = tmpmin;
      }
      ++i;
    }

    while (x != i) {
      data[w * y + x] = min;
      ++x;
    }
  }

  if (localchanged) {
    *changed = localchanged;
  }
}

kernel void id_accessor(global int *data, int w) {
  unsigned int x = get_global_id(0);
  unsigned int y = get_global_id(1);

  int loc = w * y + x;
  data[loc] = data[loc];
}

// Can't allocate if not known at compile-time anyway
#define lw 16
#define lh 8

kernel void solve_locally_nprop(global int *data, int w, int h) {
  int lx = get_local_id(0);
  int ly = get_local_id(1);
  int x = get_global_id(0);
  int y = get_global_id(1);

  char valid = 1;
  local int buffer[lw * lh];
  local char changed;

  if (y >= h || x >= w) {
    valid = 0;
  }
  buffer[lw * ly + lx] = valid ? data[w * y + x] : 0;
  changed = 1;

  while (changed) {
    barrier(CLK_LOCAL_MEM_FENCE);
    changed = 0;
    barrier(CLK_LOCAL_MEM_FENCE);

    if (valid) {
      int min = 1 << 30;
      int tmp;
      if (lx > 0) {
        tmp = buffer[lw * (ly) + (lx - 1)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (lx < lw - 1) {
        tmp = buffer[lw * (ly) + (lx + 1)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (ly > 0) {
        tmp = buffer[lw * (ly - 1) + (lx)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (ly < lh - 1) {
        tmp = buffer[lw * (ly + 1) + (lx)];
        if (tmp && tmp < min) {
          min = tmp;
        }
      }
      if (min < buffer[lw * ly + lx]) {
        changed = 1;
        buffer[lw * ly + lx] = min;
      }
    }

    barrier(CLK_LOCAL_MEM_FENCE);
  }

  if (valid) {
    data[w * y + x] = buffer[lw * ly + lx];
  }
}

kernel void solve_locally_plus(global int *data, int w, int h) {
  int lx = get_local_id(0);
  int ly = get_local_id(1);
  int x = get_global_id(0);
  int y = get_global_id(1);

  char valid = 1;
  int diff;
  local int buffer[lw * lh];
  local char changed;

  if (y >= h || x >= w) {
    valid = 0;
  }
  buffer[lw * ly + lx] = valid ? data[w * y + x] : 0;
  changed = 1;

  while (changed) {
    barrier(CLK_LOCAL_MEM_FENCE);
    changed = 0;
    barrier(CLK_LOCAL_MEM_FENCE);

    if (valid) {
      int min = 1 << 30;
      int tmp;

      diff = 1;
      while (lx - diff >= 0) {
        tmp = buffer[lw * (ly) + (lx - diff)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }

      diff = 1;
      while (lx + diff < lw) {
        tmp = buffer[lw * (ly) + (lx + diff)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }

      diff = 1;
      while (ly - diff >= 0) {
        tmp = buffer[lw * (ly - diff) + (lx)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }

      diff = 1;
      while (ly + diff < lh) {
        tmp = buffer[lw * (ly + diff) + (lx)];
        if (!tmp) {
          break;
        }
        if (tmp < min) {
          min = tmp;
        }
        ++diff;
      }
      if (min < buffer[lw * ly + lx]) {
        changed = 1;
        buffer[lw * ly + lx] = min;
      }
    }

    barrier(CLK_LOCAL_MEM_FENCE);
  }

  if (valid) {
    data[w * y + x] = buffer[lw * ly + lx];
  }
}

#define BUFFS 512

#define NORTH (w * (y - 1) + (x))
#define EAST (w * (y) + (x + 1))
#define SOUTH (w * (y + 1) + (x))
#define WEST (w * (y) + (x - 1))
#define CENTER (w * y + x)

#define OK_NORTH (y > 0)
#define OK_EAST (x < w - 1)
#define OK_SOUTH (y < h - 1)
#define OK_WEST (x > 0)
#define VALID (x < w && y < h)

kernel void recursively_win(global int *data, int w, int h,
                            global char *changed) {
  int x, y;
  int lx = get_local_id(0);
  int ly = get_local_id(1);
  int tmp, thistmp;
  char eligible;

  local int lowest[1];
  local int stack_x[BUFFS];
  local int stack_y[BUFFS];
  local int stack_ptr[1];
  int own_pointer;

  while (1) {
    x = get_global_id(0);
    y = get_global_id(1);
    eligible = 0;

    if (lx == 0 && ly == 0) {
      *lowest = 1 << 30;
      *stack_ptr = 0;
    }

    // ELIGIBILITY PHASE
    // Only pick something as the label to handle if
    // values around it can be reduced to it
    barrier(CLK_LOCAL_MEM_FENCE);

    if (VALID && (thistmp = data[CENTER])) {
      if (OK_NORTH && data[NORTH] > thistmp) {
        eligible = 1;
      }
      if (OK_EAST && data[EAST] > thistmp) {
        eligible = 1;
      }
      if (OK_SOUTH && data[SOUTH] > thistmp) {
        eligible = 1;
      }
      if (OK_WEST && data[WEST] > thistmp) {
        eligible = 1;
      }

      if (eligible) {
        atomic_min(lowest, thistmp);
      }
    }

    barrier(CLK_LOCAL_MEM_FENCE);
    if (*lowest == 1 << 30) {
      // Found no label inside this region that can be improved upon
      return;
    } else if (lx == 0 && ly == 0) {
      // Found an improvement, so a change will be had
      *changed = 1;
    }

    // FIRST PUSH PHASE
    if (VALID && thistmp == *lowest) {

      if (OK_NORTH) {
        if (data[NORTH] > thistmp) {
          data[NORTH] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x;
            stack_y[own_pointer] = y - 1;
          }
        }
      }
      if (OK_EAST) {
        if (data[EAST] > thistmp) {
          data[EAST] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x + 1;
            stack_y[own_pointer] = y;
          }
        }
      }
      if (OK_SOUTH) {
        if (data[SOUTH] > thistmp) {
          data[SOUTH] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x;
            stack_y[own_pointer] = y + 1;
          }
        }
      }
      if (OK_WEST) {
        if (data[WEST] > thistmp) {
          data[WEST] = thistmp;
          own_pointer = atomic_inc(stack_ptr);
          if (own_pointer >= BUFFS) {
            atomic_dec(stack_ptr);
          } else {
            stack_x[own_pointer] = x - 1;
            stack_y[own_pointer] = y;
          }
        }
      }
    }

    thistmp = *lowest; // For unlucky threads to participate

    if (lx == 0 && ly == 0 && thistmp == 0) {
      *changed = 0;
      return;
    }
    while (1) {
      // Test-if-there's-work-at-all phase
      barrier(CLK_LOCAL_MEM_FENCE);
      if (*stack_ptr == 0) {
        break;
      }

      // POP PHASE
      barrier(CLK_LOCAL_MEM_FENCE);
      own_pointer = atomic_dec(stack_ptr) - 1;
      if (own_pointer < 0) {
        atomic_inc(stack_ptr);
      } else {
        x = stack_x[own_pointer];
        y = stack_y[own_pointer];
      }

      // PUSH PHASE
      barrier(CLK_LOCAL_MEM_FENCE);

      if (own_pointer >= 0) {
        // Not trash in x, y

        if (OK_NORTH) {
          if (data[NORTH] > thistmp) {
            data[NORTH] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x;
              stack_y[own_pointer] = y - 1;
            }
          }
        }
        if (OK_EAST) {
          if (data[EAST] > thistmp) {
            data[EAST] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x + 1;
              stack_y[own_pointer] = y;
            }
          }
        }
        if (OK_SOUTH) {
          if (data[SOUTH] > thistmp) {
            data[SOUTH] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x;
              stack_y[own_pointer] = y + 1;
            }
          }
        }
        if (OK_WEST) {
          if (data[WEST] > thistmp) {
            data[WEST] = thistmp;
            own_pointer = atomic_inc(stack_ptr);
            if (own_pointer >= BUFFS) {
              atomic_dec(stack_ptr);
            } else {
              stack_x[own_pointer] = x - 1;
              stack_y[own_pointer] = y;
            }
          }
        }
      }
    }
  }
}