IDENTIFICATION DIVISION.
PROGRAM-ID. PROB1.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
      SELECT INPUT-FILE ASSIGN TO 'PROB1.txt'
      ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INPUT-FILE.
01  INPUT-RECORD PIC X(10).
WORKING-STORAGE SECTION.
01  INPUT-VALUE pic s9(9).
01  RUNNING-TOTAL pic s9(9).
01  MODULO-TOTAL pic s9(9).
01  CHECK-TOTAL pic s9(9).
01  PRINT-LINE.
    02  PRINT-MESSAGE pic x(30).
    02  PRINT-VALUE pic s9(9) USAGE IS DISPLAY.
01  DATA-TABLE.
    02  DATA-ENTRY OCCURS 100000 TIMES INDEXED BY PRIOR-INDEX.
        03  USER-INPUT pic s9(9).
        03  PRIOR-VALUE pic s9(9).
01  PRIOR-COUNT pic s9(9).
01  VERBOSE-FLAG pic 9.
01  ITERATION-COUNT pic s9(9).
PROCEDURE DIVISION.
DISPLAY "Welcome to the Advent of COBOL 2018 Edition!".
DISPLAY "--------------------------------------------".
DISPLAY SPACES.
MOVE ZEROS TO PRIOR-COUNT.
MOVE ZEROS TO RUNNING-TOTAL.
MOVE 1 TO VERBOSE-FLAG.
MOVE ZEROS TO ITERATION-COUNT
MOVE 1 TO PRIOR-INDEX.
OPEN INPUT INPUT-FILE.
GO TO 1-MAIN.
CHECK-DUPLICATE.
    IF PRIOR-COUNT IS GREATER THAN 100000
        DISPLAY "ERROR: Count exceeds 100,000."
        STOP RUN.
    PERFORM
        VARYING PRIOR-INDEX FROM 1 BY 1
            UNTIL PRIOR-INDEX IS GREATER THAN PRIOR-COUNT
        IF PRIOR-VALUE (PRIOR-INDEX) IS EQUAL TO RUNNING-TOTAL
            MOVE "Found duplicate" TO PRINT-MESSAGE
            MOVE RUNNING-TOTAL TO PRINT-VALUE
            DISPLAY PRINT-LINE
            STOP RUN
        END-IF
    END-PERFORM.
CHECK-EXIT.
    EXIT.
TALLY-HO-HO-HO.
    IF INPUT-VALUE IS LESS THAN ZEROS
        SUBTRACT INPUT-VALUE FROM ZEROS GIVING PRINT-VALUE
      ELSE
        MOVE INPUT-VALUE TO PRINT-VALUE
    END-IF.
    IF INPUT-VALUE IS GREATER THAN ZEROS
        MOVE "Nice!" TO PRINT-MESSAGE
      ELSE
        MOVE "Naughty!" TO PRINT-MESSAGE
    END-IF.
    IF VERBOSE-FLAG IS EQUAL TO 1
        DISPLAY PRINT-LINE.
    ADD INPUT-VALUE TO RUNNING-TOTAL.
    PERFORM CHECK-DUPLICATE THRU CHECK-EXIT.
    ADD 1 TO PRIOR-COUNT.
    SET PRIOR-INDEX TO PRIOR-COUNT.
    MOVE RUNNING-TOTAL TO PRIOR-VALUE (PRIOR-INDEX).
TALLY-EXIT.
    EXIT.
1-MAIN.
READ INPUT-FILE
    AT END GO TO 2-FINISH.
SET PRIOR-INDEX UP BY 1.
MOVE INPUT-RECORD TO USER-INPUT (PRIOR-INDEX).
MOVE INPUT-RECORD TO INPUT-VALUE.
PERFORM TALLY-HO-HO-HO THRU TALLY-EXIT.
GO TO 1-MAIN.

2-FINISH.
MOVE RUNNING-TOTAL TO PRINT-VALUE.
MOVE "Resulting Frequency:" TO PRINT-MESSAGE.
DISPLAY PRINT-LINE.
CLOSE INPUT-FILE.
STOP RUN.
