#include"Mem.h"
#include"Err.h"
#include<stdlib.h>
#include<string.h>

Land * 	Mem::K = 0;
Land 	Mem::K1 = Land(G);
Land 	Mem::K2 = Land(TG);

static int* p;

void  Mem::InitMem(){	
	K = (Land*)malloc(N*sizeof(Land)); memset(K,0,N*sizeof(Land));
	if (!K) Err::MI("Mem::InitMem","out of memory");
	for (int i=0;i<N;i++)K[i].t0 = i;
	K1.t0 = G;
	K2.t0 = TG;
}
void  Mem::TermineMem(){
	free(K);
}

int Mem::Q(){
	int s=N*sizeof(Land);
	for (int i=0;i<N;i++)s+=K[i].Q;
	s+=K1.Q+K2.Q;
	return s;
}
int Mem::Qi(){
	int s=0;
	for (int i=0;i<N;i++)s+=K[i].Qi;
	s+=K1.Qi+K2.Qi;
	return s;
}
int Mem::QP(){
	int s=0;
	for (int i=0;i<N;i++)s+=K[i].t*sizeof(int);
	s+=(K1.t+K2.t)*sizeof(int);;
	return s;
}

int * Mem::Malloc(int & t)
{
	if (t<=0) Err::MI("Mem::Malloc","t<=0");
	if (t<N) return K[t].Malloc(10);
	if (t<=G){t=G;return K1.Malloc(5);}
	if (t<=TG){t=TG;return K2.Malloc(1);}
	Err::MI("Mem::Malloc","t>TG");return NULL;
	
}
int * Mem::Calloc(int & t)
{
	if (t<=0) Err::MI("Mem::Calloc","t<=0");
	if (t<N)return K[t].Calloc(10);
	if (t<=G){t=G;return K1.Calloc(5);}
	if (t<=TG){t=TG;return K2.Calloc(1);}
	Err::MI("Mem::Calloc","t>TG");return NULL;
}
int * Mem::Realloc(int* p1,int t1,int & t)
{   
	if (t<=0) Err::MI("Mem::Realloc","t<=0");
	if (t<N){p=K[t].Malloc(10); memcpy(p,p1,sizeof(int)*((t1<t)?t1:t));Mem::Free(p1,t1);return p;}
	if (t<=G){t=G;p=K1.Malloc(5); memcpy(p,p1,sizeof(int)*((t1<t)?t1:t));Mem::Free(p1,t1);return p;}
	if (t<=TG){t=TG;p=K2.Malloc(5); memcpy(p,p1,sizeof(int)*((t1<t)?t1:t));Mem::Free(p1,t1);return p;}
	Err::MI("Mem::Realloc","t>TG");return NULL;
}
void Mem::Free(int *p, int t)
{
	if (t<=0) Err::MI("Mem::Free","t<=0");
	if (t<N) K[t].Free(p);
	else if (t==G) K1.Free(p);
	else if (t==TG) K2.Free(p);
	else Err::MI("Mem::Free","t>TGMem");
}
