#import "Pattern.h"
#import <appkit/appkit.h>
#import <objc/Object.h>
#include <streams/streams.h>
#import <stdlib.h>
#import <string.h>
#import <appkit/publicWraps.h>	/* for NXBeep() */


#define PAT_UNKOWN 0
#define PAT_ASCII 1
#define PAT_BIN 2

@implementation Pattern


+ new
{
     self=[super new];
     return self;
}
- init
{
    [super init];
    fileName = 0; 
    return self;
}
- (char *)fileName
{
    return fileName;
}
- (int)Dimension
{
    return (int)dimPat;
}
- (int)Quantity
{
    return (int)quanPat;
}
- (float)Maximum;
{
    return (float)maxPat;
}
// carefull 'cause it's the real pointer to pattern
- (float *)thePattern:(int)i
{
    return (float *)PatArray[i];
}

- setFileName:(char *)aName
{
    if (fileName)
	free(fileName);
    fileName = (char *)malloc(strlen(aName)+1);
    strcpy(fileName,aName);
    return self;
}
- load:sender
{
     int i,n;
     char savecode[10];
     char *str1="ascii";
     char *str2="bin";
     NXStream  *stream;

     // disallocation of PatArray
     if (PatArray) {
       for (i=0; i<quanPat; i++)
         free(PatArray[i]);
       free(PatArray);
       }

     stream=NXMapFile(fileName,NX_READONLY);
     if (stream) {
       NX_DURING
         NXScanf(stream, "%s%d%d",savecode,&quanPat,&dimPat);
         PatSaveCode=PAT_UNKOWN;
         if (strcmp(savecode,str1)==0)
           PatSaveCode=PAT_ASCII;
         if (strcmp(savecode,str2)==0)
           PatSaveCode=PAT_BIN;

         NX_ASSERT( (PatSaveCode!=PAT_UNKOWN),"Unkown pattern file");
//	 if (PatSaveCode==PAT_UNKOWN) NX_VALRETURN(nil);

         // new allocation of PatArray
         PatArray=0;
         PatArray=(float **) malloc(quanPat*sizeof(float *));
         NX_ASSERT( PatArray,"Bad allocation of pattern array");
//	 if (!PatArray) NX_VALRETURN(nil);
         for (i=0; i<quanPat; i++)
           PatArray[i]=(float *) malloc(dimPat*sizeof(float));
         maxPat=0.0;

         switch (PatSaveCode) {
           case PAT_ASCII:
             for (i=0; i<quanPat; i++)
               for (n=0; n<dimPat; n++) {
                 NXScanf(stream, "%f",&PatArray[i][n]);
                 maxPat=(maxPat<PatArray[i][n]) ? PatArray[i][n]:maxPat;
               }
             break;
           case PAT_BIN:
             NXSeek(stream,quanPat*dimPat*sizeof(float),NX_FROMEND);
             for (i=0; i<quanPat; i++)
               for (n=0; n<dimPat; n++)
                 NXRead(stream,&PatArray[i][n],sizeof(float));
           break;
           }
         NXCloseMemory(stream,NX_FREEBUFFER);
         NX_VALRETURN(self);
       NX_HANDLER
	NX_DURING
          NXCloseMemory(stream,NX_FREEBUFFER);
	NX_HANDLER
	NX_ENDHANDLER
	  return nil;
       NX_ENDHANDLER
       return self;
       }
     return nil;
}
@end




