Performance improvement to MLOpenConvDirUniC kernel

1. Avoid FP division by 1.
2. Simplify arithmetic if divisor is a power of two
3. Use uniform wave_id with LC
4. Placed __restrict modifier on pointer arguments.
5. Changed from int to uint types. This really better represents the range used,
   while allows compiler to omit overflow checks.

/*
 * Copyright (c) 2016 AMD Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 */

#define _FLOAT					float
#define _FLOAT2					float2
#define _FLOAT4					float4
#define _FLOAT8					float8

#ifndef FLT_MAX
#define FLT_MAX         3.402823466e+38F        /* max value */
#endif

#define MLO_FILTER_SZ (MLO_FILTER_SIZE1*MLO_FILTER_SIZE0)

#define MLO_GRP_SZ0  (MLO_GRP_TILE0*MLO_GRP_TILE1)
#define MLO_GRP_SZ1 1
#define MLO_GRP_SZ2 1
#define MLO_GRP_SZ (MLO_GRP_SZ0*MLO_GRP_SZ1*MLO_GRP_SZ2)
#define MLO_N_PROC_WAVES ((MLO_GRP_SZ + MLO_N_READ_PROCS - 1)/MLO_N_READ_PROCS)
#define MLO_OUT_TILE_SZ (MLO_OUT_PIX_TILE1*MLO_OUT_PIX_TILE0)
#define MLO_ALU_TILE_SZ (MLO_ALU_VTILE1*MLO_ALU_VTILE0)

#if MLO_IN_TILE0 < MLO_OUT_WIDTH || MLO_IN_TILE1 < MLO_OUT_HEIGHT
#define MLO_LARGE_MAP 1
#else
#define MLO_LARGE_MAP 0
#endif

#if (MLO_IN_WIDTH == MLO_OUT_WIDTH && (MLO_IN_WIDTH / MLO_IN_TILE0 ) * MLO_IN_TILE0 == MLO_IN_WIDTH && MLO_IN_HEIGHT == MLO_OUT_HEIGHT && (MLO_IN_HEIGHT / MLO_IN_TILE1 ) * MLO_IN_TILE1 == MLO_IN_HEIGHT)
#define MLO_OUT_ALIGNED 1
#else
#define MLO_OUT_ALIGNED 0
#endif

#define MLO_ALUTILES_STACK_SZ (MLO_N_ALUTILES_PERSTACK*MLO_ALU_TILE_SZ)
#define MLO_N_IN_TILES_TOTAL (MLO_N_IN_TILES_PERSTACK*MLO_N_STACKS)

#define MLO_N_OUT_TILE_BLOCKS0 ((MLO_OUT_WIDTH+MLO_IN_TILE0-1)/MLO_IN_TILE0)
#define MLO_N_OUT_TILE_BLOCKS1 ((MLO_OUT_HEIGHT+MLO_IN_TILE1-1)/MLO_IN_TILE1)
#define MLO_N_IN_PACKS  (MLO_N_INPUTS/MLO_N_IN_TILES_PERSTACK)

#define MLO_N_IN_READ (MLO_N_IN_PACKS*MLO_N_IN_TILES_PERSTACK)
#if MLO_N_IN_READ == MLO_N_INPUTS
#define MLO_INPUTS_ALIGNED 1
#else
#define MLO_INPUTS_ALIGNED 0
#endif

#define MLO_N_OUT_PACKS  (MLO_N_OUTPUTS/MLO_N_OUT_TILES_PERSTACK)
#if MLO_N_OUT_PACKS*MLO_N_OUT_TILES_PERSTACK == MLO_N_OUTPUTS && MLO_N_OUT_TILES_PERSTACK != MLO_N_OUTPUTS
#define MLO_OUTPUTS_ALIGNED 1
#else
#define MLO_OUTPUTS_ALIGNED 0
#endif

#define MLO_N_BATCH_PACKS (MLO_BATCH_SZ/MLO_N_STACKS)
#if MLO_N_BATCH_PACKS*MLO_N_STACKS == MLO_BATCH_SZ && MLO_N_STACKS != MLO_BATCH_SZ
#define MLO_BATCH_ALIGNED 1
#else
#define MLO_BATCH_ALIGNED 0
#endif

#define MLO_IN_LCL_WIDTH (MLO_IN_TILE0 + MLO_FILTER_SIZE0 - 1)  // here we use kernel size. it's important when padding == 0
#define MLO_IN_LCL_HEIGHT (MLO_IN_TILE1 + MLO_FILTER_SIZE1 - 1)
#define MLO_IN_LCL_TILE_SZ (MLO_IN_LCL_WIDTH*MLO_IN_LCL_HEIGHT)
#define MLO_IN_LCL_PERSTACK_SZ (MLO_IN_LCL_TILE_SZ*MLO_N_IN_TILES_PERSTACK)
#define MLO_IN_LCL_SZ (MLO_IN_LCL_PERSTACK_SZ*MLO_N_STACKS)

#define MLO_WEIGHTS_SZ (MLO_N_OUT_TILES_PERSTACK*MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ)

#define MLO_PVT_ACCUM_DATA_SZ (MLO_N_OUT_TILES * MLO_OUT_TILE_SZ)
#define MLO_PVT_IN_WIDTH (MLO_FILTER_SIZE0 + MLO_OUT_PIX_TILE0 - 1)
#define MLO_PVT_IN_HEIGHT (MLO_OUT_PIX_TILE1)

#define MLO_LCL_WEIGHTS 1

#if defined(__AMDGCN__)
extern uint __llvm_amdgcn_readfirstlane(uint) __asm("llvm.amdgcn.readfirstlane");
#define uniform(x) __llvm_amdgcn_readfirstlane(x)
#else
#define uniform(x) (x)
#endif

static inline void calculateXYPos(uint linPos, uint width, uint * __restrict x, uint * __restrict y)
{

	(*y) = (uint)((float)linPos * (1.0f / (float)width) + 0.00001f);

	(*x) = linPos - (*y) * width;
}

static inline uint calculateOffset(uint stride, uint x, uint y)
{
	uint ret = y * stride + x;
	return(ret);
}

static inline void readDataElem(uint linPos,__local _FLOAT *lcl_data, uint lcl_base, uint lcl_height, uint lcl_width, uint lcl_stride, uint lcl_y, uint lcl_x,
					 const __global _FLOAT * gbl_data, uint gbl_base, uint gbl_height, uint gbl_width, uint gbl_stride, uint gbl_y, uint gbl_x,
					 bool vis,
					 bool debug)
{
	uint x, y;
	calculateXYPos(linPos, lcl_width, &x, &y);
	uint g_x = x + gbl_x;
	uint g_y = y + gbl_y;
	uint gbl_off0 = calculateOffset(gbl_stride, g_x, g_y);
	uint gbl_off = gbl_off0 + gbl_base;

	uint l_x = x + lcl_x;
	uint l_y = y + lcl_y;
	uint lcl_off = lcl_base +
#if MLO_LARGE_MAP == 1
		linPos
#else
		mad24(l_y, lcl_stride, l_x);
#endif
	 ;

#if MLO_LARGE_MAP == 1
	 vis &= (g_x >= 0 && g_x < gbl_width && g_y >= 0 && g_y < gbl_height);
#endif
	 gbl_off = (vis) ? gbl_off : 0;
	 _FLOAT gbl_val = gbl_data[gbl_off];
	 gbl_val = (vis) ? gbl_val : 0;

	lcl_data[lcl_off] = gbl_val;

}

static inline void readData(uint lcl_id, uint size, uint lcl_p_stride, __local _FLOAT *lcl_data, uint lcl_base, uint lcl_height, uint lcl_width, uint lcl_stride, uint lcl_y, uint lcl_x,
					 const __global _FLOAT * gbl_data, uint gbl_base, uint gbl_height, uint gbl_width, uint gbl_stride, uint gbl_y, uint gbl_x,
					 bool vis,
					 bool debug
					 )
{

	for(uint i = lcl_id; i < size; i+= lcl_p_stride)
	{
		readDataElem(i, lcl_data, lcl_base, lcl_height, lcl_width, lcl_stride, lcl_y, lcl_x,
					 gbl_data, gbl_base, gbl_height, gbl_width, gbl_stride, gbl_y, gbl_x,
					 vis,
					 debug);
	}

}

static inline void loadData(uint lcl_id, uint lcl_p_stride,
					__local _FLOAT * lcl_data,
					uint lcl_off, uint lcl_size, uint lcl_height, uint lcl_width, uint lcl_stride, uint lcl_bot_y, uint lcl_bot_x,
					const __global _FLOAT * gbl_data,
					uint gbl_off, uint gbl_size, uint gbl_height, uint glb_width, uint gbl_stride, uint gbl_bot_y, uint gbl_bot_x,
					uint buf_block_ind, uint max_n_bufs, uint lcl_n_bufs,
					bool debug)
{

	for(uint c = 0; c < lcl_n_bufs;
		 ++c, lcl_off += lcl_size, gbl_off += gbl_size )
	{
		bool vis = (buf_block_ind + c <  max_n_bufs);
		readData(lcl_id, lcl_size, lcl_p_stride,
				 lcl_data, lcl_off, lcl_height, lcl_width, lcl_stride, lcl_bot_y, lcl_bot_x,
				 gbl_data, gbl_off, gbl_height, glb_width, gbl_stride, gbl_bot_y, gbl_bot_x,
				 vis,
				 (debug));
	}

}

static inline void Conv(uint o_map_base,
				uint in_stg_off,
				 _FLOAT * pvt_in_stage, __local _FLOAT * __restrict lcl_indata,
				 _FLOAT * pvt_wei_stage, __local _FLOAT * __restrict lcl_wei,
				 _FLOAT * pvt_accum
				 )
{
// convolution

		// over all inputs in stack
		uint in_stg_off1 = in_stg_off;
		for(uint i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_TILE_SZ)
		{
        // preload input
			uint wei_stg_base_off = mad24(o_map_base, (uint)(MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ), mul24(i_c,(uint)MLO_FILTER_SZ));
			uint in_stg_off2 = in_stg_off1;
			for(uint j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j, in_stg_off2+=MLO_IN_LCL_WIDTH
					)
			{
				for(uint i = 0; i < MLO_PVT_IN_WIDTH; ++i)
				{
					pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = lcl_indata[in_stg_off2 + i];
				}
			}

		// over filter rows
			for(uint k = 0; k < MLO_FILTER_SIZE1; ++k, in_stg_off2+=MLO_IN_LCL_WIDTH
			)
			{
				uint k_act = 0;
#if MLO_DIR_FORWARD==1
				k_act = k;
#else
// load filter in reverse order
				k_act = MLO_FILTER_SIZE1 - 1 - k;
#endif
		// load next input row
				for(uint i_pvt = 0; i_pvt < MLO_PVT_IN_WIDTH; ++i_pvt)
				{
					pvt_in_stage[(MLO_PVT_IN_HEIGHT-1)*MLO_PVT_IN_WIDTH + i_pvt] = lcl_indata[in_stg_off2 + i_pvt];
				}

		// over all outputs
				for(uint o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)
				{
					uint wei_stg_off = wei_stg_base_off + o_c * MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ + k_act * MLO_FILTER_SIZE0;
					for(uint i = 0; i < MLO_FILTER_SIZE0; ++i)
					{
						pvt_wei_stage[i] = lcl_wei[wei_stg_off + i];
					}

		// actual conv

					for( uint j = 0; j < MLO_OUT_PIX_TILE1; ++j)
					{
						for(uint i = 0; i < MLO_OUT_PIX_TILE0; ++i)
						{
							for(uint l = 0; l < MLO_FILTER_SIZE0; ++l)
							{

								uint l_act = 0;
#if MLO_DIR_FORWARD==1
								l_act = l;

#else
// in reverse horizontal and vertical orders
								l_act = MLO_FILTER_SIZE0 - 1 - l;

#endif

								pvt_accum[(o_c * MLO_OUT_PIX_TILE1 + j) * MLO_OUT_PIX_TILE0 + i]
									 += pvt_in_stage[j * MLO_PVT_IN_WIDTH + i + l] * pvt_wei_stage[l_act];

							}

						}
					}

				} // for(uint o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)

               // move data up
				for(uint j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j)
				{
					for(uint i = 0; i < MLO_PVT_IN_WIDTH; ++i)
					{
						pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = pvt_in_stage[(j+1)*MLO_PVT_IN_WIDTH + i];
					}
				}

//				mem_fence(CLK_LOCAL_MEM_FENCE);

			} // for(uint k = 0; k < MLO_FILER_SIZE1; ++k,in_stg_off2+=MLO_IN_LCL_WIDTH)

		} // for(uint i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_PERSTACK_SZ)

}

__attribute__((reqd_work_group_size(MLO_GRP_SZ0, MLO_GRP_SZ1, MLO_GRP_SZ2)))
__kernel void MLOpenConvUniC(
       const __global _FLOAT * __restrict in,
       const __global _FLOAT * __restrict weights,
#if MLO_CONV_BIAS
       const __global _FLOAT * __restrict bias,
#endif
	__global _FLOAT * __restrict out,
	_FLOAT padding_val
	   )
{
	__local _FLOAT lcl_indata[MLO_IN_LCL_SZ];
	__local _FLOAT lcl_wei[MLO_WEIGHTS_SZ];
	__private _FLOAT pvt_accum[MLO_PVT_ACCUM_DATA_SZ];
	__private _FLOAT pvt_in_stage[MLO_PVT_IN_HEIGHT * MLO_PVT_IN_WIDTH];
	__private _FLOAT pvt_wei_stage[MLO_FILTER_SIZE0];

	uint grp_id0 = get_group_id(0);
#if MLO_OUT_WIDTH == MLO_IN_TILE0
	uint y_tile_blk = grp_id0;
	uint x_tile_blk = 0;
#else
	uint y_tile_blk = (uint)((float)grp_id0 / (float) MLO_N_OUT_TILE_BLOCKS0 + 0.00001f);
	uint x_tile_blk = grp_id0 - mul24(y_tile_blk, (uint)MLO_N_OUT_TILE_BLOCKS0);
#endif
	uint o_pack = get_group_id(1); // block of outputs
	uint b_pack = get_group_id(2); // batch block

	uint lcl_id = get_local_id(0);
	uint stack = (uint)((float)lcl_id/(float)MLO_ALUTILES_STACK_SZ + 0.00001f);  // stack
	uint alu_stack_id = lcl_id - mul24(stack, (uint)MLO_ALUTILES_STACK_SZ);  // alu index in stack
// ALU plane inside stack
	uint alu_out_plane_id = (uint)((float)alu_stack_id / (float)MLO_ALU_TILE_SZ + 0.00001f);  // alu output plane index
	uint alu_out_id = alu_stack_id - mul24(alu_out_plane_id, (uint)MLO_ALU_TILE_SZ); // alu index inside an ALU output plane
// pos inside ALU tile
	uint alu_tl1 = (uint)((float)alu_out_id/(float)MLO_ALU_VTILE0 + 0.00001f);
	uint alu_tl0 = alu_out_id - mul24(alu_tl1, (uint)MLO_ALU_VTILE0);

	uint o_map_plane = o_pack * MLO_N_OUT_TILES_PERSTACK; // first output maps index per full ALU plane stack
	uint o_map_base = alu_out_plane_id*MLO_N_OUT_TILES;  // local output map offset
	uint o_map = o_map_plane + o_map_base; // output map index per ALU plane
	uint b_index = b_pack * MLO_N_STACKS;

#if MLO_N_READ_PROCS & (MLO_N_READ_PROCS - 1)
	uint wave_id = (uint)((float)lcl_id / (float)MLO_N_READ_PROCS + 0.00001f);
	uint wave_lcl_id = lcl_id - mul24(wave_id, (uint)MLO_N_READ_PROCS);
#else
	uint wave_id = (uint)((uint)lcl_id / MLO_N_READ_PROCS);
	uint wave_lcl_id = lcl_id & (MLO_N_READ_PROCS - 1);
#if MLO_N_READ_PROCS >= 64
        wave_id = uniform(wave_id);
#endif
#endif

	uint x_grp = x_tile_blk * MLO_IN_TILE0;
	uint y_grp = y_tile_blk * MLO_IN_TILE1;

// TO DO: scale
	uint x_in_grp = x_grp - MLO_FILTER_PAD0;
	uint y_in_grp = y_grp - MLO_FILTER_PAD1;

	uint x_in_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	uint y_in_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

// base offset to read data from local input data
	uint in_stg_off = stack*MLO_IN_LCL_PERSTACK_SZ + (y_in_lcl) * MLO_IN_LCL_WIDTH + x_in_lcl;

    uint in_off = b_index * MLO_IN_BATCH_STRIDE;

#if MLO_DIR_FORWARD==1
	uint wei_off = mul24(o_map_plane, (uint)(MLO_N_INPUTS * MLO_FILTER_SZ));
#else
	uint wei_off = mul24(o_map_plane,(uint)MLO_FILTER_SZ);
#endif

#if MLO_LARGE_MAP == 0
	for(uint i = lcl_id; i < MLO_IN_LCL_SZ;  i += MLO_GRP_SZ)
	{
		lcl_indata[i] = 0;
	}
#endif

	for(uint i = 0; i < MLO_PVT_ACCUM_DATA_SZ; ++i)
	{
		pvt_accum[i] = 0;
	}

	for(uint ic = 0; ic < MLO_N_INPUTS; ic += MLO_N_IN_TILES_PERSTACK, in_off += MLO_IN_CHANNEL_STRIDE*MLO_N_IN_TILES_PERSTACK,
				wei_off += MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ
#if MLO_DIR_FORWARD==0
							* MLO_N_OUTPUTS
#endif
	)
	{
		barrier(CLK_LOCAL_MEM_FENCE);

// small map has been read in full continiously into the lDS buffer within padded rect,
// padding has been done on initilization.
// large map calculates padding on the fly and fills it with 0.

#if 1 // all inputs

#if MLO_LARGE_MAP == 1
		uint in_lcl_off1 = 0;
		uint in_off1 = in_off;
		for(uint i_b = 0; i_b < MLO_N_STACKS; ++i_b, in_off1 += MLO_IN_BATCH_STRIDE, in_lcl_off1 += MLO_IN_LCL_PERSTACK_SZ)
		{
			bool vis = true;
#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

// over all inputs in stack
			uint in_off2 = in_off1;
			uint in_lcl_off2 = in_lcl_off1;
			for(uint i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_off2 += MLO_IN_CHANNEL_STRIDE, in_lcl_off2 += MLO_IN_LCL_TILE_SZ)
			{
#if MLO_INPUTS_ALIGNED == 0
				vis &= (ic + i_c < MLO_N_INPUTS);
#endif

				uint elem_id = lcl_id;
				uint lcl_p_stride = MLO_GRP_SZ0;
				uint lcl_base = 0;
				uint lcl_y = 0;
				uint lcl_x = 0;
				uint gbl_base = 0;

				readData(elem_id, (MLO_IN_LCL_HEIGHT * MLO_IN_LCL_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_LCL_HEIGHT, MLO_IN_LCL_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_in_grp, x_in_grp,
						vis,
						true
					 );
			}

		}
#else
		for(uint i = wave_id; i < MLO_N_IN_TILES_TOTAL;  i += MLO_N_PROC_WAVES)
		{
		//(MLO_N_STACKS * MLO_N_OUT_TILES_PERSTACK)
#if MLO_N_IN_TILES_PERSTACK & (MLO_N_IN_TILES_PERSTACK - 1)
			uint i_b = (uint)((float)i / (float)MLO_N_IN_TILES_PERSTACK + 0.00001f);
			uint i_c = i - mul24(i_b, (uint)MLO_N_IN_TILES_PERSTACK);
#else
			uint i_b = (uint)i / MLO_N_IN_TILES_PERSTACK;
			uint i_c = i & (MLO_N_IN_TILES_PERSTACK - 1);
#endif

			bool vis = true;

#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

#if MLO_INPUTS_ALIGNED == 0
			vis &= (ic + i_c < MLO_N_INPUTS);
#endif
			uint in_off2 = in_off + i_b * MLO_IN_BATCH_STRIDE + i_c * MLO_IN_CHANNEL_STRIDE;
			uint in_lcl_off2 = i_b * MLO_IN_LCL_PERSTACK_SZ + i_c * MLO_IN_LCL_TILE_SZ;

			uint elem_id = wave_lcl_id;
			uint lcl_p_stride = MLO_N_READ_PROCS;
			uint lcl_base = 0;
			uint lcl_y = MLO_FILTER_PAD1;
			uint lcl_x = MLO_FILTER_PAD0;
			uint gbl_base = 0;

			readData(elem_id, (MLO_IN_HEIGHT * MLO_IN_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_grp, x_grp,
						vis,
						true
					 );
		}
#endif

// read inputs and weights
// put weights into LDS

#if 1  // only weights

		for(uint i = lcl_id; i < MLO_WEIGHTS_SZ; i += MLO_GRP_SZ)
		{
#if MLO_DIR_FORWARD==1
// here is [tops][bottoms]
			uint lcl_o = (uint)((float)i / (float)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			uint gbl_i = i - mul24(lcl_o, (uint)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ));
			if((wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i) < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ))
				lcl_wei[i] = weights[wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i];
			else
				lcl_wei[i] = weights[0];
#else
// outputs are botoms(inputs))
// inputs are tops(outputs)

			uint lcl_o = (uint)((float)i/ (float)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			uint gbl_i = i - mul24(lcl_o, (uint)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ));
			uint lcl_c = (uint)((float)gbl_i/ (float)MLO_FILTER_SZ + 0.00001f);
			uint lcl_i = gbl_i - mul24(lcl_c, (uint)MLO_FILTER_SZ);

			uint lcl_we_off = mad24(mad24(lcl_c, (uint)MLO_N_IN_TILES_PERSTACK, lcl_o), (uint)MLO_FILTER_SZ, lcl_i);
			uint gbl_we_off = mad24(mad24(lcl_o, (uint)MLO_N_OUTPUTS, lcl_c), (uint)MLO_FILTER_SZ, wei_off + lcl_i);
			bool within_range = gbl_we_off < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ);
			gbl_we_off = (within_range) ? gbl_we_off : 0;
			_FLOAT wei = weights[gbl_we_off];
			wei = (within_range) ? wei : 0;
			lcl_wei[lcl_we_off]
				= wei;

#endif

		}

#endif

// over all batch stacks

#endif  // all input

		barrier(CLK_LOCAL_MEM_FENCE);

// convolution
#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
		if (lcl_id < MLO_ACTIVE_ALUS)
#endif
		Conv(o_map_base,
			in_stg_off,
			pvt_in_stage, lcl_indata,
			pvt_wei_stage, lcl_wei,
			pvt_accum
			);

//		barrier(CLK_LOCAL_MEM_FENCE);
	}

#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
	if (lcl_id >= MLO_ACTIVE_ALUS)
	{
		return;
	}
#endif
// write results out
	uint x_out_grp = x_grp;
	uint y_out_grp = y_grp;
	uint x_out_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	uint y_out_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

    uint out_off = (b_index + stack) * MLO_OUT_BATCH_STRIDE + o_map * MLO_OUT_CHANNEL_STRIDE + (y_out_grp + y_out_lcl) * MLO_OUT_STRIDE + x_out_grp + x_out_lcl;
// over all local stacks
#if MLO_BATCH_ALIGNED == 0
	if (b_index + stack < MLO_BATCH_SZ)
#endif
	{

// over all local outputs
		uint out_off1 = out_off;
		for(uint o = 0; o < MLO_N_OUT_TILES
						; ++o, out_off1 += MLO_OUT_CHANNEL_STRIDE
						)
		{
// over output tile
			_FLOAT  bias_val = 0;
#if MLO_CONV_BIAS
			bias_val = bias[o_map + o];
#endif
			uint out_off2 = out_off1;
			for( uint j = 0; j < MLO_OUT_PIX_TILE1; ++j, out_off2 += MLO_OUT_STRIDE)
			{
				for(uint i = 0; i < MLO_OUT_PIX_TILE0; ++i)
				{
					if ( true
#if 1 //MLO_OUT_ALIGNED == 0
					&& y_out_lcl + j < MLO_OUT_TILE1 && y_out_grp + y_out_lcl + j < MLO_OUT_HEIGHT &&  x_out_lcl + i < MLO_OUT_TILE0 && x_out_grp + x_out_lcl + i < MLO_OUT_WIDTH
#endif
#if MLO_OUTPUTS_ALIGNED == 0
						&& o_map + o < MLO_N_OUTPUTS
#endif
					)
					{
						out[out_off2 + i] = pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i] + bias_val;
#if 0
						if ( out_off2 + i == 1 /*y_out_grp + y_out_lcl + j == 2 && x_out_grp + x_out_lcl + i == 0*/)
						{
							printf("K:out: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d    %f %f %f\n",
								MLO_OUT_TILE1,
								MLO_OUT_TILE0,
								grp_id0,
								lcl_id,
								alu_out_plane_id,
								alu_out_id,
								b_index + stack,
								o,
								o_map,
								out_off,
								out_off1,
								out_off2,
								y_out_grp,
								y_out_lcl,
								x_out_grp,
								x_out_lcl,
								j,
								i,
								pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i],
								 bias_val,
								out[out_off2 + i]
								);
						}
#endif
					}

				}
			}

		}
	}

}

/*
 * Copyright (c) 2016 AMD Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 */

#define _FLOAT					float
#define _FLOAT2					float2
#define _FLOAT4					float4
#define _FLOAT8					float8

#ifndef FLT_MAX
#define FLT_MAX         3.402823466e+38F        /* max value */
#endif

#define MLO_FILTER_SZ (MLO_FILTER_SIZE1*MLO_FILTER_SIZE0)

#define MLO_GRP_SZ0  (MLO_GRP_TILE0*MLO_GRP_TILE1)
#define MLO_GRP_SZ1 1
#define MLO_GRP_SZ2 1
#define MLO_GRP_SZ (MLO_GRP_SZ0*MLO_GRP_SZ1*MLO_GRP_SZ2)
#define MLO_N_PROC_WAVES ((MLO_GRP_SZ + MLO_N_READ_PROCS - 1)/MLO_N_READ_PROCS)
#define MLO_OUT_TILE_SZ (MLO_OUT_PIX_TILE1*MLO_OUT_PIX_TILE0)
#define MLO_ALU_TILE_SZ (MLO_ALU_VTILE1*MLO_ALU_VTILE0)

#if MLO_IN_TILE0 < MLO_OUT_WIDTH || MLO_IN_TILE1 < MLO_OUT_HEIGHT
#define MLO_LARGE_MAP 1
#else
#define MLO_LARGE_MAP 0
#endif

#if (MLO_IN_WIDTH == MLO_OUT_WIDTH && (MLO_IN_WIDTH / MLO_IN_TILE0 ) * MLO_IN_TILE0 == MLO_IN_WIDTH && MLO_IN_HEIGHT == MLO_OUT_HEIGHT && (MLO_IN_HEIGHT / MLO_IN_TILE1 ) * MLO_IN_TILE1 == MLO_IN_HEIGHT)
#define MLO_OUT_ALIGNED 1
#else
#define MLO_OUT_ALIGNED 0
#endif

#define MLO_ALUTILES_STACK_SZ (MLO_N_ALUTILES_PERSTACK*MLO_ALU_TILE_SZ)
#define MLO_N_IN_TILES_TOTAL (MLO_N_IN_TILES_PERSTACK*MLO_N_STACKS)

#define MLO_N_OUT_TILE_BLOCKS0 ((MLO_OUT_WIDTH+MLO_IN_TILE0-1)/MLO_IN_TILE0)
#define MLO_N_OUT_TILE_BLOCKS1 ((MLO_OUT_HEIGHT+MLO_IN_TILE1-1)/MLO_IN_TILE1)
#define MLO_N_IN_PACKS  (MLO_N_INPUTS/MLO_N_IN_TILES_PERSTACK)

#define MLO_N_IN_READ (MLO_N_IN_PACKS*MLO_N_IN_TILES_PERSTACK)
#if MLO_N_IN_READ == MLO_N_INPUTS
#define MLO_INPUTS_ALIGNED 1
#else
#define MLO_INPUTS_ALIGNED 0
#endif

#define MLO_N_OUT_PACKS  (MLO_N_OUTPUTS/MLO_N_OUT_TILES_PERSTACK)
#if MLO_N_OUT_PACKS*MLO_N_OUT_TILES_PERSTACK == MLO_N_OUTPUTS && MLO_N_OUT_TILES_PERSTACK != MLO_N_OUTPUTS
#define MLO_OUTPUTS_ALIGNED 1
#else
#define MLO_OUTPUTS_ALIGNED 0
#endif

#define MLO_N_BATCH_PACKS (MLO_BATCH_SZ/MLO_N_STACKS)
#if MLO_N_BATCH_PACKS*MLO_N_STACKS == MLO_BATCH_SZ && MLO_N_STACKS != MLO_BATCH_SZ
#define MLO_BATCH_ALIGNED 1
#else
#define MLO_BATCH_ALIGNED 0
#endif

#define MLO_IN_LCL_WIDTH (MLO_IN_TILE0 + MLO_FILTER_SIZE0 - 1)  // here we use kernel size. it's important when padding == 0
#define MLO_IN_LCL_HEIGHT (MLO_IN_TILE1 + MLO_FILTER_SIZE1 - 1)
#define MLO_IN_LCL_TILE_SZ (MLO_IN_LCL_WIDTH*MLO_IN_LCL_HEIGHT)
#define MLO_IN_LCL_PERSTACK_SZ (MLO_IN_LCL_TILE_SZ*MLO_N_IN_TILES_PERSTACK)
#define MLO_IN_LCL_SZ (MLO_IN_LCL_PERSTACK_SZ*MLO_N_STACKS)

#define MLO_WEIGHTS_SZ (MLO_N_OUT_TILES_PERSTACK*MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ)

#define MLO_PVT_ACCUM_DATA_SZ (MLO_N_OUT_TILES * MLO_OUT_TILE_SZ)
#define MLO_PVT_IN_WIDTH (MLO_FILTER_SIZE0 + MLO_OUT_PIX_TILE0 - 1)
#define MLO_PVT_IN_HEIGHT (MLO_OUT_PIX_TILE1)

#define MLO_LCL_WEIGHTS 1

static inline void calculateXYPos(int linPos, int width, int *x, int *y)
{

	(*y) = (int)((float)linPos * (1.0f / (float)width) + 0.00001f);

	(*x) = linPos - (*y) * width;
}

static inline int calculateOffset(int stride, int x, int y)
{
	int ret = y * stride + x;
	return(ret);
}

static inline void readDataElem(int linPos,__local _FLOAT *lcl_data, int lcl_base, int lcl_height, int lcl_width, int lcl_stride, int lcl_y, int lcl_x,
					 const __global _FLOAT * gbl_data, int gbl_base, int gbl_height, int gbl_width, int gbl_stride, int gbl_y, int gbl_x,
					 bool vis,
					 bool debug)
{
	int x, y;
	calculateXYPos(linPos, lcl_width, &x, &y);
	int g_x = x + gbl_x;
	int g_y = y + gbl_y;
	int gbl_off0 = calculateOffset(gbl_stride, g_x, g_y);
	int gbl_off = gbl_off0 + gbl_base;

	int l_x = x + lcl_x;
	int l_y = y + lcl_y;
	int lcl_off = lcl_base +
#if MLO_LARGE_MAP == 1
		linPos
#else
		mad24(l_y, lcl_stride, l_x);
#endif
	 ;

#if MLO_LARGE_MAP == 1
	 vis &= (g_x >= 0 && g_x < gbl_width && g_y >= 0 && g_y < gbl_height);
#endif
	 gbl_off = (vis) ? gbl_off : 0;
	 _FLOAT gbl_val = gbl_data[gbl_off];
	 gbl_val = (vis) ? gbl_val : 0;

	lcl_data[lcl_off] = gbl_val;

}

static inline void readData(int lcl_id, int size, int lcl_p_stride, __local _FLOAT *lcl_data, int lcl_base, int lcl_height, int lcl_width, int lcl_stride, int lcl_y, int lcl_x,
					 const __global _FLOAT * gbl_data, int gbl_base, int gbl_height, int gbl_width, int gbl_stride, int gbl_y, int gbl_x,
					 bool vis,
					 bool debug
					 )
{

	for(int i = lcl_id; i < size; i+= lcl_p_stride)
	{
		readDataElem(i, lcl_data, lcl_base, lcl_height, lcl_width, lcl_stride, lcl_y, lcl_x,
					 gbl_data, gbl_base, gbl_height, gbl_width, gbl_stride, gbl_y, gbl_x,
					 vis,
					 debug);
	}

}

static inline void loadData(int lcl_id, int lcl_p_stride,
					__local _FLOAT * lcl_data,
					int lcl_off, int lcl_size, int lcl_height, int lcl_width, int lcl_stride, int lcl_bot_y, int lcl_bot_x,
					const __global _FLOAT * gbl_data,
					int gbl_off, int gbl_size, int gbl_height, int glb_width, int gbl_stride, int gbl_bot_y, int gbl_bot_x,
					int buf_block_ind, int max_n_bufs, int lcl_n_bufs,
					bool debug)
{

	for(int c = 0; c < lcl_n_bufs;
		 ++c, lcl_off += lcl_size, gbl_off += gbl_size )
	{
		bool vis = (buf_block_ind + c <  max_n_bufs);
		readData(lcl_id, lcl_size, lcl_p_stride,
				 lcl_data, lcl_off, lcl_height, lcl_width, lcl_stride, lcl_bot_y, lcl_bot_x,
				 gbl_data, gbl_off, gbl_height, glb_width, gbl_stride, gbl_bot_y, gbl_bot_x,
				 vis,
				 (debug));
	}

}

static inline void Conv(int o_map_base,
				int in_stg_off,
				 _FLOAT *pvt_in_stage, __local _FLOAT * lcl_indata,
				 _FLOAT *pvt_wei_stage, __local _FLOAT * lcl_wei,
				 _FLOAT *pvt_accum
				 )
{
// convolution

		// over all inputs in stack
		int in_stg_off1 = in_stg_off;
		for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_TILE_SZ)
		{
        // preload input
			int wei_stg_base_off = mad24(o_map_base, (int)(MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ), mul24(i_c,(int)MLO_FILTER_SZ));
			int in_stg_off2 = in_stg_off1;
			for(int j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j, in_stg_off2+=MLO_IN_LCL_WIDTH
					)
			{
				for(int i = 0; i < MLO_PVT_IN_WIDTH; ++i)
				{
					pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = lcl_indata[in_stg_off2 + i];
				}
			}

		// over filter rows
			for(int k = 0; k < MLO_FILTER_SIZE1; ++k, in_stg_off2+=MLO_IN_LCL_WIDTH
			)
			{
				int k_act = 0;
#if MLO_DIR_FORWARD==1
				k_act = k;
#else
// load filter in reverse order
				k_act = MLO_FILTER_SIZE1 - 1 - k;
#endif
		// load next input row
				for(int i_pvt = 0; i_pvt < MLO_PVT_IN_WIDTH; ++i_pvt)
				{
					pvt_in_stage[(MLO_PVT_IN_HEIGHT-1)*MLO_PVT_IN_WIDTH + i_pvt] = lcl_indata[in_stg_off2 + i_pvt];
				}

		// over all outputs
				for(int o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)
				{
					int wei_stg_off = wei_stg_base_off + o_c * MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ + k_act * MLO_FILTER_SIZE0;
					for(int i = 0; i < MLO_FILTER_SIZE0; ++i)
					{
						pvt_wei_stage[i] = lcl_wei[wei_stg_off + i];
					}

		// actual conv

					for( int j = 0; j < MLO_OUT_PIX_TILE1; ++j)
					{
						for(int i = 0; i < MLO_OUT_PIX_TILE0; ++i)
						{
							for(int l = 0; l < MLO_FILTER_SIZE0; ++l)
							{

								int l_act = 0;
#if MLO_DIR_FORWARD==1
								l_act = l;

#else
// in reverse horizontal and vertical orders
								l_act = MLO_FILTER_SIZE0 - 1 - l;

#endif

								pvt_accum[(o_c * MLO_OUT_PIX_TILE1 + j) * MLO_OUT_PIX_TILE0 + i]
									 += pvt_in_stage[j * MLO_PVT_IN_WIDTH + i + l] * pvt_wei_stage[l_act];

							}

						}
					}

				} // for(int o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)

               // move data up
				for(int j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j)
				{
					for(int i = 0; i < MLO_PVT_IN_WIDTH; ++i)
					{
						pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = pvt_in_stage[(j+1)*MLO_PVT_IN_WIDTH + i];
					}
				}

//				mem_fence(CLK_LOCAL_MEM_FENCE);

			} // for(int k = 0; k < MLO_FILER_SIZE1; ++k,in_stg_off2+=MLO_IN_LCL_WIDTH)

		} // for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_PERSTACK_SZ)

}

__attribute__((reqd_work_group_size(MLO_GRP_SZ0, MLO_GRP_SZ1, MLO_GRP_SZ2)))
__kernel void MLOpenConvUniC(
       const __global _FLOAT * in,
       const __global _FLOAT * weights,
#if MLO_CONV_BIAS
       const __global _FLOAT * bias,
#endif
 	  __global _FLOAT *out,
	   _FLOAT padding_val
	   )
{
	__local _FLOAT lcl_indata[MLO_IN_LCL_SZ];
	__local _FLOAT lcl_wei[MLO_WEIGHTS_SZ];
	__private _FLOAT pvt_accum[MLO_PVT_ACCUM_DATA_SZ];
	__private _FLOAT pvt_in_stage[MLO_PVT_IN_HEIGHT * MLO_PVT_IN_WIDTH];
	__private _FLOAT pvt_wei_stage[MLO_FILTER_SIZE0];

	int grp_id0 = get_group_id(0);
	int y_tile_blk = (int)((float)grp_id0 / (float) MLO_N_OUT_TILE_BLOCKS0 + 0.00001f);
	int x_tile_blk = grp_id0 - mul24(y_tile_blk, (int)MLO_N_OUT_TILE_BLOCKS0);
	int o_pack = get_group_id(1); // block of outputs
	int b_pack = get_group_id(2); // batch block

	int lcl_id = get_local_id(0);
	int stack = (int)((float)lcl_id/(float)MLO_ALUTILES_STACK_SZ + 0.00001f);  // stack
	int alu_stack_id = lcl_id - mul24(stack, (int)MLO_ALUTILES_STACK_SZ);  // alu index in stack
// ALU plane inside stack
	int alu_out_plane_id = (int)((float)alu_stack_id / (float)MLO_ALU_TILE_SZ + 0.00001f);  // alu output plane index
	int alu_out_id = alu_stack_id - mul24(alu_out_plane_id, (int)MLO_ALU_TILE_SZ); // alu index inside an ALU output plane
// pos inside ALU tile
	int alu_tl1 = (int)((float)alu_out_id/(float)MLO_ALU_VTILE0 + 0.00001f);
	int alu_tl0 = alu_out_id - mul24(alu_tl1, (int)MLO_ALU_VTILE0);

	int o_map_plane = o_pack * MLO_N_OUT_TILES_PERSTACK; // first output maps index per full ALU plane stack
	int o_map_base = alu_out_plane_id*MLO_N_OUT_TILES;  // local output map offset
	int o_map = o_map_plane + o_map_base; // output map index per ALU plane
	int b_index = b_pack * MLO_N_STACKS;

	int wave_id = (int)((float)lcl_id / (float)MLO_N_READ_PROCS + 0.00001f);
	int wave_lcl_id = lcl_id - mul24(wave_id, (int)MLO_N_READ_PROCS);

	int x_grp = x_tile_blk * MLO_IN_TILE0;
	int y_grp = y_tile_blk * MLO_IN_TILE1;

// TO DO: scale
	int x_in_grp = x_grp - MLO_FILTER_PAD0;
	int y_in_grp = y_grp - MLO_FILTER_PAD1;

	int x_in_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	int y_in_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

// base offset to read data from local input data
	int in_stg_off = stack*MLO_IN_LCL_PERSTACK_SZ + (y_in_lcl) * MLO_IN_LCL_WIDTH + x_in_lcl;

    int in_off = b_index * MLO_IN_BATCH_STRIDE;

#if MLO_DIR_FORWARD==1
	int wei_off = mul24(o_map_plane, MLO_N_INPUTS * MLO_FILTER_SZ);
#else
	int wei_off = mul24(o_map_plane,MLO_FILTER_SZ);
#endif

#if MLO_LARGE_MAP == 0
	for(int i = lcl_id; i < MLO_IN_LCL_SZ;  i += MLO_GRP_SZ)
	{
		lcl_indata[i] = 0;
	}
#endif

	for(int i = 0; i < MLO_PVT_ACCUM_DATA_SZ; ++i)
	{
		pvt_accum[i] = 0;
	}

	for(int ic = 0; ic < MLO_N_INPUTS; ic += MLO_N_IN_TILES_PERSTACK, in_off += MLO_IN_CHANNEL_STRIDE*MLO_N_IN_TILES_PERSTACK,
				wei_off += MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ
#if MLO_DIR_FORWARD==0
							* MLO_N_OUTPUTS
#endif
	)
	{
		barrier(CLK_LOCAL_MEM_FENCE);

// small map has been read in full continiously into the lDS buffer within padded rect,
// padding has been done on initilization.
// large map calculates padding on the fly and fills it with 0.

#if 1 // all inputs

#if MLO_LARGE_MAP == 1
		int in_lcl_off1 = 0;
		int in_off1 = in_off;
		for(int i_b = 0; i_b < MLO_N_STACKS; ++i_b, in_off1 += MLO_IN_BATCH_STRIDE, in_lcl_off1 += MLO_IN_LCL_PERSTACK_SZ)
		{
			bool vis = true;
#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

// over all inputs in stack
			int in_off2 = in_off1;
			int in_lcl_off2 = in_lcl_off1;
			for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_off2 += MLO_IN_CHANNEL_STRIDE, in_lcl_off2 += MLO_IN_LCL_TILE_SZ)
			{
#if MLO_INPUTS_ALIGNED == 0
				vis &= (ic + i_c < MLO_N_INPUTS);
#endif

				int elem_id = lcl_id;
				int lcl_p_stride = MLO_GRP_SZ0;
				int lcl_base = 0;
				int lcl_y = 0;
				int lcl_x = 0;
				int gbl_base = 0;

				readData(elem_id, (MLO_IN_LCL_HEIGHT * MLO_IN_LCL_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_LCL_HEIGHT, MLO_IN_LCL_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_in_grp, x_in_grp,
						vis,
						true
					 );
			}

		}
#else
		for(int i = wave_id; i < MLO_N_IN_TILES_TOTAL;  i += MLO_N_PROC_WAVES)
		{
		//(MLO_N_STACKS * MLO_N_OUT_TILES_PERSTACK)
			int i_b = (int)((float)i / (float)MLO_N_IN_TILES_PERSTACK + 0.00001f);
			int i_c = i - mul24(i_b, (int)MLO_N_IN_TILES_PERSTACK);

			bool vis = true;

#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

#if MLO_INPUTS_ALIGNED == 0
			vis &= (ic + i_c < MLO_N_INPUTS);
#endif
			int in_off2 = in_off + i_b * MLO_IN_BATCH_STRIDE + i_c * MLO_IN_CHANNEL_STRIDE;
			int in_lcl_off2 = i_b * MLO_IN_LCL_PERSTACK_SZ + i_c * MLO_IN_LCL_TILE_SZ;

			int elem_id = wave_lcl_id;
			int lcl_p_stride = MLO_N_READ_PROCS;
			int lcl_base = 0;
			int lcl_y = MLO_FILTER_PAD1;
			int lcl_x = MLO_FILTER_PAD0;
			int gbl_base = 0;

			readData(elem_id, (MLO_IN_HEIGHT * MLO_IN_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_grp, x_grp,
						vis,
						true
					 );
		}
#endif

// read inputs and weights
// put weights into LDS

#if 1  // only weights

		for(int i = lcl_id; i < MLO_WEIGHTS_SZ; i += MLO_GRP_SZ)
		{
#if MLO_DIR_FORWARD==1
// here is [tops][bottoms]
			int lcl_o = (int)((float)i / (float)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			int gbl_i = i - mul24(lcl_o, (int)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ));
			if((wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i) < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ))
				lcl_wei[i] = weights[wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i];
			else
				lcl_wei[i] = weights[0];
#else
// outputs are botoms(inputs))
// inputs are tops(outputs)

			int lcl_o = (int)((float)i/ (float)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			int gbl_i = i - mul24(lcl_o, (int)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ));
			int lcl_c = (int)((float)gbl_i/ (float)MLO_FILTER_SZ + 0.00001f);
			int lcl_i = gbl_i - mul24(lcl_c, (int)MLO_FILTER_SZ);

			int lcl_we_off = mad24(mad24(lcl_c, (int)MLO_N_IN_TILES_PERSTACK, lcl_o), (int)MLO_FILTER_SZ, lcl_i);
			int gbl_we_off = mad24(mad24(lcl_o, (int)MLO_N_OUTPUTS, lcl_c), (int)MLO_FILTER_SZ, wei_off + lcl_i);
			bool within_range = gbl_we_off < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ);
			gbl_we_off = (within_range) ? gbl_we_off : 0;
			_FLOAT wei = weights[gbl_we_off];
			wei = (within_range) ? wei : 0;
			lcl_wei[lcl_we_off]
				= wei;

#endif

		}

#endif

// over all batch stacks

#endif  // all input

		barrier(CLK_LOCAL_MEM_FENCE);

// convolution
#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
		if (lcl_id < MLO_ACTIVE_ALUS)
#endif
		Conv(o_map_base,
			in_stg_off,
			pvt_in_stage, lcl_indata,
			pvt_wei_stage, lcl_wei,
			pvt_accum
			);

//		barrier(CLK_LOCAL_MEM_FENCE);
	}

#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
	if (lcl_id >= MLO_ACTIVE_ALUS)
	{
		return;
	}
#endif
// write results out
	int x_out_grp = x_grp;
	int y_out_grp = y_grp;
	int x_out_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	int y_out_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

    int out_off = (b_index + stack) * MLO_OUT_BATCH_STRIDE + o_map * MLO_OUT_CHANNEL_STRIDE + (y_out_grp + y_out_lcl) * MLO_OUT_STRIDE + x_out_grp + x_out_lcl;
// over all local stacks
#if MLO_BATCH_ALIGNED == 0
	if (b_index + stack < MLO_BATCH_SZ)
#endif
	{

// over all local outputs
		int out_off1 = out_off;
		for(int o = 0; o < MLO_N_OUT_TILES
						; ++o, out_off1 += MLO_OUT_CHANNEL_STRIDE
						)
		{
// over output tile
			_FLOAT  bias_val = 0;
#if MLO_CONV_BIAS
			bias_val = bias[o_map + o];
#endif
			int out_off2 = out_off1;
			for( int j = 0; j < MLO_OUT_PIX_TILE1; ++j, out_off2 += MLO_OUT_STRIDE)
			{
				for(int i = 0; i < MLO_OUT_PIX_TILE0; ++i)
				{
					if ( true
#if 1 //MLO_OUT_ALIGNED == 0
					&& y_out_lcl + j < MLO_OUT_TILE1 && y_out_grp + y_out_lcl + j < MLO_OUT_HEIGHT &&  x_out_lcl + i < MLO_OUT_TILE0 && x_out_grp + x_out_lcl + i < MLO_OUT_WIDTH
#endif
#if MLO_OUTPUTS_ALIGNED == 0
						&& o_map + o < MLO_N_OUTPUTS
#endif
					)
					{
						out[out_off2 + i] = pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i] + bias_val;
#if 0
						if ( out_off2 + i == 1 /*y_out_grp + y_out_lcl + j == 2 && x_out_grp + x_out_lcl + i == 0*/)
						{
							printf("K:out: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d    %f %f %f\n",
								MLO_OUT_TILE1,
								MLO_OUT_TILE0,
								grp_id0,
								lcl_id,
								alu_out_plane_id,
								alu_out_id,
								b_index + stack,
								o,
								o_map,
								out_off,
								out_off1,
								out_off2,
								y_out_grp,
								y_out_lcl,
								x_out_grp,
								x_out_lcl,
								j,
								i,
								pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i],
								 bias_val,
								out[out_off2 + i]
								);
						}
#endif
					}

				}
			}

		}
	}

}


INTEGRATION: CWS calcwarnings (1.2.246); FILE MERGED 2006/12/12 17:44:34 nn 1.2.246.2: #i69284# warning-free: unxlngi6 2006/12/01 16:19:38 nn 1.2.246.1: #i69284# warning-free: wntmsci10

/*************************************************************************
 *
 *  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;
	}

}

/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dfa.cl,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2006-01-31 18:33:27 $
 *
 *  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 (((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;
	}

}