//
class HASHB;
	dim Const MAX_SUM As Long = 0x00ffffff;
	char(1)	ha_id[2];
	int		ha_keylen;
	int 	ha_maxreg;
	int 	ha_prereg;
	char	ha_reg[1];
	int		ha_np[1];
	char	ha_key;
	int 	ha_aux;
	int 	ha_hix;
//print ha_reg;
	func HASHB(maxreg,prereg);
		ha_maxreg = maxreg;
		ha_prereg = prereg;
		ha_aux    = prereg;
		redefine ha_reg[maxreg];
		redefine ha_np[maxreg];
		i = 0;
		loop maxreg;
			ha_reg[i] = '';
			ha_np[i++] = 0;
		end loop;
		return ERROR;
	end func;

	Function store(key As String);
		Dim count As Long;
		Dim i As Long;
		Dim i_start As Long;

//print key;
		i = My.hashf(key, ha_prereg);
		i_start = i;
		count = 0;

		loop do;
//print i;
			If ha_reg[i-1] == '' Then
				ha_reg[i-1] = key;
				return i;
			ElseIf key == ha_reg[i] Then
				return i;
			End If;

			If ha_np[i-1] > 0 Then
				i = ha_np[i-1];
				count = count + 1;
				If i <> i_start And count < maxk Thenl continue;
			End If;
			break;
		end do;
		If ha_aux < 0 Then
			return 0;
		End If;

		k = i;
		i = ha_aux;
//print k;
		loop do;
			i = i + 1;
			If i > ha_maxreg Thenl i = 1;
//print i;
			If ha_reg[i-1] == '' Then
				ha_reg[i-1] = key;
				ha_np[k-1] = i;
				ha_aux = i;
			ElseIf i == ha_aux Then
				ha_aux = -i;
				i = 0;
			Else
				continue;
			End If;
			break;
		end do;
		return i;

	End Function;

	Function refer(key As String);
		Dim count As Long;
		Dim i As Long;
		Dim i_start As Long;
//print key;
		i = My.hashf(key, ha_prereg);
		i_start = i;
		count = 0;

		loop do;
//print i ha_reg[i-1];
			If key == ha_reg[i-1] Then
				return i;
			End If;
			i = ha_np[i-1];
			If i > 0 Then
				count = count + 1;
				If i <> i_start And count < ha_maxreg Thenl continue;
			End If;
			break;
		end do;
		return 0;

	End Function;

	Function hashf(key As String,prereg As Long);
		Dim klen As Integer;
		Dim i As Integer;
		Dim k As Long;

		klen = Lenb(key);
		k = 0;
		For i=1 To klen;
			k = (k*37 + Asc(Midb(key,i,1))) & MAX_SUM;
//print i k;
		Next;
		return  (k Mod prereg) + 1;
	End Function;

end class;

proc main;
	hp = new HASHB(10,7);
	print hp.ha_maxreg hp.ha_prereg hp.ha_reg;
	i=100;
	loop 1;
		print hp.store((char)(i+=100));
	end loop;
	i=100;
	loop 1;
		print hp.refer((char)(i+=100));
	end loop;
/*
	loop;
		ELWRITE1('Enter /END,S,R: ');
		line = getline();
		if inistr(line,'/END') thenl exit;
		cmd = to(left(line,1),'U');
		ELWRITE1('Enter key: ');
		line = getline();
		switch cmd;
			case 'S';
				print hp.store(line);
			case 'R';
				print hp.refer(line);
		end switch;
	end loop;
*/
	return ERROR;
end proc;
