/**********************************************************************
 
	Copyright (C) 2005- Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program 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.

**********************************************************************/

#include	"init.h"
#include	"memory_debug.h"
#include	"filespace64.h"


#define INC_PITCH	1000
#define MAX_SIZE	200000
#define CLEAR_STEP	13
#define TRY_CNT		1000


INTEGER64
alloc_test_fs(PDB64 * fd,INTEGER64 size)
{
PN64_HEADER * h;
INTEGER64 ofs;
	printf("SIZE = %lli ",size);
	h = d_alloc(size);
	h->type = 123;
	h->size = size;
	ofs = alloc_filespace64(fd,h);
	if ( ofs < 0 )
		er_panic("alloc_test_fs(1)");

	change_endian_header64(h);
	if ( write_filespace64f(fd,ofs,h) < 0 )
		er_panic("alloc_test_fs(2)");
	d_f_ree(h);
	printf("ofs = %lli\n",ofs);
	return ofs;
}

void
free_test_fs(PDB64 * fd,INTEGER64 ofs)
{
	printf("ofs = %lli\n",ofs);
	free_filespace64(fd,ofs);
}

int
_main(int argc,char ** argv)
{
PDB64 * fd;
L_CHAR * encoding;
INTEGER64 * ofs;
int cnt;
int i;
int clear;
int try_c;
int zero;
int up_flag;
	minimum_matrix_init(argc,argv); 
	encoding = l_string(std_cm,"utf8");
	fd = open_filespace64(
		"test",
		O_TRUNC|O_CREAT|O_RDWR,0644,
		PF_USEFREELIST,FT_MATRIX,encoding);
	ofs = d_alloc(sizeof(INTEGER64)*(cnt  = MAX_SIZE/INC_PITCH + 1));
	printf("PHASE 1 ALLOC\n");
	for ( i = 1 ; i <= cnt ; i ++ )
		ofs[i-1] = alloc_test_fs(fd,INC_PITCH*i);
	printf("PHASE 2 FREE\n");
	clear = CLEAR_STEP;
	try_c = TRY_CNT;
	up_flag = 0;
	for ( ; try_c ; try_c -- ) {
		printf("T %i %i\n",clear,try_c);
		zero = 0;
		for ( ; ofs[clear] == 0 ; ) {
			clear = ((clear + 1) % cnt);
			if ( clear == 0 )
				zero++;
			if ( zero >= 2 )
				break;
		}
		if ( ofs[clear] ) {
			free_test_fs(fd,ofs[clear]);
		}
		else {
			ofs[clear] = alloc_test_fs(fd,INC_PITCH*clear+28);
			up_flag = 1;
		}
		ofs[clear] = 0;
		clear = (clear + CLEAR_STEP) % cnt;
		zero = 0;
		for ( ; ofs[clear] == 0 ; ) {
			clear = ((clear + 1) % cnt);
			if ( clear == 0 )
				zero++;
			if ( zero >= 2 )
				break;
		}
		if ( up_flag == 0 && ofs[clear] ) {
			free_test_fs(fd,ofs[clear]);
		}
		ofs[clear] = alloc_test_fs(fd,INC_PITCH*clear+28);
		clear = (clear + CLEAR_STEP) % cnt;
		zero = 0;
		for ( ; ofs[clear] == 0 ; ) {
			clear = ((clear + 1) % cnt);
			if ( clear == 0 )
				zero++;
			if ( zero >= 2 )
				break;
		}
		if ( up_flag )
			ofs[clear] = alloc_test_fs(fd,INC_PITCH*clear+28);
		up_flag = 0;
	}
	close_filespace64(fd);
	return 0;
}



