;=======================================
; cmd_main (send command to any drive)
;=======================================

program cmd_main

include library
include prosys
include 1:diskutils.e

word command
word err
word i

byte cmdbuf[81]
byte dev

;---------------------------------------
; Print usage message.
;---------------------------------------
proc usage

begin

output"#cUsage: cmd <device> <command>#c"

end

;---------------------------------------
; Parse command-line arguments.
; return: true if arguments are valid,
;         false otherwise.
;---------------------------------------
func byte parse
word i
word j
byte b

begin

if ncarg<>2
  return false

dev=0
command=0

for i=1 to ncarg ;0 is program name
  if cmpstr(carg[i],"=","0:")
    if dev>0 ;dev already specified
      return false
    dev=c64ddv0
  else if cmpstr(carg[i],"=","1:")
    if dev>0 ;dev already specified
      return false
    dev=c64ddv1
  else
    b=strval(carg[i],#j) ;j must be word
    if (carg[i]+b)@< ;not numeric?
      ;must be the command
      command=carg[i]
    else
      if dev>0 ;already specified
        return false
      if j<8 or j>30
        return false
      else
        dev=j

if dev=0 or command=0
  return false
return true

end

;=======================================
; program mainline
;=======================================

begin

drvquery

if not parse
  usage
  exit

if drives[dev-8]=0
  output"#c#cDevice #w not present!#c",dev
  exit

i=0
while i<lenstr(command)
  cmdbuf[i]=toupper((command+i)@<)
  i=i+1
  if i=80
    output"#cCommand too long!#c"
    exit
cmdbuf[i]=0

err=sendcmd(dev,cmdbuf)
if err
  output"#cError $#04h sending command!#c"
  exit

err=readcmd(dev,cmdbuf)
if err
  output"#cError $#04h reading command channel!#c"
  exit
output"#c#s",cmdbuf

end
