IDENTIFICATION DIVISION.
PROGRAM-ID. CustomerAnalytics.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT CUSTOMER-FILE ASSIGN TO 'CUSTOMER.DAT' ORGANIZATION IS LINE SEQUENTIAL.
    SELECT REPORT-FILE ASSIGN TO 'REPORT.TXT' ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD CUSTOMER-FILE.
01 CUSTOMER-RECORD.
   05 CUSTOMER-ID PIC 9(4).
   05 CUSTOMER-NAME PIC X(20).
   05 ACCOUNT-BALANCE PIC 9(7)V99.

FD REPORT-FILE.
01 REPORT-RECORD PIC A(80).

WORKING-STORAGE SECTION.
01 END-OF-FILE PIC X VALUE 'N'.
   88 EOF VALUE 'Y'.
   88 NOT-EOF VALUE 'N'.
01 TOTAL-BALANCE PIC 9(9)V99 VALUE ZERO.
01 CUSTOMER-COUNT PIC 9(4) VALUE ZERO.
01 AVERAGE-BALANCE PIC 9(7)V99.
01 WS-AVG-BALANCE-FMT PIC Z,ZZZ,ZZ9.99.
01 REPORT-LINE PIC A(80).

PROCEDURE DIVISION.
000-MAIN.
    OPEN INPUT CUSTOMER-FILE
         OUTPUT REPORT-FILE
    PERFORM UNTIL EOF
        READ CUSTOMER-FILE INTO CUSTOMER-RECORD
            AT END
                SET EOF TO TRUE
            NOT AT END
                ADD 1 TO CUSTOMER-COUNT
                ADD ACCOUNT-BALANCE TO TOTAL-BALANCE
        END-READ
    END-PERFORM

    CLOSE CUSTOMER-FILE

    IF CUSTOMER-COUNT > 0
        COMPUTE AVERAGE-BALANCE ROUNDED = TOTAL-BALANCE / CUSTOMER-COUNT
        MOVE "Average Account Balance: " TO REPORT-LINE
        WRITE REPORT-RECORD FROM REPORT-LINE

        MOVE SPACES TO REPORT-LINE
        MOVE AVERAGE-BALANCE TO WS-AVG-BALANCE-FMT
        STRING "Average: $" WS-AVG-BALANCE-FMT DELIMITED BY SIZE INTO REPORT-LINE
        WRITE REPORT-RECORD FROM REPORT-LINE AFTER 1

        MOVE "High-Value Customers:" TO REPORT-LINE
        WRITE REPORT-RECORD FROM REPORT-LINE AFTER 2 LINES

        OPEN INPUT CUSTOMER-FILE
        SET NOT-EOF TO TRUE
        PERFORM UNTIL EOF
            READ CUSTOMER-FILE INTO CUSTOMER-RECORD
                AT END
                    SET EOF TO TRUE
                NOT AT END
                    IF ACCOUNT-BALANCE > AVERAGE-BALANCE
                        MOVE SPACES TO REPORT-LINE
                        STRING CUSTOMER-ID " - " CUSTOMER-NAME DELIMITED BY SIZE INTO REPORT-LINE
                        WRITE REPORT-RECORD FROM REPORT-LINE AFTER ADVANCING 1 LINE
                    END-IF
            END-READ
        END-PERFORM
    END-IF

    CLOSE CUSTOMER-FILE
         REPORT-FILE
    STOP RUN.
