#Create a simulator object
set ns [new Simulator]

#Open the nam trace file
set nf [open cbr.nam w]
$ns namtrace-all $nf

#Open the output files
set f0 [open cbrloss.tr w]



#Define a 'finish' procedure
proc finish {} {
        global ns nf
        $ns flush-trace
	#Close the trace file
        close $nf
	#Execute nam on the trace file
        exec nam out.nam &
        exit 0
}




proc record {} {
        global loss f0 
        #Get an instance of the simulator
        set ns [Simulator instance]
        #Set the time after which the procedure should be called again
        set time 0.5
        #How many bytes have been received by the traffic sinks?
        set bw0 [$loss set bytes_]

        #Get the current time
        set now [$ns now]

        #Calculate the bandwidth (in MBit/s) and write it to the files
        puts $f0 "$now [expr $bw0/$time*8/1000000]"
       
        #Reset the bytes_ values on the traffic sinks
        $loss set bytes_ 0
       
        #Re-schedule the procedure
        $ns at [expr $now+$time] "record"
}






#Create two nodes
set n0 [$ns node]
set n1 [$ns node]

#Create a duplex link between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail


#Create a UDP agent and attach it to node n0
set tcp [new Agent/UDP]
$ns attach-agent $n0 $tcp


# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 200
$cbr0 attach-agent $tcp


#Create a Null agent (a traffic sink) and attach it to node n1
set sink [new Agent/Null]
$ns attach-agent $n1 $sink


#Connect the traffic source with the traffic sink
$ns connect $tcp $sink  

set loss [new Agent/LossMonitor]
$ns attach-agent $n1 $loss
$ns connect $tcp $loss

set loss_module [new ErrorModel]
$loss_module  set rate_ 0.2
$loss_module ranvar [new RandomVariable/Uniform]
$loss_module drop-target [new Agent/Null]
$ns lossmodel $loss_module $n0 $n1


#Schedule events for the CBR agent
$ns at 0 "record"
$ns at 0.5 "$cbr0 start"
$ns at 20 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 21 "finish"

#Run the simulation
$ns run
