/*Objective_C Implementation of the SquareMatrix Class: SquareMatrix.m*/

#import <stdio.h>
#import "SquareMatrix.h"
#import <objc/List.h>
#import <objc/Storage.h>

@implementation SquareMatrix

- init
{
	return [self initRows:1];
}
	
- initRows:(int)rows
{
	int i;
	if(columnList) {			//if previously initialized, free up
		[columnList freeObjects];
		[columnList free];
		}
	numberOfRows = numberOfColumns = rows;
	columnList = [[List alloc] initCount:numberOfColumns];
	for(i=0;i<numberOfColumns;i++) 
	[columnList addObject:[[Storage  alloc] initCount :numberOfRows
		elementSize:sizeof(float)
 		description:"f"]];
	return self;
}
				   
//Return element at (row,column)
-(float)elementAtRow:(int)row column:(int)column
{
	if(! [self checkRow:row column:column]) return 0.0;

	return *(float *)[[columnList  objectAt:column] elementAt:row];
}

//Set element at (row,column)
-setElementAtRow:(int)row column:(int)column to:(float)aNumber
{
	if( [self checkRow:row column:column]) 
		[[columnList  objectAt:column] replaceElementAt:row with:&aNumber];
	return self;
}
  
//Transpose the matrix
-transpose
{
	float upper,lower;
	int i, j, fromIndex=0;

	for(i=0;i<numberOfRows;i++) {
	  for(j=fromIndex;j<numberOfColumns;j++) {
	    lower = [self elementAtRow:i column:j];
	    upper = [self elementAtRow:j column:i];
	    [self setElementAtRow:j column:i to:lower];
	    [self setElementAtRow:i column:j to:upper];
	  }
	  fromIndex++;
	}
	return self;
}

- (BOOL) checkRow:(int)row column:(int)column
{
	if ((row >= numberOfRows)||(column >= numberOfColumns))
		return NO;
	else
		return YES;
}

//Free the matrix
- free
{
	[columnList freeObjects];
	[columnList free];
	return [super free];
}

//Print the elements in the matrix
-printMatrix
{
	int i, j;	
	printf("Contents of the Matrix:\n");
	for(j=0;j<numberOfColumns;j++)
	  for(i=0;i<numberOfRows;i++)
	    printf("Element at Location [%i %i] is %f\n", i, j, [self elementAtRow:i column:j]);
	return self;
}

@end
