Flag variable in SAS based on two conditions

I am having trouble getting the following code to work properly. Essentially, I'm creating a flag variable for incident diabetes based on randid, and diabetes. My data contain two records for each patient, one entry for period 1 and an entry for period 2. If for the first entry (first.randid), diabetes=1, then I want to flag variable=0. If for first.randid, diabetes=0, the I want to evaluate diabetes status for last.randid. If diabetes=1 for last.randid, then flag variable=1. Otherwise, the flag variable=0. Here is the code:

data flag;
input RANDID DIABETES PERIOD rte_cat $6.;
6238    0   1   High
6238    1   2   High
9428    0   1   Normal
9428    0   2   Normal

*Creating a flag variable for incident diabetes;

data mid.flag;
set mid.heart end=eof;
    by randid diabetes;
    if first.randid and diabetes=1 then diab_flag=0;
    if first.randid and diabetes=0 then do;
        if last.randid and diabetes=1 then diab_flag=1;
        else diab_flag=0;

proc print data=mid.flag (obs=200);

For the output, I want it to look like this:

RANDID DIABETES PERIOD rte_cat diab_flag
6238    0   1   High    0
6238    1   2   High    1
9428    0   1   Normal    0
9428    0   2   Normal    0