#!/usr/bin/awk -f

BEGIN {
    RS="\n"
    FS=" "
    CSV_HEADER="node,wakets,sleepts,duration"
    CSV_DATA=""
    skip=1
}

/wakes up/{
    gsub("]","",$0)
    wakets[$4][length(wakets[$4])+1]=$2
    skip=0
}

/is sleeping/{
    gsub("]","",$0)
    if(!skip){
        sleepts[$4][length(sleepts[$4])+1]=$2
    }
}

/LOG2PARSE/{
    gsub("]","",$0)
    endts[$6][length(endts[$6])+1]=$2
}

END {
    print(CSV_HEADER);
    for(node in wakets){
        for(j=1;j<=length(wakets[node]);j++){
            start=wakets[node][j]
            end=endts[node][1]
            # Pay attention, the last sleep report for the last wake up is not printed
            # so use the printed sleep only if available (otherwise we use the en of the simulation)
            if(j<=length(sleepts[node])){
                end=sleepts[node][j]
            }
            print(node","start","end","end-start)
        }
    }
}
