unit square_lib;
{
translation of sample/square_lib.h
}

interface

function getN: longint;
function getL: longint;
function getWeight(x, y, direction : longint): longint;
procedure solution(x, y : longint);

{ inofficial interface }

const LIB_MAXN = 2003;

var
   LIB_W : array[0..LIB_MAXN] of
           array[0..LIB_MAXN] of array[0..1] of longint;
   LIB_queries	: longint;
   LIB_N, LIB_L	: longint;
   LIB_out	: textfile;

procedure LIB_init;


implementation

function getN : longint;
begin
   LIB_init;
   getN := LIB_N;
end; { getN }

function getL : longint;
begin
   LIB_init;
   getL := LIB_L;
end; { getL }

function getWeight(x, y, direction : longint): longint;
var res	: longint;
begin
   LIB_init;
   inc(LIB_queries);
   if (x<1) or (x>getN)
      then begin
	 writeln(LIB_out, 'getWeight: invalid x=', x);
	 halt(0);
      end;
   if (y<1) or (y>getN)
      then begin
	 writeln(LIB_out, 'getWeight: invalid y=', y);
	 halt(0);
      end;
   if (direction <> 0) and (direction <> 1)
      then begin
	 writeln(LIB_out, 'getWeight: invalid direction=', direction);
	 halt(0);
      end;
   res:= LIB_W[x][y][direction];
   if res < 0
      then begin
	 writeln(LIB_out, 'getWeight: edge does not exist (', x, ', ', y, ', ', direction, ')');
	 halt(0);
      end;
   writeln(LIB_out, 'getWeight: ', x, ' ', y, ' ', direction, ' ', res);
   getWeight:=res;
end; { getWeight }

procedure solution(x, y	: longint);
begin
   LIB_init();
   writeln(LIB_out, 'solution: (', x, ', ', y, ') queries=', LIB_queries);
   close(LIB_out);
   halt(0);
end; { solution }

var already_initialized : longint;
procedure LIB_init;
var x, y : longint;
   fin	 : textfile;
begin
   if already_initialized <> 0
      then exit;
   already_initialized:=1;
   for y:=1 to LIB_MAXN do
      for x:=1 to LIB_MAXN do
      begin
	 LIB_W[x][y][0] := -1;
	 LIB_W[x][y][1] := -1;
      end;
   assign(fin, 'square.in');
   {$I-}
   reset(fin);
   {$I+}
   if IOResult <> 0 then begin
      writeln(LIB_out, 'cannot open square.in');
      halt(0);
   end;
   readln(fin, LIB_N, LIB_L);
   for y:=1 to LIB_N do
      for x:=1 to LIB_N-1 do
	 read(fin, LIB_W[x][y][0]);
   for y:=1 to LIB_N-1 do
      for x:=1 to LIB_N do
	 read(fin, LIB_W[x][y][1]);
   close(fin);
end;

begin
   LIB_queries := 0;
   already_initialized := 0;
   LIB_out := stdout;
end.