
{This function retrieves string from DDE server}
function ReceiveString(service,topic,item);
var channel;
begin		
// Delay(100);	
   channel := DdeInitiate(service,topic) ;
   if channel = 0 then halt( 'Could not connect to Receive Data ' ) ;
   ReceiveString := DdeRequest(channel,item, fmt_Text) ;
   DdeTerminate(channel) ; 
end;		  

{This function pokes string to DDE server}
procedure SendString(service,topic,item,string);
var channel;
begin
// Delay(100);	
   channel := DdeInitiate(service,topic) ;
   if channel = 0 then halt( 'Could not connect to Receive Data ' ) ;			 
   DdePoke(channel,item,string,fmt_Text); 
   DdeTerminate(channel) ;				 	  		  
end;


function CurrentUnit(topic);
var s,t;
begin
   s:=ReceiveString('MotionStageServer',topic,'Unit');
   t:=ParseStr(s,' ,:=');
   CurrentUnit:=t;
end;

function CurrentPosition(topic);
var s,t;
begin
   s:=ReceiveString('MotionStageServer',topic,'Position');
   t:=ParseStr(s,' ,:=');
   CurrentPosition:=Val(t);
end;

function CurrentStatus(topic);
var s,t;
begin
   s:=ReceiveString('MotionStageServer',topic,'Status');
   t:=ParseStr(s,' ,:=');
   if CompareStr(t,'1')=0 then begin CurrentStatus:=True; {WriteStatus('in position');} end
   else begin CurrentStatus:=False; {WriteStatus('in motion');} end;
end;

procedure SetTarget(topic,target);
begin
   SendString('MotionStageServer',topic,'Target',Str(target));
   WriteStatus('moving '+topic+' to '+Str(target));
end;

procedure WaitTarget(topic);
var p,s;
begin
   s:=False;
   repeat
      Delay(100);
	  s:=CurrentStatus(topic);
	  p:=CurrentPosition(topic);
	  WriteStatus(topic+'= '+Str(p)+', status= '+Str(s));
   until (s=True);
end;

{ MAIN PROGRAM }
var Available,Controller,Position,Unit,message;
begin
   Available :=ReceiveString('MotionStageServer','System','Topics');
   WriteInfo(Available);
   Available := 'U100;DG535;BNC575;C862;CTC283;MCDC' ;
   Controller:= 'C862';
   if SelectString('Choose which controller to scan',Available,Controller ) >= 0 then
   begin
      Position:=CurrentPosition(Controller);
      Unit:=CurrentUnit(Controller);
//    WriteInfo( 'will set ',Controller,' in unit of ',Unit) ;
      message:='Current position of '+Controller+' = '+Str(Position)+' '+Unit+Chr(13)+'Enter new position';
//    Position:=1000;
      if GetNumber(message,Position) = id_Ok then
	  begin
         SetTarget(Controller,Position); 
         WaitTarget(Controller);
      end;		
   end;
   PlaySound( 'D:\DATA\SOUNDS\Mac.wav' ) ;
end


// C862 CANNOT go any higer than -1,300,000. Always remember to put the negative sign. // 