PK.MARKEY
"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>"^!;

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

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

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

[6]::MARS
IF{"if discontinued, check rx end date against date from pk",
   ^$(T)TR[tr]^PHA.MAIN,
   [PHA.MAIN]|8^stat,
   stat="AC" "MARS2",@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<MEDODATE);
   "MARS2",@7};

[7]::MARS2
""^traQ,
DO{"NEXT.MAR",@8 "SEND",@9};

[8]::NEXT.MAR
-(?(T)TRA[tr,traQ],TRA)^traQ,
IF{?(T)TRA[tr,traQ]|1<MARDATE "";traQ};

[9]::SEND
&(T)TDO[$(T)TR[tr]|7]|2^TYPE,
IF{TYPE="COMP" DO{+$(T)TR[tr]IN[x]^x tr_"."_x^mnemonic,"SEND.MAR",@10};
   TYPE="SPLIT" DO{+$(T)TR[tr]MD[x]^x tr_"."_x^mnemonic,"SEND.MAR",@10};
   TYPE="ALT" DO{+$(T)TR[tr]BT[x]^x IF{TRA|7'=x;tr_"."_x^mnemonic,"SEND.MAR",@10}};
   tr^mnemonic,"SEND.MAR",@10};

[10]::SEND.MAR
"<MedicationResult>"^!,
"<EventMnemonic>"_mnemonic_":"_traQ_"</EventMnemonic>"^!,
"<Key>"_TRA|1_TRA|2_"</Key>"^!,
"<PatientNumber>"_$(A)AA[aa]|3_"</PatientNumber>"^!,
"<OrderMnemonic>"_mnemonic_"</OrderMnemonic>"^!,
"</MedicationResult>"^!;

