PK.MEDOKEY
"HDR",@1,
"PATS",@3,
"TRLR",@2,
END;

[1]::HDR
"<?xml version="_D(34)_1.0_D(34)_" ?>"^!,
"<ReplyMessage>"^!,
"<TransactionId>"_1234_"</TransactionId>"^!,
"<Status>Success</Status>"^!,
"<Payload>"^!;

[2]::TRLR
"</Payload>"^!,
"</ReplyMessage>"^!;

[3]::PATS
/ARGV[1]^DT,
2^nr,
DO{nr</ARGC 1,
   /ARGV[nr]^ACT,
   ?(A)AAAI[ACT]^aa,
   "PHA",@4,
   nr+1^nr};

[4]::PHA
""^Q,
DO{"NEXT.RX",@5 "SEND",@6};

[5]::NEXT.RX
>(?(T)TRP[aa,Q],tr)^Q;

[6]::SEND
IF{"if discontinued, check rx end date against date from pk",
   ^$(T)TR[tr]^PHA.MAIN,
   [PHA.MAIN]|8^stat,
   stat="AC" "SEND2",@7;
    IF{stat="DC" [PHA.MAIN]|5;
      stat="CAN" [PHA.MAIN,2]|3}^other.dt,
   [PHA.MAIN]|16^STOP.DT,
   IF{STOP.DT_.=. other.dt;
      other.dt&(other.dt<STOP.DT) other.dt;
      STOP.DT}^STOP.DT,
   (STOP.DT_.'=.)&(STOP.DT<DT);
   "SEND2",@7};

[7]::SEND2
[PHA.MAIN]|14_[PHA.MAIN]|15^START.DT,
[PHA.MAIN,2]|0_[PHA.MAIN,2]|1_START.DT_STOP.DT^KEY,
$(A)AA[aa]|3^MRN,
&(T)TDO[[PHA.MAIN]|7]|2^TYPE,
IF{TYPE="COMP" DO{+[PHA.MAIN,"IN",x]^x tr_"."_x^mnemonic,"SEND.ORDER",@8};
   TYPE="SPLIT" DO{+[PHA.MAIN,"MD",x]^x tr_"."_x^mnemonic,"SEND.ORDER",@8};
   TYPE="ALT" DO{+[PHA.MAIN,"BT",x]^x tr_"."_x^mnemonic,"SEND.ORDER",@8};
   tr^mnemonic,"SEND.ORDER",@8};

[8]::SEND.ORDER
"<Order>"^!,
"<OrderMnemonic>"_mnemonic_"</OrderMnemonic>"^!,
"<Key>"_KEY_"</Key>"^!,
"<PatientNumber>"_MRN_"</PatientNumber>"^!,
"</Order>"^!;

