unit grid;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TDGrid1 = class(TForm)

    Button1: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Button2: TButton;
    Edit4: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);



  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  DGrid1: TDGrid1;

implementation

{$R *.DFM}

procedure TDGrid1.Button1Click(Sender: TObject);
var
Longitude,Latitude:double;
A,B,C,D:double;

begin
Longitude:= strtofloat(Edit2.text); //1.785;
Longitude:= -Longitude;
Latitude:= strtofloat(edit1.text); //51.078;
Longitude:=(Longitude+180)/20;
Latitude:=(Latitude+90)/10;
A:=int(Longitude);
B:=int(Latitude);
Longitude:=(Longitude-A)*10;
Latitude:=(Latitude-B)*10;
C:=int(Longitude);
D:=int(Latitude);
edit3.text :=  chr(strtoint(floattostr(A+65)))+  chr(strtoint(floattostr(B+65)))+chr(strtoint(floattostr(c+48)))+ chr(strtoint(floattostr(d+48)))+chr(strtoint(floattostr((INT((Longitude-C)*24)+65))))  +chr(strtoint(floattostr((INT((Latitude-D)*24)+65))))

end;

procedure TDGrid1.Button2Click(Sender: TObject);
var
 La, Lb : real;
 A : array[1..6] of integer;
 s:string;
 c, value:integer;

begin        //calculates latitude and longitude from grid square data

A[1]:=0;
A[2]:=0;
A[3]:=0;
A[4]:=0;
A[5]:=0;
A[6]:=0;
 s:=edit4.Text;   //the grid square
 if (length(s) < 5 )then      //if only 4 grid terms are input assumes the
                              //approx. middle of the grid, i.e. "LL"
    begin
    s:= s+'LL';
    end;
 if (length(s) > 6 )then      //handle too many terms
    begin
    edit4.text :='too long!' ;
    s := 'JJ00AA';    //default value
    edit1.text :='0';
    edit2.text :='0';
    exit ;
    end;

 for c:=1 to length(s) do      //finally, calculate the lat/long
 begin
     value:=ord(s[c]);
     a[c]:= value;

  end;


   La := -180 +(A[1]-65)*20+(A[3]-48)*2+(A[5]-64.5)/12 ;
   Lb := -90 + (A[2]-65)*10 +(A[4]-48)+( A[6]-64.5)/24 ;

  Edit1.Text := FloattoStrf(Lb,ffFixed,4,2);
  Edit2.Text := floattoStrf(-La,ffFixed,5,2);
   
end;
  
end.
