(* Collection of code snippets by Arne Vajhøj *)
(* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) *)
program cmplx(input,output);

%include 'gentypes.pas'
%include 'recs.pas'

const
   MAX_CUSTOMERS = 10000;

type
   extcustomer = record
                    customer_name : packed array [1..32] of char;
                    total_sales : integer;
                 end;
   extcustomerlist = array [1..MAX_CUSTOMERS] of extcustomer;

var
   no_xc : integer;
   xc_list : extcustomerlist;

procedure load_data;

var
   fc : file of customer;
   fo : file of order;
   c : customer;
   o : order;
   i : integer;

begin
   open(fc, 'customer.isq', old, organization := indexed, access_method := keyed);
   open(fo, 'order.isq', old, organization := indexed, access_method := keyed);
   resetk(fc, 0);
   no_xc := 0;
   while not eof(fc) do begin
      c := fc^;
      no_xc := no_xc + 1;
      xc_list[no_xc].customer_name := c.name;
      xc_list[no_xc].total_sales := 0;
      resetk(fo, 1);
      findk(fo, 1, c.customer_id);
      while not(ufb(fo)) and not(eof(fo)) and (fo^.customer_id = c.customer_id) do begin
         o := fo^;
         if o.status = 'Delivered' then begin
            for i := 1 to o.no_orderlines do begin
               xc_list[no_xc].total_sales := xc_list[no_xc].total_sales + o.orderlines[i].price;
            end;
         end;
         get(fo);                  ;
      end;
      get(fc);
   end;
   close(fo);
   close(fc);
end;

procedure sort_data;

var
   i, j : integer;
   tmp : extcustomer;

begin
   for i := 1 to no_xc do begin
      for j := (i + 1) to no_xc do begin
         if xc_list[i].total_sales < xc_list[j].total_sales then begin
            tmp := xc_list[i];
            xc_list[i] := xc_list[j];
            xc_list[j] := tmp;
         end;
      end;
   end;
end;

procedure dump_data;

var
   i : integer;

begin
   writeln('Pascal - top customers by sales:');
   for i := 1 to min(no_xc, 3) do begin
      if xc_list[i].total_sales > 10 then begin
         writeln(trim(xc_list[i].customer_name),' : ',xc_list[i].total_sales:1);
      end;
   end;
end;

begin
   load_data;
   sort_data;
   dump_data;
end.
