#PARAMETERS

#simulation parameters
set simtime 1000
puts " "
puts "simulation time = $simtime seconds"
puts " "


#access link parameters
set abw 100Mb
set adel 0.10
set aqsize 1000

#bottleneck link parameters
set bnbw 40Mb
set bndel 0.05
set bnqsize 100

#TCP parameters
set minwnd 20
set maxwnd 1000

#TCP/UDP parameters
set smallsize 500
set largesize 1500

#create random number generator
set rng [new RNG]
$rng seed predef 2

#SIMULATOR OBJECT
set nssim [new Simulator]

set trace_all [open q2-out.all w]
#$nssim trace-all $trace_all




#TOPOLOGY

#create 4 nodes
set na1 [$nssim node]
set na2 [$nssim node]
set na3 [$nssim node]
set nb1 [$nssim node]
set nb2 [$nssim node]


#create duplex links between nodes
$nssim duplex-link $na1 $nb1 $abw $adel DropTail
$nssim duplex-link $na2 $nb1 $abw $adel DropTail
$nssim duplex-link $na3 $nb1 $abw $adel DropTail
$nssim duplex-link $nb1 $nb2 $bnbw $bndel DropTail


#set queue sizes
$nssim queue-limit $na1 $nb1 $aqsize
$nssim queue-limit $na2 $nb1 $aqsize
$nssim queue-limit $na3 $nb1 $aqsize
$nssim queue-limit $nb1 $nb2 $bnqsize



#SOURCES AND SINKS

set imax 25

puts "=== Sources and nodes ===="
puts "Source CC segmentsize window node : arrivals drops\n"
for {set i 1} {$i < $imax} {incr i} {
    if { $i % 3 == 1 } {
	set snode $na1
	set sn($i) 1
    } elseif { $i % 3 == 2 } {
	set snode $na2
	set sn($i) 2
    } else {
	set snode $na3
	set sn($i) 3
    }
    if { $i % 2 == 0 } {
	set tcpVariant "TCP"
	set cc($i) "Tahoe"
    } else {
	set tcpVariant "TCP/Fack"
	set cc($i) "Fack"
    }
    if { ($i-1) % 12  < 6 } {
	set segmentsize $smallsize
    } else {
	set segmentsize $largesize
    }
    if { $i < 13 } {
	set maxwindow $minwnd
    } else {
	set maxwindow $maxwnd
    }
    set cc($i) "$cc($i) $segmentsize $maxwindow"
    set tcp($i) [$nssim create-connection $tcpVariant $snode TCPSink/Sack1 $nb2 $i]
    set ftp($i) [new Application/FTP]
    $ftp($i) attach-agent $tcp($i)
    $tcp($i) set packetSize_ $segmentsize
    $tcp($i) set window_ $maxwindow
    puts "Source $i node $sn($i) $cc($i)"
}



#TRACING AND MONITORING

puts "=== Simulation starts ===\n"

#set monitoring
set fmon [$nssim makeflowmon Fid]
$nssim attach-fmon [$nssim link $nb1 $nb2] $fmon

proc flowstats {} {
    global fmon imax cc sn trace_all
    close $trace_all
    set fclassifier [$fmon classifier]
    for {set i 1} {$i < $imax} {incr i} {
    set flow($i) [$fclassifier lookup auto 0 0 $i]
    set parrtcp($i) [$flow($i) set parrivals_]
    set pdropstcp($i) [$flow($i) set pdrops_]
    puts "TCP $i $cc($i) $sn($i) : $parrtcp($i) $pdropstcp($i)"
    }    
puts " "
set parr [$fmon set parrivals_]
    set pdrops [$fmon set pdrops_]
    puts "All : $parr $pdrops"

}




#set tracing



#RUNNING SIMULATION

#schedule events for ns2
for {set i 1} {$i < $imax} {incr i} {
    $nssim at [expr $i*0.094] "$ftp($i) start"
}
$nssim at $simtime "flowstats"
$nssim at $simtime "$nssim halt"

#run and end the simulation
$nssim run





exit 0
