/* array04 - simple tests for NSDecimal arrays 

   Copyright (C) 1995, Adam Fedor

*/

#ifdef NEXT_FOUNDATION
#include <foundation/NSValue.h>
#include <foundation/NSAutoreleasePool.h>
#define  reason exceptionReason
#else
#include <Foundation/NSValue.h>
#include <Foundation/NSAutoreleasePool.h>
#endif
#ifdef HAVE_FOUNDATION_NSDECIMAL_H
#include <Foundation/NSDecimalNumber.h>
#else
#define NSDecimal double
#endif
#include <stdio.h>
#include <math.h>
#include "MathArray/MathArray.h"
#include "MathArray/MaskedException.h"
#include "MathArray/MAValue.h"

/* Replace value by the exponent of it's index */
id <NSNumber,ComplexNumber>
exp_array(id <NSNumber,ComplexNumber>number, unsigned *index, void *info)
{
  return [MANumber numberWithDouble:index[0]*index[1]];
}

int
main()
{
  NSAutoreleasePool* pool;
  MathArray *array;
  unsigned  index[2];

  pool = [NSAutoreleasePool new];
  [MaskedException bodysnatchNSException];
  [MaskedException setMaskForAllExceptions:AbortException];

  printf("Create 100 point vector...\n");
  array = [MathArray maWithVector:100 objCType:@encode(NSDecimal)];

  [array maAdd:[NSNumber numberWithFloat:3.01]];
  printf("Add 3.01, Total is %f (should be 301.0)\n", 
	[[array maTotal] floatValue]);

  [array maDivide:[NSNumber numberWithInt:2]];
  printf("Divide 2, Total is %f (should be 150.5)\n", 
	[[array maTotal] floatValue]);

/*
  [array maCos];
  printf("Take cos, Total is %f (should be 6.57488)\n", 
	[[array maTotal] floatValue]);
*/

  /* Matrices */
  printf("Create 10X10 matrix...\n");
  array = [MathArray maMatrixWithCols:10 rows:10 objCType: @encode(NSDecimal)];

  printf("Perform user function...\n");
  [array maPerformFunction:exp_array userInfo:NULL];
  index[0] = 3;
  index[1] = 3;
  printf("Value at (3,3) is %g (should be 9)\n", 
	[[array arrayValueAtIndex:index] doubleValue]);
  printf("Total is %g (should be 2025)\n", [[array maTotal] doubleValue]);

  /* Try an illegal operation */
  printf("Intentionally divide by 0 (should get error)\n");
  NS_DURING
    [array maDivide: [NSNumber numberWithFloat:0.0]];
  NS_HANDLER
#ifdef NEXT_FOUNDATION
    printf("  Caught Exception - %s\n", [[exception reason] cString]);
#else
    printf("  Caught Exception - %s\n", [[localException reason] cString]);
#endif
  NS_ENDHANDLER

#ifdef HAVE_FOUNDATION_NSDECIMAL_H
  printf("Try very small numbers...\n");
  printf("Start with zeroed 9x9 array\n");
  array = [MathArray maMatrixWithCols: 9 rows: 9 objCType: @encode(NSDecimal)];
  [array maAdd: [NSDecimalNumber decimalNumberWithString: 
		  @"3.456789012345678e-45"]];
  printf("Add 3.456789102345678e-45, Total is %s\n", 
	[[[array maTotal] stringValue] cString]);
  [array maDivide: [NSDecimalNumber decimalNumberWithString: @"8.1"]];
  printf("Divide by 8.1,             Total is %s (should by 3.456...e-44)\n", 
	[[[array maTotal] stringValue] cString]);

#endif

  printf("Finished test\n");
  [pool release];
  return 0;
}
