#Create an instance of the Simulator class

set ns [new Simulator]

#Add dynamic routing

$ns rtproto DV

#Define blue color for the first data flow

$ns color 1 Blue

#Add seven nodes n0, to n6 with a for loop

for {set i 0} {$i < 7} {incr i} {
set n($i) [$ns node]
}


#Export packet traces

set f [open d2_p1.tr w]
$ns trace-all $f

#Export nam traces

set nf [open d2_p1.nam w]
$ns namtrace-all $nf

#Create a duplex link (n0-n1)
#with 2Mb bandwidth and 10ms delay per link,
#including a DropTail queue for each link

$ns duplex-link $n(0) $n(1) 2Mb 10ms DropTail

#Create 5 (duplex) circular links (n1 to n5)
#with 2Mb bandwidth and 10ms delay per link,
#including a DropTail queue for each link

$ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 2Mb 10ms DropTail
$ns duplex-link $n(3) $n(4) 2Mb 10ms DropTail
$ns duplex-link $n(4) $n(5) 2Mb 10ms DropTail
$ns duplex-link $n(5) $n(1) 2Mb 10ms DropTail

#Create a duplex link (n4-n6)
#with 2Mb bandwidth and 10ms delay per link,
#including a DropTail queue for each link

$ns duplex-link $n(4) $n(6) 2Mb 10ms DropTail

#Monitor the queue for link 4-6 for NAM

$ns duplex-link-op $n(4) $n(6) queuePos 0.5

#Set error model on link 2-3 equal to 10%

set loss_module [new ErrorModel]
$loss_module set rate_ 0.1
$loss_module ranvar [new RandomVariable/Uniform]
$loss_module drop-target [new Agent/Null]
$ns lossmodel $loss_module $n(2) $n(3)

#Create a UDP connection (udp0) and attach it to node n(0)

set udp0 [new Agent/UDP]
$udp0 set class_ 1
$ns attach-agent $n(0) $udp0

#Create a CBR traffic source (cbr0) and attach it to udp0
#Set packetSize = 200 bytes
#Set interval time = 0.001 secs (stored in int variable)

set cbr0 [new Application/Traffic/CBR]
set int 0.001
$cbr0 set packetSize_ 200
$cbr0 set interval_ $int
$cbr0 attach-agent $udp0

#Create a Null agent (null0) and attach it to node n(6)

set null0 [new Agent/Null]
$ns attach-agent $n(6) $null0

#Connect udp0 and null0 agents

$ns connect $udp0 $null0

#Set the link n(4)-n(5) down for 1 sec between 2.0 and 3.0 sec

$ns rtmodel-at 2.0 down $n(4) $n(5)
$ns rtmodel-at 3.0 up $n(4) $n(5) 

#Monitor queue 4-6 and store traces in queue.tr for each 0.1 sec

set qmon [$ns monitor-queue $n(4) $n(6) [open queue_p1.tr w] 0.1]
[$ns link $n(4) $n(6)] queue-sample-timeout

#Schedule event cbr0 to start at 0.1 secs and to stop at 4.9 secs

$ns at 0.1 "$cbr0 start"
$ns at 4.9 "$cbr0 stop"

#Call the procedure "finish" at 5.0 secs

$ns at 5.0 "finish"

#Add a procedure, called "finish"

proc finish {} {
	global ns f nf
        $ns flush-trace
        close $nf
	close $f
        exit 0
}

#Start the simulation

$ns run
