File: cl_demo.c

package info (click to toggle)
ezquake 2.2%2Bgit20150324-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 6,996 kB
  • ctags: 16,582
  • sloc: ansic: 143,243; makefile: 339; tcl: 107; sh: 28
file content (5035 lines) | stat: -rw-r--r-- 123,845 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
/*
Copyright (C) 1996-1997 Id Software, Inc.
Copyright (C) 2007-2015 ezQuake team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the included (GNU.txt) GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include <time.h>
#include "quakedef.h"
#include "movie.h"
#include "menu_demo.h"
#include "qtv.h"
#include "gl_model.h"
#include "gl_local.h"
#include "tr_types.h"
#include "teamplay.h"
#include "pmove.h"
#include "fs.h"
#include "hash.h"
#include "vfs.h"
#include "utils.h"
#include "crc.h"
#include "logging.h"
#include "version.h"
#include "demo_controls.h"
#include "mvd_utils.h"
#ifndef CLIENTONLY
#include "server.h"
#endif

/* FIXME Move these to a proper header file and included that */
void Cam_Unlock(void);

// TODO: Create states for demo_recording, demo_playback, and so on and put all related vars into these.
// Right now with global vars for everything is a mess. Also renaming some of the time vars to be less
// confusing is probably good. demotime, olddemotime, nextdemotime, prevtime...

typedef struct demo_state_s
{
	float		olddemotime;
	float		nextdemotime;

	double		bufferingtime;

	sizebuf_t	democache;
	qbool		democache_available;

	#ifdef _WIN32
	qbool		qwz_unpacking;
	qbool		qwz_playback;
	qbool		qwz_packing;
	char		tempqwd_name[256];
	#endif // _WIN32
} demo_state_t;

float olddemotime, nextdemotime; // TODO: Put in a demo struct.

double bufferingtime; // if we stream from QTV, this is non zero when we trying fill our buffer

//
// Vars related to QIZMO compressed demos.
// (Only available in Win32 since we need to use an external app)
//
#ifdef _WIN32
static qbool	qwz_unpacking = false;
static qbool	qwz_playback = false;
static qbool	qwz_packing = false;

#define QWZ_DECOMPRESSION_TIMEOUT_MS	10000

static void		OnChange_demo_format(cvar_t*, char*, qbool*);
cvar_t			demo_format = {"demo_format", "qwz", 0, OnChange_demo_format};

static HANDLE hQizmoProcess = NULL;
static char tempqwd_name[256] = {0}; // This file must be deleted after playback is finished.
int CL_Demo_Compress(char*);
#endif

static vfsfile_t *CL_Open_Demo_File(char *name, qbool searchpaks, char **fullpath);
static void OnChange_demo_dir(cvar_t *var, char *string, qbool *cancel);
cvar_t demo_dir = {"demo_dir", "", 0, OnChange_demo_dir};
cvar_t demo_benchmarkdumps = {"demo_benchmarkdumps", "1"};
cvar_t cl_startupdemo = {"cl_startupdemo", ""};

// Used to save track status when rewinding.
static int rewind_trackslots[4];
static int rewind_duel_track1 = 0;
static int rewind_duel_track2 = 0;
static int rewind_spec_track = 0;
static vec3_t rewind_angle;
static vec3_t rewind_pos;

char Demos_Get_Trackname(void);
static void CL_DemoPlaybackInit(void);

char *CL_DemoDirectory(void);
void CL_Demo_Jump_Status_Check (void);

//=============================================================================
//								DEMO WRITING
//=============================================================================

static FILE *recordfile = NULL;		// File used for recording demos. // TODO: Put in a demo struct.
static float playback_recordtime;	// Time when in demo playback and recording. // TODO: Put in a demo struct.

#define DEMORECORDTIME	((float) (cls.demoplayback ? playback_recordtime : cls.realtime))
#define DEMOCACHE_MINSIZE	(2 * 1024 * 1024)
#define DEMOCACHE_FLUSHSIZE	(1024 * 1024)

static sizebuf_t democache; // TODO: Put in a demo struct.
static qbool democache_available = false;	// Has the user opted to use a demo cache? // TODO: Put in a demo struct.

//
// Opens a demo for writing.
//
static qbool CL_Demo_Open(char *name)
{
	// Clear the demo cache and open the demo file for writing.
	if (democache_available)
		SZ_Clear(&democache);
	recordfile = fopen (name, "wb");
	return recordfile ? true : false;
}

//
// Closes a demo.
//
static void CL_Demo_Close(void)
{
	// Flush the demo cache and close the demo file.
	if (democache_available)
		fwrite(democache.data, democache.cursize, 1, recordfile);
	fclose(recordfile);
	recordfile = NULL;
}

//
// Writes a chunk of data to the currently opened demo record file.
//
static void CL_Demo_Write(void *data, int size)
{
	if (democache_available)
	{
		//
		// Write to the demo cache.
		//
		if (size > democache.maxsize)
		{
			// The size of the data to be written is bigger than the demo cache, fatal error.
			Sys_Error("CL_Demo_Write: size > democache.maxsize");
		}
		else if (size > democache.maxsize - democache.cursize)
		{
			//
			// Flushes part of the demo cache (enough to fit the new data) if it has been overflowed.
			//
			int overflow_size = size - (democache.maxsize - democache.cursize);

			Com_Printf("Warning: democache overflow...flushing\n");

			if (overflow_size <= DEMOCACHE_FLUSHSIZE)
				overflow_size = min(DEMOCACHE_FLUSHSIZE, democache.cursize);

			// Write as much data as overflowed from the current
			// contents of the demo cache to the demo file.
			fwrite(democache.data, overflow_size, 1, recordfile);

			// Shift the cache contents (remove what was just written).
			memmove(democache.data, democache.data + overflow_size, democache.cursize - overflow_size);
			democache.cursize -= overflow_size;

			// Write the new data to the demo cache.
			SZ_Write(&democache, data, size);
		}
		else
		{
			// Write to the demo cache.
			SZ_Write(&democache, data, size);
		}
	}
	else
	{
		//
		// Write directly to the file.
		//
		fwrite (data, size, 1, recordfile);
	}
}

//
// Flushes any pending write operations to the recording file.
//
static void CL_Demo_Flush(void)
{
	fflush(recordfile);
}

//
// Writes a user cmd to the open demo file.
//
void CL_WriteDemoCmd (usercmd_t *pcmd)
{
	int i;
	float fl, t[3];
	byte c;
	usercmd_t cmd;

	// Write the current time.
	fl = LittleFloat(DEMORECORDTIME);
	CL_Demo_Write(&fl, sizeof(fl));

	// Write the message type. A user cmd (movement and such).
	c = dem_cmd;
	CL_Demo_Write(&c, sizeof(c));

	// Correct for byte order, bytes don't matter.
	cmd = *pcmd;

	// Convert the movement angles / vectors to the correct byte order.
	for (i = 0; i < 3; i++)
		cmd.angles[i] = LittleFloat(cmd.angles[i]);
	cmd.forwardmove = LittleShort(cmd.forwardmove);
	cmd.sidemove    = LittleShort(cmd.sidemove);
	cmd.upmove      = LittleShort(cmd.upmove);

	// Write the actual user command to the demo.
	CL_Demo_Write(&cmd, sizeof(cmd));

	// Write the view angles with the correct byte order.
	t[0] = LittleFloat (cl.viewangles[0]);
	t[1] = LittleFloat (cl.viewangles[1]);
	t[2] = LittleFloat (cl.viewangles[2]);
	CL_Demo_Write(t, sizeof(t));

	// Flush the changes to file.
	CL_Demo_Flush();
}

//
// Dumps the current net message, prefixed by the length and view angles
//
void CL_WriteDemoMessage (sizebuf_t *msg)
{
	int len;
	float fl;
	byte c;

	// Write time of cmd.
	fl = LittleFloat(DEMORECORDTIME);
	CL_Demo_Write(&fl, sizeof(fl));

	// Write the message type. Net message.
	c = dem_read;
	CL_Demo_Write(&c, sizeof(c));

	// Write the length of the data.
	len = LittleLong (msg->cursize);
	CL_Demo_Write(&len, 4);

	// Write the data.
	CL_Demo_Write(msg->data, msg->cursize);

	// Flush the changes to the recording file.
	CL_Demo_Flush();

	// Request pings from the net chan if the user has set it.
    {
        extern void Request_Pings(void);
        extern cvar_t demo_getpings;

        if (demo_getpings.value)
            Request_Pings();
    }
}


//
// Writes the entities list to a demo.
//
void CL_WriteDemoEntities (void)
{
	int ent_index, ent_total;
	entity_state_t *ent;
	
	// Write the ID byte for a delta entity operation to the demo.
	MSG_WriteByte (&cls.demomessage, svc_packetentities);

	// Get the entities list from the frame.
	ent = cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK].packet_entities.entities;
	ent_total = cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK].packet_entities.num_entities;

	// Write all the entity changes since last packet entity message.
	for (ent_index = 0; ent_index < ent_total; ent_index++, ent++)
		MSG_WriteDeltaEntity (&cl_entities[ent->number].baseline, ent, &cls.demomessage, true);

	// End of packetentities.
	MSG_WriteShort (&cls.demomessage, 0);
}

//
// Writes a startup demo message to the demo being recorded.
//
static void CL_WriteStartupDemoMessage (sizebuf_t *msg, int seq)
{
	int len, i;
	float fl;
	byte c;

	// Don't write, we're not recording.
	if (!cls.demorecording)
		return;

	// Write the time.
	fl = LittleFloat(DEMORECORDTIME);
	CL_Demo_Write(&fl, sizeof(fl));

	// Message type = net message.
	c = dem_read;
	CL_Demo_Write(&c, sizeof(c));

	// Write the length of the message.
	len = LittleLong (msg->cursize + 8);
	CL_Demo_Write(&len, 4);

	// Write the sequence number twice. Why?
	i = LittleLong(seq);
	CL_Demo_Write(&i, 4);
	CL_Demo_Write(&i, 4);

	// Write the actual message data to the demo.
	CL_Demo_Write(msg->data, msg->cursize);

	// Flush the message to file.
	CL_Demo_Flush();
}

//
// Writes a set demo message. The outgoing / incoming sequence at the start of the demo.
// This is only written once at startup.
//
static void CL_WriteSetDemoMessage (void)
{
	int len;
	float fl;
	byte c;

	// We're not recording.
	if (!cls.demorecording)
		return;

	// Write the demo time.
	fl = LittleFloat(DEMORECORDTIME);
	CL_Demo_Write(&fl, sizeof(fl));

	// Write the message type.
	c = dem_set;
	CL_Demo_Write(&c, sizeof(c));

	// Write the outgoing / incoming sequence.
	len = LittleLong(cls.netchan.outgoing_sequence);
	CL_Demo_Write(&len, 4);
	len = LittleLong(cls.netchan.incoming_sequence);
	CL_Demo_Write(&len, 4);

	// Flush the demo file to disk.
	CL_Demo_Flush();
}

// FIXME: same as in sv_user.c. Move to common.c?
static char *TrimModelName (const char *full)
{
	static char shortn[MAX_QPATH];
	int len;

	if (!strncmp(full, "progs/", 6) && !strchr(full + 6, '/'))
		strlcpy (shortn, full + 6, sizeof(shortn));		// strip progs/
	else
		strlcpy (shortn, full, sizeof(shortn));

	len = strlen(shortn);
	if (len > 4 && !strcmp(shortn + len - 4, ".mdl")
		&& strchr(shortn, '.') == shortn + len - 4)
	{	// strip .mdl
		shortn[len - 4] = '\0';
	}

	return shortn;
}

void CL_WriteServerdata (sizebuf_t *msg)
{
	int ignore_extensions;

	MSG_WriteByte (msg, svc_serverdata);

	// Maintain demo compatibility.
	ignore_extensions = 0;
#ifdef FTE_PEXT_CHUNKEDDOWNLOADS
	// this is OK, since download data skipped anyway
	ignore_extensions |= FTE_PEXT_CHUNKEDDOWNLOADS;
#endif
#ifdef FTE_PEXT_256PACKETENTITIES
	// this is probably OK, since engine should ignore more than 64 entities if not supported.
	ignore_extensions |= FTE_PEXT_256PACKETENTITIES;
#endif

	#ifdef PROTOCOL_VERSION_FTE
	if (cls.fteprotocolextensions &~ ignore_extensions)
	{
		MSG_WriteLong (msg, PROTOCOL_VERSION_FTE);
		MSG_WriteLong (msg, cls.fteprotocolextensions);
	}
	#endif // PROTOCOL_VERSION_FTE

	// Maintain demo pseudo-compatibility,
	ignore_extensions = 0;

	#ifdef PROTOCOL_VERSION_FTE2
	if (cls.fteprotocolextensions2 & ~ignore_extensions)
	{
		MSG_WriteLong (msg, PROTOCOL_VERSION_FTE2);
		MSG_WriteLong (msg, cls.fteprotocolextensions2);
	}
	#endif // PROTOCOL_VERSION_FTE2

	MSG_WriteLong (msg, PROTOCOL_VERSION);
	MSG_WriteLong (msg, cl.servercount);
	MSG_WriteString (msg, cls.gamedirfile);

	// Write if we're a spectator or not.
	if (cl.spectator)
		MSG_WriteByte (msg, cl.playernum | 128);
	else
		MSG_WriteByte (msg, cl.playernum);

	// Send full levelname.
	MSG_WriteString (msg, cl.levelname);

	// Send the movevars.
	MSG_WriteFloat(msg, movevars.gravity);
	MSG_WriteFloat(msg, movevars.stopspeed);
	MSG_WriteFloat(msg, cl.maxspeed);
	MSG_WriteFloat(msg, movevars.spectatormaxspeed);
	MSG_WriteFloat(msg, movevars.accelerate);
	MSG_WriteFloat(msg, movevars.airaccelerate);
	MSG_WriteFloat(msg, movevars.wateraccelerate);
	MSG_WriteFloat(msg, movevars.friction);
	MSG_WriteFloat(msg, movevars.waterfriction);
	MSG_WriteFloat(msg, cl.entgravity);
}

//
// Write startup data to demo (called when demo started and cls.state == ca_active)
//
static void CL_WriteStartupData (void)
{
	sizebuf_t buf;
	char buf_data[MAX_MSGLEN * 2], *s;
	int n, i, j, seq = 1;
	entity_t *ent;
	entity_state_t *es, blankes;
	player_info_t *player;

	//
	// Serverdata
	// Send the info about the new client to all connected clients.
	//

	// Init a buffer that we write to before writing to the file.
	SZ_Init (&buf, (byte *) buf_data, sizeof(buf_data));

	//
	// Send the serverdata.
	//
	CL_WriteServerdata (&buf);

	// Send music.
	MSG_WriteByte (&buf, svc_cdtrack);
	MSG_WriteByte (&buf, 0); // None in demos

	// Send server info string.
	MSG_WriteByte (&buf, svc_stufftext);
	MSG_WriteString (&buf, va("fullserverinfo \"%s\"\n", cl.serverinfo));

	// Flush the buffer to the demo file and then clear it.
	CL_WriteStartupDemoMessage (&buf, seq++);
	SZ_Clear (&buf);

	//
	// Write the soundlist.
	//
	MSG_WriteByte (&buf, svc_soundlist);
	MSG_WriteByte (&buf, 0);

	// Loop through all sounds and write them to the demo.
	n = 0;
	s = cl.sound_name[n + 1];
	while (*s)
	{
		// Write the sound name to the buffer.
		MSG_WriteString (&buf, s);

		// If the buffer is half full, flush it.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			// End of the partial sound list.
			MSG_WriteByte (&buf, 0);

			// Write how many sounds we've listed so far.
			MSG_WriteByte (&buf, n);

			// Flush the buffer to the demo file and clear the buffer.
			CL_WriteStartupDemoMessage (&buf, seq++);
			SZ_Clear (&buf);

			// Start on a new sound list and continue writing the
			// remaining sounds.
			MSG_WriteByte (&buf, svc_soundlist);
			MSG_WriteByte (&buf, n + 1);
		}

		n++;
		s = cl.sound_name[n+1];
	}

	// If the buffer isn't empty flush and clear it.
	if (buf.cursize)
	{
		MSG_WriteByte (&buf, 0);
		MSG_WriteByte (&buf, 0);
		CL_WriteStartupDemoMessage (&buf, seq++);
		SZ_Clear (&buf);
	}

	// Vwep modellist
	if (cl.vwep_enabled && cl.vw_model_name[0][0]) 
	{
		// Send VWep precaches
		// pray we don't overflow
		char ss[1024] = "//vwep ";
		for (i = 0; i < MAX_VWEP_MODELS; i++) {
			s = cl.vw_model_name[i];
			if (!*s)
				break;
			if (i > 0)
				strlcat (ss, " ", sizeof(ss));
			strlcat (ss, TrimModelName(s), sizeof(ss));
		}
		strlcat (ss, "\n", sizeof(ss));
		if (strlen(ss) < sizeof(ss)-1)		// Didn't overflow?
		{
			MSG_WriteByte (&buf, svc_stufftext);
			MSG_WriteString (&buf, ss);
		}
	}
	// Don't bother flushing, the vwep list is not that large (I hope).

	//
	// Modellist.
	//
	MSG_WriteByte (&buf, svc_modellist);
	MSG_WriteByte (&buf, 0);

	// Loop through the models
	n = 0;
	s = cl.model_name[n + 1];
	while (*s)
	{
		// Write the model name to the buffer.
		MSG_WriteString (&buf, s);

		// If the buffer is half full, flush it.
		if (buf.cursize	> MAX_MSGLEN / 2)
		{
			// End of partial model list.
			MSG_WriteByte (&buf, 0);

			// Write how many models we've written so far.
			MSG_WriteByte (&buf, n);

			// Flush the model list to the demo file and clear the buffer.
			CL_WriteStartupDemoMessage (&buf, seq++);
			SZ_Clear (&buf);

			// Start on a new partial model list and continue.
			MSG_WriteByte (&buf, svc_modellist);
			MSG_WriteByte (&buf, n + 1);
		}
		n++;
		s = cl.model_name[n + 1];
	}

	// Flush the buffer if it's not empty.
	if (buf.cursize)
	{
		MSG_WriteByte (&buf, 0);
		MSG_WriteByte (&buf, 0);
		CL_WriteStartupDemoMessage (&buf, seq++);
		SZ_Clear (&buf);
	}

	//
	// Write static entities.
	//
	for (i = 0; i < cl.num_statics; i++)
	{
		// Get the next static entity.
		ent = cl_static_entities + i;

		// Write ID for static entities.
		MSG_WriteByte (&buf, svc_spawnstatic);

		// Find if the model is precached or not.
		for (j = 1; j < MAX_MODELS; j++)
		{
			if (ent->model == cl.model_precache[j])
				break;
		}

		// Write if the model is precached.
		if (j == MAX_MODELS)
			MSG_WriteByte (&buf, 0);
		else
			MSG_WriteByte (&buf, j);

		// Write the entities frame and skin number.
		MSG_WriteByte (&buf, ent->frame);
		MSG_WriteByte (&buf, 0);
		MSG_WriteByte (&buf, ent->skinnum);

		// Write the coordinate and angles.
		for (j = 0; j < 3; j++)
		{
			MSG_WriteCoord (&buf, ent->origin[j]);
			MSG_WriteAngle (&buf, ent->angles[j]);
		}

		// Flush the buffer if it's half full.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			CL_WriteStartupDemoMessage (&buf, seq++);
			SZ_Clear (&buf);
		}
	}

	// spawnstaticsound
	for (i = 0; i < cl.num_static_sounds; i++) 
	{
		static_sound_t *ss = &cl.static_sounds[i];
		MSG_WriteByte (&buf, svc_spawnstaticsound);
		for (j = 0; j < 3; j++)
			MSG_WriteCoord (&buf, ss->org[j]);
		MSG_WriteByte (&buf, ss->sound_num);
		MSG_WriteByte (&buf, ss->vol);
		MSG_WriteByte (&buf, ss->atten);

		if (buf.cursize > MAX_MSGLEN/2) 
		{
			CL_WriteStartupDemoMessage (&buf, seq++);
			SZ_Clear (&buf);
		}
	}

	//
	// Write entity baselines.
	//
	memset(&blankes, 0, sizeof(blankes));
	for (i = 0; i < CL_MAX_EDICTS; i++)
	{
		es = &cl_entities[i].baseline;

		//
		// If the entity state isn't blank write it to the buffer.
		//
		if (memcmp(es, &blankes, sizeof(blankes)))
		{
			// Write ID.
			MSG_WriteByte (&buf, svc_spawnbaseline);
			MSG_WriteShort (&buf, i);

			// Write model info.
			MSG_WriteByte (&buf, es->modelindex);
			MSG_WriteByte (&buf, es->frame);
			MSG_WriteByte (&buf, es->colormap);
			MSG_WriteByte (&buf, es->skinnum);

			// Write coordinates and angles.
			for (j = 0; j < 3; j++)
			{
				MSG_WriteCoord(&buf, es->origin[j]);
				MSG_WriteAngle(&buf, es->angles[j]);
			}

			// Flush to demo file if buffer is half full.
			if (buf.cursize > MAX_MSGLEN / 2)
			{
				CL_WriteStartupDemoMessage (&buf, seq++);
				SZ_Clear (&buf);
			}
		}
	}

	// Write spawn information into the clients console buffer.
	MSG_WriteByte (&buf, svc_stufftext);
	MSG_WriteString (&buf, va("cmd spawn %i 0\n", cl.servercount));

	// Flush buffer to demo file.
	if (buf.cursize)
	{
		CL_WriteStartupDemoMessage (&buf, seq++);
		SZ_Clear (&buf);
	}

	//
	// Send current status of all other players.
	//
	for (i = 0; i < MAX_CLIENTS; i++)
	{
		player = cl.players + i;

		// Frags.
		MSG_WriteByte (&buf, svc_updatefrags);
		MSG_WriteByte (&buf, i);
		MSG_WriteShort (&buf, player->frags);

		// Ping.
		MSG_WriteByte (&buf, svc_updateping);
		MSG_WriteByte (&buf, i);
		MSG_WriteShort (&buf, player->ping);

		// Packet loss.
		MSG_WriteByte (&buf, svc_updatepl);
		MSG_WriteByte (&buf, i);
		MSG_WriteByte (&buf, player->pl);

		// Entertime.
		MSG_WriteByte (&buf, svc_updateentertime);
		MSG_WriteByte (&buf, i);
		MSG_WriteFloat (&buf, cls.realtime - player->entertime);

		// User ID and user info.
		MSG_WriteByte (&buf, svc_updateuserinfo);
		MSG_WriteByte (&buf, i);
		MSG_WriteLong (&buf, player->userid);
		MSG_WriteString (&buf, player->userinfo);

		// Flush buffer to demo file.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			CL_WriteStartupDemoMessage (&buf, seq++);
			SZ_Clear (&buf);
		}
	}

	// Send all current light styles.
	for (i = 0; i < MAX_LIGHTSTYLES; i++)
	{
		// Don't send empty lightstyle strings.
		if (!cl_lightstyle[i].length)
			continue;

		MSG_WriteByte (&buf, svc_lightstyle);
		MSG_WriteByte (&buf, (char)i);
		MSG_WriteString (&buf, cl_lightstyle[i].map);
	}

	for (i = 0; i < MAX_CL_STATS; i++)
	{
		// No need to send zero values.
		if (!cl.stats[i])
			continue;

		// Write the current players user stats.
		if (cl.stats[i] >= 0 && cl.stats[i] <= 255)
		{
			MSG_WriteByte (&buf, svc_updatestat);
			MSG_WriteByte (&buf, i);
			MSG_WriteByte (&buf, cl.stats[i]);
		}
		else
		{
			MSG_WriteByte (&buf, svc_updatestatlong);
			MSG_WriteByte (&buf, i);
			MSG_WriteLong (&buf, cl.stats[i]);
		}

		// Flush buffer to demo file.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			CL_WriteStartupDemoMessage (&buf, seq++);
			SZ_Clear (&buf);
		}
	}

	// Get the client to check and download skins
	// when that is completed, a begin command will be issued.
	MSG_WriteByte (&buf, svc_stufftext);
	MSG_WriteString (&buf, va("skins\n"));

	CL_WriteStartupDemoMessage (&buf, seq++);

	CL_WriteSetDemoMessage();
}

//=========================================================
// MVD demo writing
//=========================================================

static FILE *mvdrecordfile = NULL;
static char mvddemoname[2 * MAX_OSPATH] = {0};

static void CL_MVD_DemoWrite (void *data, int len)
{
	if (!mvdrecordfile)
		return;

	fwrite(data, len, 1, mvdrecordfile);
}

// ====================
// CL_WriteRecordMVDMessage
// ====================
static void CL_WriteRecordMVDMessage (sizebuf_t *msg)
{
	int len;
	byte c;

	if (!cls.mvdrecording)
		return;

	if (!msg->cursize)
		return;

	c = 0;
	CL_MVD_DemoWrite (&c, sizeof(c));

	c = dem_all;
	CL_MVD_DemoWrite (&c, sizeof(c));

	len = LittleLong (msg->cursize);
	CL_MVD_DemoWrite (&len, 4);

	CL_MVD_DemoWrite (msg->data, msg->cursize);
}

// ====================
// CL_WriteRecordMVDStatsMessage
// ====================
static void CL_WriteRecordMVDStatsMessage (sizebuf_t *msg, int client)
{
	int len;
	byte c;

	if (!cls.mvdrecording)
		return;

	if (!msg->cursize)
		return;

	if (client < 0 || client >= MAX_CLIENTS)
		return;

	c = 0;
	CL_MVD_DemoWrite (&c, sizeof(c));

	c = dem_stats | (client << 3) ; // msg "type" and "to" incapsulated in one byte
	CL_MVD_DemoWrite (&c, sizeof(c));

	len = LittleLong (msg->cursize);
	CL_MVD_DemoWrite (&len, 4);

	CL_MVD_DemoWrite (msg->data, msg->cursize);
}

// TODO: Split this up?
void CL_WriteMVDStartupData(void)
{
	sizebuf_t	buf;
	unsigned char buf_data[MAX_MSGLEN * 4];
	player_info_t *player;
	entity_state_t *es, blankes;
	entity_t *ent;
	int i, j, n;
	char *s;

	// Serverdata
	// send the info about the new client to all connected clients
	SZ_Init (&buf, buf_data, sizeof(buf_data));

	// send the serverdata

	MSG_WriteByte (&buf, svc_serverdata);

	#ifdef PROTOCOL_VERSION_FTE
	if (cls.fteprotocolextensions)
	{
		MSG_WriteLong (&buf, PROTOCOL_VERSION_FTE);
		MSG_WriteLong (&buf, cls.fteprotocolextensions);
	}
	#endif // PROTOCOL_VERSION_FTE

	#ifdef PROTOCOL_VERSION_FTE2
	if (cls.fteprotocolextensions2)
	{
		MSG_WriteLong (&buf, PROTOCOL_VERSION_FTE2);
		MSG_WriteLong (&buf, cls.fteprotocolextensions2);
	}
	#endif // PROTOCOL_VERSION_FTE2

	MSG_WriteLong (&buf, PROTOCOL_VERSION);
	MSG_WriteLong (&buf, cl.servercount);

	//
	// Gamedir.
	//

	s = cls.gamedirfile; // FIXME: or do we need to take a look in serverinfo?
	if (!s[0])
		s = "qw"; // If empty use "qw" gamedir

	MSG_WriteString (&buf, s);

	MSG_WriteFloat (&buf, cls.demotime); // FIXME: not sure

	// Send full levelname.
	MSG_WriteString (&buf, cl.levelname);

	// Send the movevars.
	MSG_WriteFloat(&buf, movevars.gravity);
	MSG_WriteFloat(&buf, movevars.stopspeed);
	MSG_WriteFloat(&buf, movevars.maxspeed);
	MSG_WriteFloat(&buf, movevars.spectatormaxspeed);
	MSG_WriteFloat(&buf, movevars.accelerate);
	MSG_WriteFloat(&buf, movevars.airaccelerate);
	MSG_WriteFloat(&buf, movevars.wateraccelerate);
	MSG_WriteFloat(&buf, movevars.friction);
	MSG_WriteFloat(&buf, movevars.waterfriction);
	MSG_WriteFloat(&buf, movevars.entgravity);

	// Send music.
	MSG_WriteByte (&buf, svc_cdtrack);
	MSG_WriteByte (&buf, 0); // None in demos.

	// Send server info string.
	MSG_WriteByte (&buf, svc_stufftext);
	MSG_WriteString (&buf, va("fullserverinfo \"%s\"\n", cl.serverinfo));

	// Flush packet.
	CL_WriteRecordMVDMessage (&buf);
	SZ_Clear (&buf);

	//
	// Soundlist.
	//
	MSG_WriteByte (&buf, svc_soundlist);
	MSG_WriteByte (&buf, 0);

	n = 0;
	s = cl.sound_name[n + 1];
	while (*s)
	{
		MSG_WriteString (&buf, s);
		if (buf.cursize > MAX_MSGLEN/2)
		{
			MSG_WriteByte (&buf, 0);
			MSG_WriteByte (&buf, n);
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
			MSG_WriteByte (&buf, svc_soundlist);
			MSG_WriteByte (&buf, n + 1);
		}
		n++;
		s = cl.sound_name[n + 1];
	}

	if (buf.cursize)
	{
		MSG_WriteByte (&buf, 0);
		MSG_WriteByte (&buf, 0);
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// Modellist.
	//
	MSG_WriteByte (&buf, svc_modellist);
	MSG_WriteByte (&buf, 0);

	n = 0;
	s = cl.model_name[n+1];
	while (*s)
	{
		MSG_WriteString (&buf, s);
		if (buf.cursize > MAX_MSGLEN/2)
		{
			MSG_WriteByte (&buf, 0);
			MSG_WriteByte (&buf, n);
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
			MSG_WriteByte (&buf, svc_modellist);
			MSG_WriteByte (&buf, n + 1);
		}
		n++;
		s = cl.model_name[n+1];
	}

	if (buf.cursize)
	{
		MSG_WriteByte (&buf, 0);
		MSG_WriteByte (&buf, 0);
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// Write static entities.
	//
	for (i = 0; i < cl.num_statics; i++)
	{
		// Get the next static entity.
		ent = cl_static_entities + i;

		// Write ID for static entities.
		MSG_WriteByte (&buf, svc_spawnstatic);

		// Find if the model is precached or not.
		for (j = 1; j < MAX_MODELS; j++)
		{
			if (ent->model == cl.model_precache[j])
				break;
		}

		// Write if the model is precached.
		if (j == MAX_MODELS)
			MSG_WriteByte (&buf, 0);
		else
			MSG_WriteByte (&buf, j);

		// Write the entities frame and skin number.
		MSG_WriteByte (&buf, ent->frame);
		MSG_WriteByte (&buf, 0);
		MSG_WriteByte (&buf, ent->skinnum);

		// Write the coordinate and angles.
		for (j = 0; j < 3; j++)
		{
			MSG_WriteCoord (&buf, ent->origin[j]);
			MSG_WriteAngle (&buf, ent->angles[j]);
		}

		// Flush the buffer if it's half full.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
		}
	}

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// Write static sounds
	//
	for (i = 0; i < cl.num_static_sounds; i++)
	{
		static_sound_t *ss = &cl.static_sounds[i];

		MSG_WriteByte (&buf, svc_spawnstaticsound);

		for (j = 0; j < 3; j++)
			MSG_WriteCoord (&buf, ss->org[j]);

		MSG_WriteByte (&buf, ss->sound_num);
		MSG_WriteByte (&buf, ss->vol);
		MSG_WriteByte (&buf, ss->atten);

		if (buf.cursize > MAX_MSGLEN/2)
		{
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
		}
	}

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// Write entity baselines.
	//
	memset(&blankes, 0, sizeof(blankes));

	for (i = 0; i < CL_MAX_EDICTS; i++)
	{
		es = &cl_entities[i].baseline;

		//
		// If the entity state isn't blank write it to the buffer.
		//
		if (memcmp(es, &blankes, sizeof(blankes)))
		{
			// Write ID.
			MSG_WriteByte (&buf, svc_spawnbaseline);
			MSG_WriteShort (&buf, i);

			// Write model info.
			MSG_WriteByte (&buf, es->modelindex);
			MSG_WriteByte (&buf, es->frame);
			MSG_WriteByte (&buf, es->colormap);
			MSG_WriteByte (&buf, es->skinnum);

			// Write coordinates and angles.
			for (j = 0; j < 3; j++)
			{
				MSG_WriteCoord(&buf, es->origin[j]);
				MSG_WriteAngle(&buf, es->angles[j]);
			}

			// Flush to demo file if buffer is half full.
			if (buf.cursize > MAX_MSGLEN / 2)
			{
				CL_WriteRecordMVDMessage (&buf);
				SZ_Clear (&buf);
			}
		}
	}

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// Send all current light styles.
	//
	for (i = 0; i < MAX_LIGHTSTYLES; i++)
	{
		// Don't send empty lightstyle strings.
		if (!cl_lightstyle[i].length)
			continue;

		MSG_WriteByte (&buf, svc_lightstyle);
		MSG_WriteByte (&buf, (char)i);
		MSG_WriteString (&buf, cl_lightstyle[i].map);

		// Flush to demo file if buffer is half full.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
		}
	}

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	MSG_WriteByte (&buf, svc_stufftext);
	MSG_WriteString (&buf, va("cmd spawn %i 0\n", cl.servercount));

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// Send current status of all other players: frags, ping, pl, enter time, userinfo, player id.
	//
	for (i = 0; i < MAX_CLIENTS; i++)
	{
		player = cl.players + i;

		// Do NOT ignore spectators here, since we need at least userinfo.

		// Frags.
		MSG_WriteByte (&buf, svc_updatefrags);
		MSG_WriteByte (&buf, i);
		MSG_WriteShort (&buf, player->frags);

		// Ping.
		MSG_WriteByte (&buf, svc_updateping);
		MSG_WriteByte (&buf, i);
		MSG_WriteShort (&buf, player->ping);

		// Packet loss.
		MSG_WriteByte (&buf, svc_updatepl);
		MSG_WriteByte (&buf, i);
		MSG_WriteByte (&buf, player->pl);

		// Entertime.
		MSG_WriteByte (&buf, svc_updateentertime);
		MSG_WriteByte (&buf, i);
		MSG_WriteFloat (&buf, cls.realtime - player->entertime);

		// User ID and user info.
		MSG_WriteByte (&buf, svc_updateuserinfo);
		MSG_WriteByte (&buf, i);
		MSG_WriteLong (&buf, player->userid);
		MSG_WriteString (&buf, player->userinfo);

		// Flush buffer to demo file.
		if (buf.cursize > MAX_MSGLEN / 2)
		{
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
		}
	}

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	//
	// This set proper model, origin, angles etc for players.
	//
	for (i = 0; i < MAX_CLIENTS; i++)
	{
		vec3_t origin, angles;
		int j, flags;
		player_state_t *state;

		player = cl.players + i;

		state = cl.frames[cl.validsequence & UPDATE_MASK].playerstate + i;

		if (!player->name[0])
			continue;

		if (player->spectator)
			continue; // Ignore spectators.

		flags =   (DF_ORIGIN << 0) | (DF_ORIGIN << 1) | (DF_ORIGIN << 2)
				| (DF_ANGLES << 0) | (DF_ANGLES << 1) | (DF_ANGLES << 2)
				| DF_EFFECTS | DF_SKINNUM 
				| ((state->flags & PF_DEAD) ? DF_DEAD : 0)
				| ((state->flags & PF_GIB)  ? DF_GIB  : 0)
				| DF_WEAPONFRAME | DF_MODEL;

		VectorCopy(state->origin, origin);
		VectorCopy(state->viewangles, angles);

		MSG_WriteByte (&buf, svc_playerinfo);
		MSG_WriteByte (&buf, i);
		MSG_WriteShort (&buf, flags);

		MSG_WriteByte (&buf, state->frame);

		for (j = 0 ; j < 3 ; j++)
			if (flags & (DF_ORIGIN << j))
				MSG_WriteCoord (&buf, origin[j]);

		for (j = 0 ; j < 3 ; j++)
			if (flags & (DF_ANGLES << j))
				MSG_WriteAngle16 (&buf, angles[j]);

		if (flags & DF_MODEL)
			MSG_WriteByte (&buf, state->modelindex);

		if (flags & DF_SKINNUM)
			MSG_WriteByte (&buf, state->skinnum);

		if (flags & DF_EFFECTS)
			MSG_WriteByte (&buf, state->effects);

		if (flags & DF_WEAPONFRAME)
			MSG_WriteByte (&buf, state->weaponframe);

		if (buf.cursize > MAX_MSGLEN/2)
		{
			CL_WriteRecordMVDMessage (&buf);
			SZ_Clear (&buf);
		}
	}

	// we really need clear buffer before sending stats
	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	// send stats
	for (i = 0; i < MAX_CLIENTS; i++)
	{
		int		*stats;
		int		j;

		player = cl.players + i;

		if (!player->name[0])
			continue;

		if (player->spectator)
			continue; // Ignore spectators.

		stats = cl.players[i].stats;

		for (j = 0; j < MAX_CL_STATS; j++)
		{
			if (stats[j] >= 0 && stats[j] <= 255)
			{
				MSG_WriteByte(&buf, svc_updatestat);
				MSG_WriteByte(&buf, j);
				MSG_WriteByte(&buf, stats[j]);
			}
			else
			{
				MSG_WriteByte(&buf, svc_updatestatlong);
				MSG_WriteByte(&buf, j);
				MSG_WriteLong(&buf, stats[j]);
			}
		}

		if (buf.cursize)
		{
			CL_WriteRecordMVDStatsMessage(&buf, i);
			SZ_Clear (&buf);
		}
	}

	// Above stats writing must clear buffer.
	if (buf.cursize)
	{
		Sys_Error("CL_WriteMVDStartupData: buf.cursize %d", buf.cursize);
	}

	// 
	// Send packetentities.
	//
	{
		int ent_index, ent_total;
		entity_state_t *ent_state;

		// Write the ID byte for a delta entity operation to the demo.
		MSG_WriteByte (&buf, svc_packetentities);

		// Get the entities list from the frame.
		ent_state = cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK].packet_entities.entities;
		ent_total = cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK].packet_entities.num_entities;

		// Write all the entity changes since last packet entity message.
		for (ent_index = 0; ent_index < ent_total; ent_index++, ent_state++)
			MSG_WriteDeltaEntity (&cl_entities[ent_state->number].baseline, ent_state, &buf, true);

		// End of packetentities.
		MSG_WriteShort (&buf, 0);
	}

	if (buf.cursize)
	{
		CL_WriteRecordMVDMessage (&buf);
		SZ_Clear (&buf);
	}

	// Get the client to check and download skins
	// when that is completed, a begin command will be issued.
	MSG_WriteByte (&buf, svc_stufftext);
	MSG_WriteString (&buf, "skins\n");

	CL_WriteRecordMVDMessage (&buf);
}

// ==============
// Commands
// ==============

void CL_StopMvd_f(void)
{
	if (!cls.mvdrecording && !mvdrecordfile)
	{
		Com_Printf ("Not recording a demo\n");
		return;
	}

	if (mvdrecordfile)
	{
		char *quotes[] = {
	       " Make love not WarCraft\n"
	       " Get quake at http://nquake.sf.net\n",
	       " ez come ez go\n"
	       " Get ezQuake at http://ezQuake.sf.net\n",
	       " In the name of fun\n"
	       " Visit http://quakeworld.nu\n"
		};

		char str[1024];
		sizebuf_t	buf;
		unsigned char buf_data[MAX_MSGLEN];

		SZ_Init (&buf, buf_data, sizeof(buf_data));

		// Print offensive message.
		snprintf(str, sizeof(str),
				"\x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f\n"
		        "%s"
				"\x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f\n",
				quotes[i_rnd( 0, sizeof(quotes)/sizeof(quotes[0]) - 1 )]);

		MSG_WriteByte(&buf, svc_print);
		MSG_WriteByte(&buf, 2);
		MSG_WriteString(&buf, str);

		// Add disconnect.

		MSG_WriteByte (&buf, svc_disconnect);
		MSG_WriteString (&buf, "EndOfDemo");

		CL_WriteRecordMVDMessage (&buf);

		fclose(mvdrecordfile);
		mvdrecordfile = NULL;

		Com_Printf ("Completed demo\n");
	}
	else
	{
		Com_Printf ("BUG: Demo alredy completed or something\n");
	}

	cls.mvdrecording = false;
}

void CL_RecordMvd_f(void)
{
	char nameext[MAX_OSPATH * 2], name[MAX_OSPATH * 2];

	switch(Cmd_Argc())
	{
		case 1:
		//
		// Just show if anything is being recorded.
		//
		{
			if (cls.mvdrecording)
				Com_Printf("Recording to %s\n", mvddemoname);
			else
				Com_Printf("Not recording\n");
			break;
		}
		case 2:
		//
		// Start recording to the specified demo name.
		//
		{
			if (cls.state != ca_active && cls.state != ca_disconnected)
			{
				Com_Printf ("Cannot record whilst connecting\n");
				return;
			}

			// Stop any recording in progress.
			if (cls.mvdrecording)
				CL_StopMvd_f();

			// Make sure the filename doesn't contain any invalid characters.
			if (!Util_Is_Valid_Filename(Cmd_Argv(1)))
			{
				Com_Printf(Util_Invalid_Filename_Msg(Cmd_Argv(1)));
				return;
			}

			// Open the demo file for writing.
			strlcpy(nameext, Cmd_Argv(1), sizeof(nameext));
			COM_ForceExtensionEx (nameext, ".mvd", sizeof (nameext));

			// Get the path for the demo and try opening the file for writing.
			snprintf (name, sizeof(name), "%s/%s", CL_DemoDirectory(), nameext);

			mvdrecordfile = fopen(name, "wb");

			if (!mvdrecordfile)
			{
				Com_Printf ("Error: Couldn't record to %s. Make sure path exists.\n", name);
				return;
			}

			// Demo starting has begun.
			cls.mvdrecording = true;

			// Save the demoname for later use.
			strlcpy(mvddemoname, name, sizeof(mvddemoname));

			// If we're active, write startup data right away.
			if (cls.state == ca_active)
				CL_WriteMVDStartupData();

			Com_Printf ("Recording to %s\n", nameext);
			break;
		}
		default:
		{
			Com_Printf("Usage: %s [demoname]\n", Cmd_Argv(0));
			break;
		}
	}
}

//=============================================================================
//								DEMO READING
//=============================================================================

vfsfile_t *playbackfile = NULL;			// The demo file used for playback.
float demo_time_length = 0;				// The length of the demo.

unsigned char pb_buf[1024*32];			// Playback buffer.
int		pb_cnt = 0;						// How many bytes we've have in playback buffer.
qbool	pb_eof = false;					// Have we reached the end of the playback buffer?

//
// Inits the demo playback buffer.
// If we do QTV demo playback, we read data ahead while parsing QTV connection headers,
// so we may have demo data in qtvrequestbuffer[], so we move data from qtvrequestbuffer[] to pb_buf[] with this function.
//
void CL_Demo_PB_Init(void *buf, int buflen)
{
	// The length of the buffer is out of bounds.
	if (buflen < 0 || buflen > (int)sizeof(pb_buf))
		Sys_Error("CL_Demo_PB_Init: buflen out of bounds.");

	// Copy the specified init data into the playback buffer.
	memcpy(pb_buf, buf, buflen);

	// Reset any associated playback buffers.
	pb_cnt = buflen;
	pb_eof = false;
}

//
// This is memory reading(not from file or socket), we just copy data from pb_buf[] to caller buffer,
// sure if we're not peeking we decrease pb_buf[] size (pb_cnt) and move along pb_buf[] itself.
//
int CL_Demo_Read(void *buf, int size, qbool peek)
{
	int need;

	// Size can't be negative.
	if (size < 0)
		Host_Error("pb_read: size < 0");

	need = max(0, min(pb_cnt, size));
	memcpy(buf, pb_buf, need);

	if (!peek)
	{
		// We are not peeking, so move along buffer.
		pb_cnt -= need;
		memmove(pb_buf, pb_buf + need, pb_cnt);

		// We get some data from playback file or qtv stream, dump it to file right now.
		if (need > 0 && cls.mvdplayback && cls.mvdrecording)
			CL_MVD_DemoWrite(buf, need);
	}

	if (need != size)
		Host_Error("Unexpected end of demo");

	return need;
}

//
// Reads a chunk of data from the playback file and returns the number of bytes read.
//
static int pb_raw_read(void *buf, int size)
{
	vfserrno_t err;
	int r = VFS_READ(playbackfile, buf, size, &err);

	// Size > 0 mean detect EOF only if we actually trying read some data.
	if (size > 0 && !r && err == VFSERR_EOF)
		pb_eof = true;

	return r;
}

//
// Ensure we have enough data to parse, it not then return false.
// Function was introduced with QTV. If you read a demo from file and you run out of data
// that's critical, but when streaming an MVD using QTV and don't receive enough data from 
// the network it isn't critical, we just freeze the client for some time while filling
// the playback buffer.
//
qbool pb_ensure(void)
{
	// Increase internal TCP buffer by faking a read to it.
	pb_raw_read(NULL, 0);

	// Show how much we've read.
	if (cl_shownet.value == 3)
		Com_Printf(" %d", pb_cnt);

	// Try to fill the entire buffer with demo data.
	pb_cnt += pb_raw_read(pb_buf + pb_cnt, max(0, (int)sizeof(pb_buf) - pb_cnt));

	if (pb_cnt == (int)sizeof(pb_buf) || pb_eof)
		return true; // Return true if we have full buffer or get EOF.

	// Probably not enough data in buffer, check do we have at least one message in buffer.
	if (cls.mvdplayback && pb_cnt)
	{
		if(ConsistantMVDData((unsigned char*)pb_buf, pb_cnt))
			return true;
	}

	// Set the buffering time if it hasn't been set already.
	if (cls.mvdplayback == QTV_PLAYBACK && !bufferingtime && !cls.qtv_donotbuffer)
	{
		double prebufferseconds = QTVBUFFERTIME;

		bufferingtime = Sys_DoubleTime() + prebufferseconds;

		if (developer.integer >= 2)
			Com_DPrintf("&cF00" "qtv: not enough buffered, buffering for %.1fs\n" "&r", prebufferseconds); // print some annoying message
	}

	return false;
}

static float prevtime = 0; // TODO: Put in a demo struct.

//
// Peeks the demo time.
//
static float CL_PeekDemoTime(void)
{
	float demotime = 0.0;

	if (cls.mvdplayback)
	{
		byte mvd_time = 0; // Number of miliseconds since last frame. Can be between 0-255. MVD Only.

		// Peek inside, but don't read.
		// (Since it might not be time to continue reading in the demo
		// we want to be able to check this again later if that's the case).
		CL_Demo_Read(&mvd_time, sizeof(mvd_time), true);

		// Calculate the demo time.
		// (The time in an MVD is saved as a byte with number of miliseconds since the last cmd
		// so we need to multiply it by 0.001 to get it in seconds like normal quake time).
		demotime = prevtime + (mvd_time * 0.001);

		if ((cls.demotime - nextdemotime) > 0.0001 && (nextdemotime != demotime))
		{
			olddemotime = nextdemotime;
			cls.netchan.incoming_sequence++;
			cls.netchan.incoming_acknowledged++;
			cls.netchan.frame_latency = 0;
			cls.netchan.last_received = cls.demotime; // Make timeout check happy.
			nextdemotime = demotime;
		}
	}
	else 
	{
		// Peek inside, but don't read.
		// (Since it might not be time to continue reading in the demo
		// we want to be able to check this again later if that's the case).
		CL_Demo_Read(&demotime, sizeof(demotime), true);
		demotime = LittleFloat(demotime);

		if (demotime < cls.demotime)
		{
			olddemotime = nextdemotime;

			nextdemotime = demotime;
		}
	}

	return demotime;
}

//
// Consume the demo time.
//
static void CL_ConsumeDemoTime(void)
{
	if (cls.mvdplayback)
	{
		byte dummy_newtime;
		CL_Demo_Read(&dummy_newtime, sizeof(dummy_newtime), false);
	}
	else
	{
		float dummy_demotime;
		CL_Demo_Read(&dummy_demotime, sizeof(dummy_demotime), false);
	}
}

//
// Reads a dem_cmd message from an demo.
//
static void CL_DemoReadDemCmd(void)
{			
	// User cmd read.

	// Get which frame we should read the cmd into from the demo.
	int i = cls.netchan.outgoing_sequence & UPDATE_MASK;
	int j;

	// Read the user cmd from the demo.
	usercmd_t *pcmd = &cl.frames[i].cmd;
	CL_Demo_Read(pcmd, sizeof(*pcmd), false);

	// Convert the angles/movement vectors into the correct byte order.
	for (j = 0; j < 3; j++)
		pcmd->angles[j] = LittleFloat(pcmd->angles[j]);
	pcmd->forwardmove = LittleShort(pcmd->forwardmove);
	pcmd->sidemove = LittleShort(pcmd->sidemove);
	pcmd->upmove = LittleShort(pcmd->upmove);

	// Set the time time this cmd was sent and increase
	// how many net messages have been sent.
	cl.frames[i].senttime = cls.realtime;
	cl.frames[i].receivedtime = -1;		// We haven't gotten a reply yet.
	cls.netchan.outgoing_sequence++;

	// Read the viewangles from the demo and convert them to correct byte order.
	CL_Demo_Read(cl.viewangles, 12, false);
	for (j = 0; j < 3; j++)
		cl.viewangles[j] = LittleFloat (cl.viewangles[j]);

	// Calculate the player fps based on the cmd.
	CL_CalcPlayerFPS(&cl.players[cl.playernum], pcmd->msec);

	// Try locking on to a player.
	if (cl.spectator)
		Cam_TryLock();

	// Write the demo to the record file if we're recording.
	if (cls.demorecording)
		CL_WriteDemoCmd(pcmd);
}

//
// Reads a dem_read message from a demo. Returns true if we should continue reading messages.
//
static qbool CL_DemoReadDemRead(void)
{
	// Read the size of next net message in the demo file
	// and convert it into the correct byte order.
	CL_Demo_Read(&net_message.cursize, 4, false);
	net_message.cursize = LittleLong(net_message.cursize);

	// The message was too big, stop playback.
	if (net_message.cursize > net_message.maxsize)
	{
		Com_DPrintf("CL_GetDemoMessage: net_message.cursize > net_message.maxsize");
		Host_EndGame();
		Host_Abort();
	}

	// Read the net message from the demo.
	CL_Demo_Read(net_message.data, net_message.cursize, false);

	// Check what the last message type was for MVDs.
	if (cls.mvdplayback)
	{
		int tracknum = -1;

		switch(cls.lasttype)
		{
			case dem_multiple:
			{
				// Get the number of the player being tracked.
				tracknum = Cam_TrackNum();

				// If no player is tracked (free flying), or the player we're tracking
				// is not affected by this message. If that's the case just read the next message.
				if ((tracknum == -1) || !(cls.lastto & (1 << tracknum)))
				{
					return true;
				}
				break;
			}
			case dem_single:
			{
				// If we're not tracking the player referred to in the demo
				// message it's time to read the next message.
				tracknum = Cam_TrackNum();
				if ((tracknum == -1) || (cls.lastto != spec_track))
				{
					return true;
				}
				break;
			}
		}
	}

	return false;
}

//
// Reads a dem_set message from a demo.
//
static void CL_DemoReadDemSet(void)
{
	int i;

	CL_Demo_Read(&i, sizeof(i), false);
	cls.netchan.outgoing_sequence = LittleLong(i);

	CL_Demo_Read(&i, sizeof(i), false);
	cls.netchan.incoming_sequence = LittleLong(i);

	if (cls.mvdplayback)
		cls.netchan.incoming_acknowledged = cls.netchan.incoming_sequence;
}

//
// Returns true if it's time to read the next message, false otherwise.
//
static qbool CL_DemoShouldWeReadNextMessage(float demotime)
{
	if (cls.timedemo)
	{
		// Timedemo playback, grab the next message as quickly as possible.

		if (cls.td_lastframe < 0)
		{
			// This is the first frame of the timedemo.
			cls.td_lastframe = demotime;
		}
		else if (demotime > cls.td_lastframe)
		{
			// We've already read this frame's message so skip it.
			cls.td_lastframe = demotime;
			return false;
		}

		// Did we just start the time demo?
		if (!cls.td_starttime && (cls.state == ca_active))
		{
			// Save the start time (real world time) and current frame number
			// so that we will know how long it took to go through it all
			// and calculate the framerate when it's done.
			cls.td_starttime = Sys_DoubleTime();
			cls.td_startframe = cls.framecount;
		}

		cls.demotime = demotime; // Warp.
	}
	else if (!(cl.paused & PAUSED_SERVER) && (cls.state == ca_active)) // Always grab until fully connected.
	{
		// Not paused and active.

		if (cls.mvdplayback)
		{
			if (nextdemotime < demotime)
			{
				return false; // Don't need another message yet.
			}
		}
		else
		{
			if (cls.demotime < demotime)
			{
				// Don't need another message yet.

				// Adjust the demotime to match what's read from file.
				if (cls.demotime + 1.0 < demotime)
					cls.demotime = demotime - 1.0;

				return false;
			}
		}
	}
	else
	{
		cls.demotime = demotime; // We're warping.
	}

	return true;
}

//
// When a demo is playing back, all NET_SendMessages are skipped, and NET_GetMessages are read from the demo file.
// Whenever cl.time gets past the last received message, another message is read from the demo file.
//
// Summary:
//
// 1. MVD - Make sure we're not more than 1 second behind the next demo time.
// 2. Get the time of the next demo message by peeking at it.
// 3. Is it time to get the next demo message yet? (Always for timedemo) Return false if not.
// 4. Read the time of the next message from the demo (consume it).
// 5. MVD - Save the current time so we have it for the next frame
//    (we need it to calculate the demo time. Time in MVDs is saved
//     as the number of miliseconds since last frame).
// 6. Read the message type from the demo, only the first 3 bits are significant.
//    There are 3 basic message types used by all demos:
//    dem_set = Only appears once at start of demo. Contains sequence numbers for the netchan.
//    dem_cmd = A user movement cmd.
//    dem_Read = An arbitrary network message.
//
//    MVDs also use:
//    dem_multiple, dem_single, dem_stats and dem_all to direct certain messages to
//    specific clients only, and to update stats.
//
// 7. Parse the specific demo messages.
//
qbool CL_GetDemoMessage (void)
{
	float demotime;
	byte c;
	byte message_type;
	//static float prevtime = 0;

	// Don't try to play while QWZ is being unpacked.
	#ifdef _WIN32
	if (qwz_unpacking)
		return false;
	#endif

	// Demo paused, don't read anything.
	if (cl.paused & PAUSED_DEMO)
	{
		pb_ensure();	// Make sure we keep the QTV connection alive by reading from the socket.
		return false;
	}

	// We're not ready to parse since we're buffering for QTV.
	if (bufferingtime && (bufferingtime > Sys_DoubleTime()))
	{
		extern qbool	host_skipframe;

		pb_ensure();			// Fill the buffer for QTV.
		host_skipframe = true;	// This will force not update cls.demotime.

		return false;
	}

	bufferingtime = 0;

	// DEMO REWIND.
	if (!cls.mvdplayback || cls.mvdplayback != QTV_PLAYBACK)
	{
		CL_Demo_Check_For_Rewind(nextdemotime);
	}

	// Adjust the time for MVD playback.
	if (cls.mvdplayback)
	{
		// Reset the previous time.
		if (prevtime < nextdemotime)
			prevtime = nextdemotime;

		// Always be within one second from the next demo time.
		if (cls.demotime + 1.0 < nextdemotime)
			cls.demotime = nextdemotime - 1.0;
	}

	// Check if we need to get more messages for now and if so read it
	// from the demo file and pass it on to the net channel.
	while (true)
	{
		// Make sure we have enough data in the buffer.
		if (!pb_ensure())
			return false;

		// Read the time of the next message in the demo.
		demotime = CL_PeekDemoTime();

		// Keep gameclock up-to-date if we are seeking
		if (cls.demoseeking && demotime > prevtime)
			cl.gametime += demotime - prevtime;

		// Keep MVD features such as itemsclock up-to-date during seeking
		if (cls.demoseeking) {
			double tmp = cls.demotime;
			cls.demotime = demotime;
			MVD_Interpolate();
			MVD_Mainhook();
			cls.demotime = tmp;
		}

		if (cls.demoseeking == DST_SEEKING_STATUS)
			CL_Demo_Jump_Status_Check();

		// If we found demomark, we should stop seeking, so reset time to the proper value.
		if (cls.demoseeking == DST_SEEKING_FOUND) 
			cls.demotime = demotime; // this will trigger seeking stop

		// If we've reached our seek goal, stop seeking.
		if (cls.demoseeking && cls.demotime <= demotime && cls.state >= ca_active)
		{
			cls.demoseeking = DST_SEEKING_NONE;

			if (cls.demorewinding)
			{
				CL_Demo_Stop_Rewinding();
			}
		}

		playback_recordtime = demotime;

		// Decide if it is time to grab the next message from the demo yet.
		if (!CL_DemoShouldWeReadNextMessage(demotime))
		{
			return false;
		}
		
		// Read the time from the packet (we peaked at it earlier),
		// we're ready to get the next message.
		CL_ConsumeDemoTime();

		// Save the previous time for MVD playback (for the next message),
		// it is needed to calculate the demotime since in mvd's the time is
		// saved as the number of miliseconds since last frame message.
		// This is also used when seeking in qwds to keep the gameclock in time.
		prevtime = demotime;

		// Get the msg type.
		CL_Demo_Read(&c, sizeof(c), false);
		message_type = (c & 7);

		// QWD Only.
		if (message_type == dem_cmd)
		{
			CL_DemoReadDemCmd();
			
			continue; // Get next message.
		}

		// MVD Only. These message types tells to which players the message is directed to.
		if ((message_type >= dem_multiple) && (message_type <= dem_all))
		{
			switch (message_type)
			{
				case dem_multiple:
				//
				// This message should be sent to more than one player, get which players.
				//
				{
					// Read the player bit mask from the demo and convert to the correct byte order.
					// Each bit in this number represents a player, 32-bits, 32 players.
					int i;
					CL_Demo_Read(&i, 4, false);
					cls.lastto = LittleLong(i);
					cls.lasttype = dem_multiple;
					break;
				}
				case dem_stats:
				//
				// The stats for a player has changed. Get the player number of that player.
				//
				case dem_single:
				//
				// Only a single player should receive this message. Get the player number of that player.
				//
				{
					// The first 3 bits contain the message type (so remove that part), the rest contains
					// a 5-bit number which contains the player number of the affected player.
					cls.lastto = (c >> 3);
					cls.lasttype = message_type;
					break;
				}
				case dem_all:
				//
				// This message is directed to all players.
				//
				{
					cls.lastto = 0;
					cls.lasttype = dem_all;
					break;
				}
				default:
				{
					Host_Error("This can't happen (unknown command type) %c.\n", message_type);
				}
			}

			// Fall through to dem_read after we've gotten the affected players.
			message_type = dem_read;
		}

		// Get the next net message from the demo file.
		if (message_type == dem_read)
		{
			if (CL_DemoReadDemRead())
			{
				continue; // Continue reading messages.
			}
			
			return true; // We just read something.
		}

		// Gets the sequence numbers for the netchan at the start of the demo.
		if (message_type == dem_set)
		{
			CL_DemoReadDemSet();
			
			continue;
		}

		// We should never get this far if the demo is ok.
		Host_Error("Corrupted demo");
		return false;
	}
}

//=============================================================================
//								DEMO RECORDING
//=============================================================================

static char demoname[2 * MAX_OSPATH];
static char fulldemoname[MAX_PATH];
static qbool autorecording = false;
static qbool easyrecording = false;

void CL_AutoRecord_StopMatch(void);
void CL_AutoRecord_CancelMatch(void);

static void OnChange_demo_dir(cvar_t *var, char *string, qbool *cancel)
{
	if (!string[0])
		return;

	// Replace \ with /.
	Util_Process_FilenameEx(string, cl_mediaroot.integer == 2);

	// Make sure the filename doesn't have any invalid chars in it.
	if (!Util_Is_Valid_FilenameEx(string, cl_mediaroot.integer == 2))
	{
		Com_Printf(Util_Invalid_Filename_Msg(var->name));
		*cancel = true;
		return;
	}

	// Change to the new folder in the demo browser.
	// FIXME: this did't work
	Menu_Demo_NewHome(string);
}

#ifdef _WIN32
static void OnChange_demo_format(cvar_t *var, char *string, qbool *cancel)
{
	char* allowed_formats[5] = { "qwd", "qwz", "mvd", "mvd.gz", "qwd.gz" };
	int i;

	for (i = 0; i < 5; i++)
		if (!strcmp(allowed_formats[i], string))
			return;

	Com_Printf("Not valid demo format. Allowed values are: ");
	for (i = 0; i < 5; i++)
	{
		if (i)
			Com_Printf(", ");
		Com_Printf(allowed_formats[i]);
	}
	Com_Printf(".\n");

	*cancel = true;
}
#endif

//
// Writes a "pimp message" for ezQuake at the end of a demo.
//
static void CL_WriteDemoPimpMessage(void)
{
	int i;
	char pimpmessage[256], border[64];

	if (cls.demoplayback)
		return;

	strlcpy (border, "\x1d", sizeof (border));

	for (i = 0; i < 34; i++)
		strlcat (border, "\x1e", sizeof (border));

	strlcat (border, "\x1f", sizeof (border));

	snprintf (pimpmessage, sizeof(pimpmessage), "\n%s\n%s\n%s\n",
		border,
		"\x1d\x1e\x1e\x1e\x1e\x1e\x1e Recorded by ezQuake \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f",
		border
	);

	SZ_Clear (&net_message);
	MSG_WriteLong (&net_message, cls.netchan.incoming_sequence + 1);
	MSG_WriteLong (&net_message, cls.netchan.incoming_acknowledged | (cls.netchan.incoming_reliable_acknowledged << 31));
	MSG_WriteByte (&net_message, svc_print);
	MSG_WriteByte (&net_message, PRINT_HIGH);
	MSG_WriteString (&net_message, pimpmessage);
	CL_WriteDemoMessage (&net_message);
}

//
// Stop recording a demo.
//
static void CL_StopRecording (void)
{
	// Nothing to stop.
	if (!cls.demorecording)
		return;

	// Write a pimp message to the demo.
	CL_WriteDemoPimpMessage();

	// Write a disconnect message to the demo file.
	SZ_Clear (&net_message);
	MSG_WriteLong (&net_message, -1);	// -1 sequence means out of band
	MSG_WriteByte (&net_message, svc_disconnect);
	MSG_WriteString (&net_message, "EndOfDemo");
	CL_WriteDemoMessage (&net_message);

	// Finish up by closing the demo file.
	CL_Demo_Close();
	cls.demorecording = false;
}

//
// Stop recording a demo.
//
void CL_Stop_f (void)
{
	if (com_serveractive && strcmp(Cmd_Argv(0), "stop") == 0)
	{
		SV_MVDStop_f();
		return;
	}

	if (!cls.demorecording)
	{
		Com_Printf ("Not recording a demo\n");
		return;
	}
	if (autorecording)
	{
		CL_AutoRecord_StopMatch();
#ifdef _WIN32
	}
	else if (easyrecording)
	{
		CL_StopRecording();
		CL_Demo_Compress(fulldemoname);
		easyrecording = false;
#endif
	}
	else
	{
		CL_StopRecording();
		Com_Printf ("Completed demo\n");
	}
}

//
// Returns the Demo directory. If the user hasn't set the demo_dir var, the gamedir is returned.
//
char *CL_DemoDirectory(void)
{
	static char dir[MAX_PATH];

	strlcpy(dir, FS_LegacyDir(demo_dir.string), sizeof(dir));
	return dir;
}

//
// Start recording a demo.
//
void CL_Record_f (void)
{
	char nameext[MAX_OSPATH * 2], name[MAX_OSPATH * 2];

	if (com_serveractive && strcmp(Cmd_Argv(0), "record") == 0)
	{
		SV_MVD_Record_f();
		return;
	}

	if (cls.fteprotocolextensions &~ (FTE_PEXT_CHUNKEDDOWNLOADS|FTE_PEXT_256PACKETENTITIES))
	{
		Com_Printf ("WARNING: FTE protocol extensions enabled; this demo most likely will be unplayable in older clients. "
			"Use cl_pext 0 for 100%% compatible demos. But do NOT forget set it to 1 later or you will lack useful features!\n");
	}

	switch(Cmd_Argc())
	{
		case 1:
		//
		// Just show if anything is being recorded.
		//
		{
			if (autorecording)
				Com_Printf("Auto demo recording is in progress\n");
			else if (cls.demorecording)
				Com_Printf("Recording to %s\n", demoname);
			else
				Com_Printf("Not recording\n");
			break;
		}
		case 2:
		//
		// Start recording to the specified demo name.
		//
		{
			if (cls.mvdplayback)
			{
				Com_Printf ("Cannot record during mvd playback\n");
				return;
			}

			if (cls.state != ca_active && cls.state != ca_disconnected)
			{
				Com_Printf ("Cannot record whilst connecting\n");
				return;
			}

			if (autorecording)
			{
				Com_Printf("Auto demo recording must be stopped first!\n");
				return;
			}

			// Stop any recording in progress.
			if (cls.demorecording)
				CL_Stop_f();

			// Make sure the filename doesn't contain any invalid characters.
			if (!Util_Is_Valid_Filename(Cmd_Argv(1)))
			{
				Com_Printf(Util_Invalid_Filename_Msg(Cmd_Argv(1)));
				return;
			}

			// Open the demo file for writing.
			strlcpy(nameext, Cmd_Argv(1), sizeof(nameext));
			COM_ForceExtensionEx (nameext, ".qwd", sizeof (nameext));

			// Get the path for the demo and try opening the file for writing.
			snprintf (name, sizeof(name), "%s/%s", CL_DemoDirectory(), nameext);
			if (!CL_Demo_Open(name))
			{
				Com_Printf ("Error: Couldn't record to %s. Make sure path exists.\n", name);
				return;
			}

			// Demo starting has begun.
			cls.demorecording = true;

			// If we're active, write startup data right away.
			if (cls.state == ca_active)
				CL_WriteStartupData();

			// Save the demoname for later use.
			strlcpy(demoname, nameext, sizeof(demoname));

			Com_Printf ("Recording to %s\n", nameext);

			break;
		}
		default:
		{
			Com_Printf("Usage: %s [demoname]\n", Cmd_Argv(0));
			break;
		}
	}
}

//
// Starts recording a demo using autorecord or easyrecord.
//
static qbool CL_MatchRecordDemo(char *dir, char *name, qbool autorecord)
{
	char extendedname[MAX_PATH];
	char strippedname[MAX_PATH];
	char *fullname;
	char *exts[] = {"qwd", "qwz", "mvd", NULL};
	int num;

	if (cls.state != ca_active)
	{
		Com_Printf ("You must be connected before using easyrecord\n");
		return false;
	}

	if (cls.mvdplayback)
	{
		Com_Printf ("Cannot record during mvd playback\n");
		return false;
	}

	if (autorecording)
	{
		Com_Printf("Auto demo recording must be stopped first!\n");
		return false;
	}

	// Stop any old recordings.
	if (cls.demorecording)
		CL_Stop_f();

	// Make sure we don't have any invalid chars in the demo name.
	if (!Util_Is_Valid_Filename(name))
	{
		Com_Printf(Util_Invalid_Filename_Msg(name));
		return false;
	}

	// We always record to qwd. If the user has set some other demo format
	// we convert to that later on.
	COM_ForceExtension(name, ".qwd");

	if (autorecord)
	{
		// Save the final demo name.
		strlcpy (extendedname, name, sizeof(extendedname));
	}
	else
	{
		//
		// Easy recording, file is saved using match_* settings.
		//

		// Get rid of the extension again.
		COM_StripExtension(name, strippedname);
		fullname = va("%s/%s", dir, strippedname);

		// Find a unique filename in the specified dir.
		if ((num = Util_Extend_Filename(fullname, exts)) == -1)
		{
			Com_Printf("Error: no available filenames\n");
			return false;
		}

		// Save the demo name..
		snprintf (extendedname, sizeof(extendedname), "%s_%03i.qwd", strippedname, num);
	}

	// Get dir + final demo name.
	fullname = va("%s/%s", dir, extendedname);

	// Open the demo file for writing.
	if (!CL_Demo_Open(fullname))
	{
		// Failed to open the file, make sure it exists and try again.
		FS_CreatePath(fullname);
		if (!CL_Demo_Open(fullname))
		{
			Com_Printf("Error: Couldn't open %s\n", fullname);
			return false;
		}
	}

	// Write the demo startup stuff.
	cls.demorecording = true;
	CL_WriteStartupData ();

	// Echo the name of the demo if we're easy recording
	// and save the demo name for later use.
	if (!autorecord)
	{
		Com_Printf ("Recording to %s\n", extendedname);
		strlcpy(demoname, extendedname, sizeof(demoname));		// Just demo name.
		strlcpy(fulldemoname, fullname, sizeof(fulldemoname));  // Demo name including path.
	}

	return true;
}

//
// Starts recording a demo and names it according to your match_ settings.
//
void CL_EasyRecord_f (void)
{
	char *name;

	if ( com_serveractive )
	{
		SV_MVDEasyRecord_f();
		return;
	}

	if (cls.state != ca_active)
	{
		Com_Printf("You must be connected to easyrecord\n");
		return;
	}

	switch(Cmd_Argc())
	{
		case 1:
		{
			// No name specified by the user, get it from match tools instead.
			name = MT_MatchName();
			break;
		}
		case 2:
		{
			// User specified a demo name, use it.
			name = Cmd_Argv(1);
			break;
		}
		default:
		{
			Com_Printf("Usage: %s [demoname]\n", Cmd_Argv(0));
			return;
		}
	}

	easyrecording = CL_MatchRecordDemo(CL_DemoDirectory(), name, false);
}

//=============================================================================
//							DEMO AUTO RECORDING
//=============================================================================

static char	auto_matchname[MAX_PATH];	// Demoname when recording auto match demo.
static qbool temp_demo_ready = false;	// Indicates if the autorecorded match demo is done recording.
static float auto_starttime;

char *MT_TempDirectory(void);

extern cvar_t match_auto_record, match_auto_minlength;

#define TEMP_DEMO_NAME "_!_temp_!_.qwd"

#define DEMO_MATCH_NORECORD		0 // No autorecord.
#define DEMO_MATCH_MANUALSAVE	1 // Demo will be recorded but requires manuall saving.
#define DEMO_MATCH_AUTOSAVE		2 // Automatically saves the demo after the match is completed.

//
// Stops auto recording of a match.
//
void CL_AutoRecord_StopMatch(void)
{
	// Not doing anything.
	if (!autorecording)
		return;

	// Stop the recording and write end of demo stuff.
	autorecording = false;
	CL_StopRecording();
	temp_demo_ready = true;

	// Automatically save the demo after the match is completed.
	if (match_auto_record.value == DEMO_MATCH_AUTOSAVE)
	{
		CL_AutoRecord_SaveMatch();
		Com_Printf ("Auto record ok\n");
	}
	else
	{
		Com_Printf ("Auto demo recording completed\n");
	}
}

//
// Cancels the match.
//
void CL_AutoRecord_CancelMatch(void)
{
	// Not recording.
	if (!autorecording)
		return;

	// Stop the recording and write end of demo stuff.
	autorecording = false;
	CL_StopRecording();
	temp_demo_ready = true;

	if (match_auto_record.value == DEMO_MATCH_AUTOSAVE)
	{
		// Only save the demo if it's longer than the specified minimum length
		if (cls.realtime - auto_starttime > match_auto_minlength.value)
			CL_AutoRecord_SaveMatch();
		else
			Com_Printf("Auto demo recording cancelled\n");
	}
	else
	{
		Com_Printf ("Auto demo recording completed\n");
	}
}

//
// Starts autorecording a match.
//
void CL_AutoRecord_StartMatch(char *demoname)
{
	temp_demo_ready = false;

	// No autorecording is set.
	if (!match_auto_record.value)
		return;

	// Don't start autorecording if the
	// user already is recording a demo.
	if (cls.demorecording)
	{
		// We're autorecording since before, it's
		// ok to restart the recording then.
		if (autorecording)
		{
			autorecording = false;
			CL_StopRecording();
		}
		else
		{
			Com_Printf("Auto demo recording skipped (already recording)\n");
			return;
		}
	}

	// Save the name of the auto recorded demo for later.
	strlcpy(auto_matchname, demoname, sizeof(auto_matchname));

	// Try starting to record the demo.
	if (!CL_MatchRecordDemo(MT_TempDirectory(), TEMP_DEMO_NAME, true))
	{
		Com_Printf ("Auto demo recording failed to start!\n");
		return;
	}

	// We're now in business.
	autorecording = true;
	auto_starttime = cls.realtime;
	Com_Printf ("Auto demo recording commenced\n");
}

//
//
//
qbool CL_AutoRecord_Status(void)
{
	return temp_demo_ready ? 2 : autorecording ? 1 : 0;
}

//
// Saves an autorecorded demo.
//
void CL_AutoRecord_SaveMatch(void)
{
	//
	// All demos are first recorded in .qwd, and will then be converted to .mvd/.qwz afterwards
	// if those formats are chosen.
	//
	int error, num;
	FILE *f;
	char *dir, *tempname, savedname[MAX_PATH], *fullsavedname, *exts[] = {"qwd", "qwz", "mvd", NULL};

	// The auto recorded demo hasn't finished recording, can't do this yet.
	if (!temp_demo_ready)
		return;

	// Don't try to save it again.
	temp_demo_ready = false;

	// Get the demo dir.
	dir = CL_DemoDirectory();

	// Get the temp name of the file we've recorded.
	tempname = va("%s/%s", MT_TempDirectory(), TEMP_DEMO_NAME);

	// Get the final name where we'll save the final product.
	fullsavedname = va("%s/%s", dir, auto_matchname);

	// Find a unique filename in the final location.
	if ((num = Util_Extend_Filename(fullsavedname, exts)) == -1)
	{
		Com_Printf("Error: no available filenames\n");
		return;
	}

	// Get the final full path where we'll save the demo. (This is the final name for real now)
	snprintf (savedname, sizeof(savedname), "%s_%03i.qwd", auto_matchname, num);
	fullsavedname = va("%s/%s", dir, savedname);

	// Try opening the temp file to make sure we can read it.
	if (!(f = fopen(tempname, "rb")))
		return;
	fclose(f);

	// Move the temp file to the final location.
	if ((error = rename(tempname, fullsavedname)))
	{
		// Failed to move, make sure the path exists and try again.
		FS_CreatePath(fullsavedname);
		error = rename(tempname, fullsavedname);
	}

#ifdef _WIN32

	// If the file type is not QWD we need to conver it using external apps.
	if (!strcmp(demo_format.string, "qwz") || !strcmp(demo_format.string, "mvd"))
	{
		Com_Printf("Converting QWD to %s format.\n", demo_format.string);

		// Convert the file to either MVD or QWZ.
		if (CL_Demo_Compress(fullsavedname))
		{
			return;
		}
		else
		{
			qwz_packing = false;
		}
	}

#endif

	if (!error)
		Com_Printf("Match demo saved to %s\n", savedname);
}

//=============================================================================
//							QIZMO COMPRESSION
//=============================================================================

#ifdef _WIN32

//
//
//
void CL_Demo_RemoveQWD(void)
{
	unlink(tempqwd_name);
}

//
// cdemo_name is assumed to be 255 chars long
//
void CL_Demo_GetCompressedName (char* cdemo_name)
{
	size_t namelen = strlen (tempqwd_name);

	if (strlen (demo_format.string) && namelen)
	{
		strlcpy (cdemo_name, tempqwd_name, 255);
		strlcpy (cdemo_name + namelen - 3, demo_format.string, 255 - namelen + 3);
	}
}

//
//
//
void CL_Demo_RemoveCompressed(void)
{
	char cdemo_name[255];
	CL_Demo_GetCompressedName (cdemo_name);
	unlink(cdemo_name);
}

//
//
//
static void StopQWZPlayback (void)
{
	if (!hQizmoProcess && tempqwd_name[0])
	{
		if (remove (tempqwd_name) != 0)
			Com_Printf ("Error: Couldn't delete %s\n", tempqwd_name);
		tempqwd_name[0] = 0;
	}
	qwz_playback = false;
	qwz_unpacking = false;
}

//
//
//
void CL_CheckQizmoCompletion (void)
{
	DWORD ExitCode;

	if (!hQizmoProcess)
		return;

	if (!GetExitCodeProcess (hQizmoProcess, &ExitCode))
	{
		Com_Printf ("WARINING: CL_CheckQizmoCompletion: GetExitCodeProcess failed\n");
		hQizmoProcess = NULL;
		if (qwz_unpacking)
		{
			qwz_unpacking = false;
			qwz_playback = false;
			cls.demoplayback = cls.timedemo = false;
			StopQWZPlayback();
		}
		else if (qwz_packing)
		{
			qwz_packing = false;
			CL_Demo_RemoveCompressed();
		}
		return;
	}

	if (ExitCode == STILL_ACTIVE)
		return;

	hQizmoProcess = NULL;

	if (!qwz_packing && (!qwz_unpacking || !cls.demoplayback))
	{
		StopQWZPlayback ();
		return;
	}

	if (qwz_unpacking)
	{
		qwz_unpacking = false;

		if (!(playbackfile = FS_OpenVFS (tempqwd_name, "rb", FS_NONE_OS)))
		{
			Com_Printf ("Error: Couldn't open %s\n", tempqwd_name);
			qwz_playback = false;
			cls.demoplayback = cls.timedemo = false;
			tempqwd_name[0] = 0;
			return;
		}

		Com_Printf("Decompression completed...playback starting\n");
	}
	else if (qwz_packing)
	{
		FILE* tempfile;
		char newname[255];
		CL_Demo_GetCompressedName (newname);
		qwz_packing = false;

		if ((tempfile = fopen(newname, "rb")) && (FS_FileLength(tempfile) > 0) && fclose(tempfile) != EOF)
		{
			Com_Printf("Demo saved to %s\n", newname + strlen(com_basedir));
			CL_Demo_RemoveQWD();
		}
		else
		{
			Com_Printf("Compression failed, demo saved as QWD.\n");
		}
	}
}

//
//
//
static void PlayQWZDemo (void)
{
	extern cvar_t qizmo_dir;
	STARTUPINFO si;
	PROCESS_INFORMATION	pi;
	char *name, qwz_name[MAX_PATH], cmdline[512], *p;
	DWORD res;

	if (hQizmoProcess)
	{
		Com_Printf ("Cannot unpack -- Qizmo still running!\n");
		return;
	}

	name = Cmd_Argv(1);

	char* initialName = NULL;
	if (!(playbackfile = CL_Open_Demo_File(name, false, &initialName)))
	{
		Com_Printf ("Error: Couldn't open %s\n", name);
		return;
	}

	// Convert to system path
	Sys_fullpath(qwz_name, initialName, MAX_PATH);

	VFS_CLOSE (playbackfile);
	playbackfile = NULL;

	strlcpy (tempqwd_name, qwz_name, sizeof(tempqwd_name) - 4);

	// the way Qizmo does it, sigh
	if (!(p = strstr (tempqwd_name, ".qwz")))
		p = strstr (tempqwd_name, ".QWZ");
	if (!p)
		p = tempqwd_name + strlen(tempqwd_name);
	strcpy (p, ".qwd");

	// If .qwd already exists, just play it.
	if ((playbackfile = FS_OpenVFS(tempqwd_name, "rb", FS_NONE_OS)))
		return;

	Com_Printf ("Unpacking %s...\n", COM_SkipPath(name));

	// Start Qizmo to unpack the demo.
	memset (&si, 0, sizeof(si));
	si.cb = sizeof(si);
	si.wShowWindow = SW_SHOWMINNOACTIVE;
	si.dwFlags = STARTF_USESHOWWINDOW;

	strlcpy (cmdline, va("%s/%s/qizmo.exe -q -u -3 -D \"%s\"", com_basedir, qizmo_dir.string, qwz_name), sizeof(cmdline));

	if (!CreateProcess (NULL, cmdline, NULL, NULL,
		FALSE, GetPriorityClass(GetCurrentProcess()),
		NULL, va("%s/%s", com_basedir, qizmo_dir.string), &si, &pi))
	{
		Com_Printf ("Couldn't execute %s/%s/qizmo.exe\n", com_basedir, qizmo_dir.string);
		return;
	}
	
	res = WaitForSingleObject(pi.hProcess, QWZ_DECOMPRESSION_TIMEOUT_MS);
	if (res == WAIT_TIMEOUT) {
		Com_Printf("Decompression took too long, aborting\n");
		return;
	}

	hQizmoProcess = pi.hProcess;
	qwz_unpacking = true;
	qwz_playback = true;
}

//
//
//
int CL_Demo_Compress(char* qwdname)
{
	extern cvar_t qizmo_dir;
	extern cvar_t qwdtools_dir;
	STARTUPINFO si;
	PROCESS_INFORMATION	pi;
	char cmdline[1024];
	char *path, outputpath[255];
	char *appname;
	char *parameters;

	if (hQizmoProcess)
	{
		Com_Printf ("Cannot compress -- Qizmo still running!\n");
		return 0;
	}

	memset (&si, 0, sizeof(si));
	si.cb = sizeof(si);
	si.wShowWindow = SW_SHOWMINNOACTIVE;
	si.dwFlags = STARTF_USESHOWWINDOW;

	if (!strcmp(demo_format.string, "qwz"))
	{
		appname = "qizmo.exe";
		parameters = "-q -C";
		path = qizmo_dir.string;
		outputpath[0] = 0;
	}
	else if (!strcmp(demo_format.string, "mvd"))
	{
		appname = "qwdtools.exe";
		parameters = "-c -o * -od";
		path = qwdtools_dir.string;
		strlcpy(outputpath, qwdname, COM_SkipPath(qwdname) - qwdname);
	}
	else
	{
		Com_Printf("%s demo format not yet supported.\n", demo_format.string);
		return 0;
	}

	strlcpy (cmdline, va("\"%s/%s/%s\" %s \"%s\" \"%s\"", com_basedir, path, appname, parameters, outputpath, qwdname), sizeof(cmdline));
	Com_DPrintf("Executing ---\n%s\n---\n", cmdline);

	if (!CreateProcess (NULL, cmdline, NULL, NULL,
		FALSE, GetPriorityClass(GetCurrentProcess()),
		NULL, va("%s/%s", com_basedir, path), &si, &pi))
	{
		Com_Printf ("Couldn't execute %s/%s/%s\n", com_basedir, path, appname);
		return 0;
	}

	strlcpy(tempqwd_name, qwdname, sizeof(tempqwd_name));

	hQizmoProcess = pi.hProcess;
	qwz_packing = true;
	return 1;
}

#endif // _WIN32

//=============================================================================
//							DEMO PLAYBACK
//=============================================================================

double		demostarttime;

#ifdef WITH_ZIP
#ifndef WITH_VFS_ARCHIVE_LOADING
//
// [IN]		play_path = The compressed demo file that needs to be extracted to play it.
// [OUT]	unpacked_path = The path to the decompressed file.
//
static int CL_GetUnpackedDemoPath (char *play_path, char *unpacked_path, int unpacked_path_size)
{
	//
	// Check if the demo is in a zip file and if so, try to extract it before playing.
	//
	int retval = 0;
	char archive_path[MAX_PATH];
	char inzip_path[MAX_PATH];

	//
	// Is it a GZip file?
	//
	if (!strcmp (COM_FileExtension (play_path), "gz"))
	{
		int i = 0;
		int ext_len = 0;
		char ext[5];

		//
		// Find the extension with .gz removed.
		//
		{
			for (i = strlen(play_path) - 4; i > 0; i--)
			{
				if (play_path[i] == '.' || ext_len >= 4)
				{
					break;
				}

				ext_len++;
			}

			if (ext_len <= 4)
			{
				strlcpy (ext, play_path + strlen(play_path) - 4 - ext_len, sizeof(ext));
			}
			else
			{
				// Default to MVD.
				strlcpy (ext, ".mvd", sizeof(ext));
			}
		}

		// Unpack the file.
		if (!FS_GZipUnpackToTemp (play_path, unpacked_path, unpacked_path_size, ext))
		{
			return 0;
		}

		return 1;
	}

	//
	// Check if the path is in the format "c:\quake\bla\demo.zip\some_demo.mvd" and split it up.
	//
	if (FS_ZipBreakupArchivePath ("zip", play_path, archive_path, sizeof(archive_path), inzip_path, sizeof(inzip_path)) < 0)
	{
		return retval;
	}

	//
	// Extract the ZIP file.
	//
	{
		char temp_path[MAX_PATH];

		// Open the zip file.
		unzFile zip_file = FS_ZipUnpackOpenFile (archive_path);

		// Try extracting the zip file.
		if(FS_ZipUnpackOneFileToTemp (zip_file, inzip_path, false, false, NULL, temp_path, sizeof(temp_path)) != UNZ_OK)
		{
			Com_Printf ("Failed to unpack the demo file \"%s\" to the temp path \"%s\"\n", inzip_path, temp_path);
			unpacked_path[0] = 0;
		}
		else
		{
			// Successfully unpacked the demo.
			retval = 1;

			// Copy the path of the unpacked file to the return string.
			strlcpy (unpacked_path, temp_path, unpacked_path_size);
		}

		// Close the zip file.
		FS_ZipUnpackCloseFile (zip_file);
	}

	return retval;
}
#endif // WITH_VFS_ARCHIVE_LOADING
#endif // WITH_ZIP

void CL_Demo_DumpBenchmarkResult(int frames, float timet)
{
	char logfile[MAX_PATH];
	char datebuf[32];
	FILE* f;
	time_t t = time(&t);
	struct tm *ptm = localtime(&t);
	int width = 0, height = 0; 

	snprintf(logfile, sizeof(logfile), "%s/timedemo.log", FS_LegacyDir(log_dir.string));
	f = fopen(logfile, "a");
	if (!f) {
		Com_Printf("Can't open %s to dump timedemo result\n", logfile);
		return;
	}

	fputs("<timedemo date=\"", f);
	if (ptm)
		strftime (datebuf, sizeof(datebuf) - 1, "%Y-%m-%dT%H:%M:%S", ptm);
	else
		*datebuf = '\0';
	fputs(datebuf, f); fputs("\">\n", f);

	fputs(va("\t<system>\n\t\t<os>%s</os>\n\t\t<hardware>%s</hardware>\n\t</system>\n", QW_PLATFORM, SYSINFO_GetString()), f);

	fputs(va("\t<client>\n\t\t<name>ezQuake</name><version>%s</version>\n"
		"\t\t<configuration>%s</configuration><rendering>%s</rendering>\n\t</client>\n",
		VersionString(), QW_CONFIGURATION, QW_RENDERER), f);
//FIXME width/height doesnt get set, remove vid_mode/r_mode... Is this function used??
	if (width)
		fputs(va("\t<screen width=\"%d\" height=\"%d\"/>\n", width, height), f);

	fputs(va("\t<demo><name>%s</name></demo>\n", cls.demoname), f);

	fputs(va("\t<result frames=\"%i\" time=\"PT%fS\" fps=\"%f\"/>\n", frames, timet, frames/timet), f);
	
	fputs("</timedemo>\n", f);

	fclose(f);
}

//
// Stops demo playback.
//
void CL_StopPlayback (void)
{
	extern int demo_playlist_started;
	extern int mvd_demo_track_run;

	// Nothing to stop.
	if (!cls.demoplayback)
		return;

	// Capturing to avi/images, stop that.
	if (Movie_IsCapturing())
		Movie_Stop();

	// Close the playback file.
	if (playbackfile)
		VFS_CLOSE(playbackfile);

	// Reset demo playback vars.
	playbackfile = NULL;
	cls.mvdplayback = cls.demoplayback = cls.nqdemoplayback = false;
	cl.paused &= ~PAUSED_DEMO;

	cls.qtv_svversion = 0;
	cls.qtv_ezquake_ext = 0;
	cls.qtv_donotbuffer = false;

	// Stop Qizmo demo playback.
	#ifdef WIN32
	if (qwz_playback)
		StopQWZPlayback ();
	#endif

	//
	// Stop timedemo and show the result.
	//
	if (cls.timedemo)
	{
		int frames;
		float time;

		cls.timedemo = false;

		//
		// Calculate the time it took to render the frames.
		//
		frames = cls.framecount - cls.td_startframe - 1;
		time = Sys_DoubleTime() - cls.td_starttime;
		if (time <= 0)
			time = 1;
		Com_Printf ("%i frames %5.1f seconds %5.1f fps\n", frames, time, frames / time);
		if (demo_benchmarkdumps.integer)
			CL_Demo_DumpBenchmarkResult(frames, time);
	}

	// Go to the next demo in the demo playlist.
	if (demo_playlist_started)
	{
		CL_Demo_Playlist_f();
		mvd_demo_track_run = 0;
	}

	// Reset demoseeking and such.
	cls.demoseeking = DST_SEEKING_NONE;
	cls.demorewinding = false;

	TP_ExecTrigger("f_demoend");
}

//
// Returns the demo length.
//
float CL_GetDemoLength(void)
{
	return demo_time_length;
}

typedef enum demoprobe_parse_type_e
{
	READ_MVD_TIME	= 1,
	READ_QWD_TIME	= 2,
	TRY_READ_MVD	= 3
} demoprobe_parse_type_t;

//
// Validates a demo probe read.
//
#define DEMOPROBE_VALIDATE_READ(bytes_expected, bytes_read, message)		\
	if (bytes_expected != bytes_read)										\
	{																		\
		Com_DPrintf("CL_ProbeDemo: Unexpected end of demo. "message"\n");	\
		abort = true;														\
		break;																\
	}

//
// Seek the specified length and fail/abort if it fails.
//
#define DEMOPROBE_SEEK(file, length, message)								\
	if (VFS_SEEK(file, length, SEEK_CUR) == -1)								\
	{																		\
		Com_DPrintf("CL_ProbeDemo: Unexpected end of demo. "message"\n");	\
		abort = true;														\
		break;																\
	}

//
// Probe a demo in different ways.
//
qbool CL_ProbeDemo(vfsfile_t *demfile, demoprobe_parse_type_t probetype, float *demotime)
{
	#define PARSE_AS_MVD()			((probetype == READ_MVD_TIME) || (probetype == TRY_READ_MVD))
	#define REGARD_AS_MVD_COUNT		4		// Regard this to be an MVD when this count has been reached.

	vfserrno_t err;
	
	float qwd_time				= 0.0;		// QWD Time = Time since start of demo in seconds.
	byte mvd_time				= 0;		// MVD Time = Time in miliseconds since last time stamp.
	unsigned int total_mvd_time = 0;		// Total MVD time in miliseconds.
	
	byte command				= 0;		// Holds the command code.
	unsigned int multiple		= 0;		// Read dem_multiple data into this.
	unsigned int size			= 0;		// The size of the demo packet (follows dem_multiple, _single, _stats, _all and _read).

	int message_count			= 0;		// The total amount of demo messages.
	int len						= 0;		// Length of what's been read
	qbool is_mvd				= false;	// Is this an MVD. (Used when guessing if this is an MVD).
	int mvd_only_count			= 0;		// Try to figure out if this is a MVD by looking for commands only present in MVDs.
	qbool abort					= false;	// Something bad happened when reading the demo.

	while (!abort)
	{
		// Read the time.
		if (PARSE_AS_MVD())
		{
			// MVD time.
			len = VFS_READ(demfile, &mvd_time, 1, &err);
		}
		else
		{
			// QWD time.
			len = VFS_READ(demfile, &qwd_time, 4, &err);
			qwd_time = LittleFloat(qwd_time);
		}
		
		// Any well formed demo should only end at an expected time stamp.
		if ((len == 0) || (err == VFSERR_EOF))
		{
			Com_DPrintf("CL_ProbeDemo: End of file. All good!\n");
			break;
		}

		// Read the command.
		len = VFS_READ(demfile, &command, 1, &err);
		DEMOPROBE_VALIDATE_READ(1, len, "when reading command");

		size = 0;

		// The first 3 bits contains the command code.
		// The 5 other bits are:
		// dem_stats, 
		// dem_single	= Player number for the player affected.
		// dem_all		= Nothing, directed to all players.
		// dem_multiple = Nothing.
		switch (command & 0x7)
		{
			case dem_multiple :
			{
				// Only MVD.

				// Read a 32-bit number containing a bitmask for which the affected players are.
				// 32-bits, 32 players.
				len = VFS_READ(demfile, &multiple, 4, &err);

				if (err == VFSERR_EOF)
				{
					Com_Printf("Unexpected end of demo when reading multiple.\n");
					abort = true;
					break;
				}
			}
			case dem_single :		// Only MVD.
			case dem_all :			// Only MVD.
				mvd_only_count++;	// Count the number of MVD-only commands we find to determine if this is an MVD or not.
			case dem_stats : 
			case dem_read :
			{
				// Read the size of the packet, we'll need it to seek past it.
				len = VFS_READ(demfile, &size, 4, &err);
				DEMOPROBE_VALIDATE_READ(4, len, "when reading size");
				size = LittleLong(size);
				break;
			}
			case dem_set :
			{
				DEMOPROBE_SEEK(demfile, 4, "when reading incoming sequence number"); // 32-bit int.
				DEMOPROBE_SEEK(demfile, 4, "when reading outgoing sequence number"); // 32-bit int.
				break;
			}
			case dem_cmd :
			{
				// Only QWD.
				DEMOPROBE_SEEK(demfile, sizeof(usercmd_t), "when reading user movement cmd.");
				DEMOPROBE_SEEK(demfile, 12, "when reading user viewangles cmd."); // 3 * 32-bit floats.
				break;
			}
			default :
			{
				Com_DPrintf("CL_ProbeDemo: Unsupported command type %d!\n", (command & 0x7));
				abort = true;
				break;
			}
		}

		// We're just trying to find out if this is an MVD so break if it is.
		if ((probetype == TRY_READ_MVD) && (mvd_only_count >= REGARD_AS_MVD_COUNT))
		{
			is_mvd = true;
			break;
		}

		if (abort)
			break;

		// Read any specified data if needed.
		DEMOPROBE_SEEK(demfile, size, "when reading size bytes of message");

		// MVD time is saved as the time since last frame,
		// so we need to keep track of the total seperatly.
		if (probetype == READ_MVD_TIME)
		{
			total_mvd_time += mvd_time;
		}

		message_count++;
	}

	// Return to the start of the file.
	VFS_SEEK(demfile, 0, SEEK_SET);

	if (demotime)
	{
		if (probetype == READ_MVD_TIME)
		{
			// Convert mvd time to seconds.
			*demotime = total_mvd_time * 0.001;
		}
		else if (probetype == READ_QWD_TIME)
		{
			*demotime = qwd_time;
		}

		Com_DPrintf("CL_DemoProbe: Time: %f\n", *demotime);
	}

	// Is this a really short MVD, that doesn't contain our threshold of MVD only messages
	// but still enough for it to likely be one.
	if (!is_mvd 
		&& (probetype == TRY_READ_MVD)
		&& (message_count > 0) 
		&& (((float)mvd_only_count / message_count) >= 0.1))
	{
		is_mvd = true;
	}

	return is_mvd;
}

//
// Try to guess if this is an MVD by trying to parse it as one.
//
qbool CL_GetIsMVD(vfsfile_t *demfile)
{
	return CL_ProbeDemo(demfile, TRY_READ_MVD, NULL);
}

//
// Try to calculate the time of a demo.
//
float CL_CalculateDemoTime(vfsfile_t *demfile)
{
	float demotime = 0.0;

	CL_ProbeDemo(demfile, (cls.mvdplayback ? READ_MVD_TIME : READ_QWD_TIME), &demotime);

	return demotime;
}

//
// Returns true if the specified filename has a demo extension.
//
qbool CL_IsDemoExtension(const char *filename)
{
	char *ext = COM_FileExtension(filename);

	return (!strncasecmp(ext, "mvd", sizeof("mvd"))
		 || !strncasecmp(ext, "qwd", sizeof("qwd"))
		 || !strncasecmp(ext, "dem", sizeof("dem"))
		 || !strncasecmp(ext, "qwz", sizeof("qwz")));
}

//
// Resets various states for beginning playback.
//
static void CL_DemoPlaybackInit(void)
{	
	cls.demoplayback	= true;	

	// Set demoplayback vars depending on the demo type.
	// CL_GetIsMVD(playbackfile); 
	// TODO : Add a similar check for QWD also (or DEM), so that we can distinguish if it's a DEM or not playing also
	// TODO : Make a working check if a demo really is an mvd by its contents that also works on short demos.
	cls.mvdplayback		= !strcasecmp(COM_FileExtension(cls.demoname), "mvd"); 
	cls.nqdemoplayback	= !strcasecmp(COM_FileExtension(cls.demoname), "dem");

	 // Init some buffers for reading.
	CL_Demo_PB_Init(NULL, 0);

	// NetQuake demo support.
	if (cls.nqdemoplayback)
	{
		NQD_StartPlayback();
		demo_time_length = -1.0;
	}
	else
	{
		// Calculate the demo time.
		double start = Sys_DoubleTime();
		demo_time_length = CL_CalculateDemoTime(playbackfile);
		Com_DPrintf("Demo probe took %f seconds.\n", Sys_DoubleTime() - start);
	}

	// Setup the netchan and state.
	Netchan_Setup(NS_CLIENT, &cls.netchan, net_from, 0);
	cls.state		= ca_demostart;
	cls.demotime	= 0;
	demostarttime	= -1.0;
	olddemotime		= 0;
	nextdemotime	= 0;
	cls.findtrack	= true;
	bufferingtime	= 0;

	// Used for knowing who messages is directed to in MVD's.
	cls.lastto		= 0;
	cls.lasttype	= 0;

	CL_ClearPredict();

	// Recording not allowed during mvdplayback.
	if (cls.mvdplayback && cls.demorecording)
	{
		CL_Stop_f();
	}
}

//
// Starts playback of a demo.
//
void CL_Play_f (void)
{
	#ifndef WITH_VFS_ARCHIVE_LOADING
	#ifdef WITH_ZIP
	char unpacked_path[MAX_OSPATH];
	#endif // WITH_ZIP
	#endif // WITH_VFS_ARCHIVE_LOADING

	char *real_name;
	char name[MAX_OSPATH], **s;
	static char *ext[] = {"qwd", "mvd", "dem", NULL};

	// Show usage.
	if (Cmd_Argc() != 2)
	{
		Com_Printf ("Usage: %s <demoname>\n", Cmd_Argv(0));
		return;
	}

	// Save the name the user specified.
	real_name = Cmd_Argv(1);

	// Disconnect any current game.
	Host_EndGame();

	TP_ExecTrigger("f_demostart");
	
	// VFS-FIXME: This will affect playing qwz inside a zip
	#ifndef WITH_VFS_ARCHIVE_LOADING 
	#ifdef WITH_ZIP
	//
	// Unpack the demo if it's zipped or gzipped. And get the path to the unpacked demo file.
	//
	if (CL_GetUnpackedDemoPath (Cmd_Argv(1), unpacked_path, sizeof(unpacked_path)))
	{
		real_name = unpacked_path;
	}
	#endif // WITH_ZIP
	#endif // WITH_VFS_ARCHIVE_LOADING

	#ifdef WIN32
	//
	// Decompress QWZ demos to QWD before playing it (using an external app).
	//
	strlcpy (name, real_name, sizeof(name) - 4);

	if (strlen(name) > 4 && !strcasecmp(COM_FileExtension(name), "qwz"))
	{
		PlayQWZDemo();

		// We failed to extract the QWZ demo.
		if (!playbackfile && !qwz_playback)
		{
			return;
		}

		playbackfile = FS_OpenVFS (tempqwd_name, "rb", FS_NONE_OS);
	}
	else
	#endif // WIN32

	#ifndef WITH_VFS_ARCHIVE_LOADING
	{
		//
		// Find the demo path, trying different extensions if needed.
		//

		// If they specified a valid extension, try that first
		for (s = ext; *s && !playbackfile; ++s)
			if (!strcasecmp(COM_FileExtension(name), *s)) 
				playbackfile = CL_Open_Demo_File(name, true, NULL);

		for (s = ext; *s && !playbackfile; s++)
		{
			// Strip the extension from the specified filename and append
			// the one we're currently checking for.
			COM_StripExtension(real_name, name);
			strlcpy(name, va("%s.%s", name, *s), sizeof(name));

			playbackfile = CL_Open_Demo_File(name, true, NULL);
		}
	}
	#else // WITH_VFS_ARCHIVE_LOADING
	{
		char *file_ext = COM_FileExtension(Cmd_Argv(1));
		if (!playbackfile)
		{
			// Check the file extension is valid
			for (s = ext; *s; s++) 
			{
				if (strcmp(*s, file_ext) == 0)
					break;
			}
			if (*s != NULL)
			{
				strlcpy (name, real_name, sizeof(name));
				if (!strncmp(name, "../", 3) || !strncmp(name, "..\\", 3))
				{
					playbackfile = FS_OpenVFS(va("%s/%s", com_basedir, name + 3), "rb", FS_NONE_OS);
				}
				else
				{
					// Search demo on quake file system, even in paks.
					playbackfile = FS_OpenVFS(name, "rb", FS_ANY);
				}

				// Look in the demo dir (user specified).
				if (!playbackfile)
				{
					playbackfile = FS_OpenVFS(va("%s/%s", CL_DemoDirectory(), name), "rb", FS_NONE_OS);
				}

				// Check the full system path (Run a demo anywhere on the file system).
				if (!playbackfile)
				{
					playbackfile = FS_OpenVFS(name, "rb", FS_NONE_OS);
				}

				if (playbackfile)
					strlcpy(name, Cmd_Argv(1), sizeof(name));
			}
		}
	}
	#endif // WITH_VFS_ARCHIVE_LOADING else

	// Read the file completely into memory
	if (playbackfile) 
	{
		size_t len;
		void *buf;
		vfsfile_t *mmap_file;

		len = VFS_GETLEN(playbackfile);
		buf = Q_malloc(len);

		VFS_READ(playbackfile, buf, len, NULL);
		if (!(mmap_file = FSMMAP_OpenVFS(buf, len))) 
		{
			// Couldn't create the memory file, just remove the buffer
			Q_free(buf);
		}
		else 
		{
			// Close the file on disk now that we have read the file into memory
			VFS_CLOSE(playbackfile);
			playbackfile = mmap_file;
		}
	}

	// Failed to open the demo from any path :(
	if (!playbackfile)
	{
		Com_Printf ("Error: Couldn't open %s\n", Cmd_Argv(1));
		return;
	}

	strlcpy(cls.demoname, name, sizeof(cls.demoname));

	// Reset multiview track slots.
	memset(mv_trackslots, -1, sizeof(mv_trackslots));
	nTrack1duel			= 0;
	nTrack2duel			= 0;
	mv_skinsforced		= false;

	// Reset stuff so demo rewinding works.
	cls.demoseeking		= DST_SEEKING_NONE;
	cls.demorewinding	= false;
	cls.demo_rewindtime = 0;

	CL_DemoPlaybackInit();

	Com_Printf("Playing demo from %s\n", COM_SkipPath(name));
}

static vfsfile_t* CL_Open_Demo_File(char* name, qbool searchpaks, char** fullPath)
{
	static char fullname[MAX_OSPATH];
	vfsfile_t *file = NULL;

	memset(fullname, 0, sizeof(fullname));
	if (fullPath != NULL)
		*fullPath = fullname;

	// Look for the file in the above directory if it has ../ prepended to the filename.
	if (!strncmp(name, "../", 3) || !strncmp(name, "..\\", 3))
	{
		snprintf(fullname, MAX_OSPATH, "%s/%s", com_basedir, name + 3);
		file = FS_OpenVFS(fullname, "rb", FS_NONE_OS);
	}
	else if (searchpaks)
	{
		// Search demo on quake file system, even in paks.
		strncpy(fullname, name, MAX_OSPATH);
		file = FS_OpenVFS(name, "rb", FS_ANY);
	}

	// Look in the demo dir (user specified).
	if (!file)
	{
		snprintf(fullname, MAX_OSPATH, "%s/%s", CL_DemoDirectory(), name);
		file = FS_OpenVFS(fullname, "rb", FS_NONE_OS);
	}

	// Check the full system path (Run a demo anywhere on the file system).
	if (!file)
	{
		strncpy(fullname, name, MAX_OSPATH);
		file = FS_OpenVFS(name, "rb", FS_NONE_OS);
	}

	return file;
}

//
// Renders a demo as quickly as possible.
//
void CL_TimeDemo_f (void)
{
	if (Cmd_Argc() != 2)
	{
		Com_Printf ("timedemo <demoname> : gets demo speeds\n");
		return;
	}

	CL_Play_f ();

	// We failed to start demoplayback.
	if (cls.state != ca_demostart)
		return;

	// cls.td_starttime will be grabbed at the second frame of the demo,
	// so all the loading time doesn't get counted.

	cls.timedemo = true;
	cls.td_starttime = 0;
	cls.td_startframe = cls.framecount;
	cls.td_lastframe = -1;		// Get a new message this frame.
}

void CL_QTVPlay (vfsfile_t *newf, void *buf, int buflen);

char qtvrequestbuffer[512 * 1024] = {0}; // mmm, demo list may be pretty long
int  qtvrequestsize = 0;

char qtvpassword[128] = {0};

vfsfile_t *qtvrequest = NULL;

//
// Closes a QTV request.
//
void QTV_CloseRequest(qbool warn)
{
	if (qtvrequest)
	{
		if (warn)
			Com_Printf("Closing qtv request file\n");

		VFS_CLOSE(qtvrequest);
		qtvrequest = NULL;
	}

	qtvrequestsize = 0;
}

//
// Polls a QTV proxy. (Called on each frame to see if we have a new QTV request available)
//
void CL_QTVPoll (void)
{
	char QTVSV[] = "QTVSV ";
	int	 QTVSVLEN = sizeof(QTVSV)-1;

	char hash[512] = {0};
	char challenge[128] = {0};
	char authmethod[128] = {0};
	vfserrno_t err;
	char *start, *end, *colon;
	int len, need, chunk_size;
	qbool streamavailable = false;
	qbool saidheader = false;
	float svversion = 0;
	int qtv_ezquake_ext = 0;

	// We're not playing any QTV stream.
	if (!qtvrequest)
		return;

	//
	// Calculate how much we need to read from the buffer.
	//
	need = sizeof(qtvrequestbuffer); // Read the entire buffer
	need -= 1;						// For null terminator.
	need -= qtvrequestsize;			// We probably already have something, so don't re-read something we already read.
	need = max(0, need);			// Don't cause a crash by trying to read a negative value.

	len = VFS_READ(qtvrequest, qtvrequestbuffer + qtvrequestsize, need, &err);

	// EOF, end of polling.
	if (!len && err == VFSERR_EOF)
	{
		QTV_CloseRequest(true);
		return;
	}

	// Increase how much we've read.
	qtvrequestsize += len;
	qtvrequestbuffer[qtvrequestsize] = '\0';

	// QTVSV not seen yet, abort.
	if (qtvrequestsize < QTVSVLEN)
		return;

	if (strncmp(qtvrequestbuffer, QTVSV, QTVSVLEN))
	{
		Com_Printf("Server is not a QTV server (or is incompatible)\n");
		QTV_CloseRequest(true);
		return;
	}

	// Make sure it's a complete chunk. "\n\n" specifies the end of a message.
	for (start = qtvrequestbuffer; *start; start++)
	{
		if (start[0] == '\n' && start[1] == '\n')
			break;
	}

	// We've reached the end and didn't find "\n\n" so the chunk is incomplete.
	if (!*start)
		return;

	svversion = atof(qtvrequestbuffer + QTVSVLEN);

	// server sent float version, but we compare only major version number here
	if ((int)svversion != (int)QTV_VERSION)
	{
		Com_Printf("QTV server doesn't support a compatible protocol version, returned %.2f, need %.2f\n", svversion, QTV_VERSION);
		QTV_CloseRequest(true);
		return;
	}

	start = qtvrequestbuffer;

	//
	// Loop through the request buffer line by line.
	//
	for (end = start; *end; )
	{
		// Found a new line.
		if (*end == '\n')
		{
			// Don't parse it again.
			*end = '\0';

			// Find the first colon in the string.
			colon = strchr(start, ':');

			// We found a request.
			if (colon)
			{
				// Remove the colon.
				*colon++ = '\0';

				while (*colon == ' ')
					colon++;

				//
				// Check the request type. Might be an error.
				//
				if (!strcmp(start, "PERROR"))
				{
					Com_Printf("QTV Error:\n%s\n", colon);
				}
				else if (!strcmp(start, "PRINT"))
				{
					Com_Printf("QTV:\n%s\n", colon);
				}
				else if (!strcmp(start, "TERROR"))
				{
					Com_Printf("QTV Error:\n%s\n", colon);
				}
				else if (!strcmp(start, "ADEMO"))
				{
					//
					// Print demos.
					//

					if (!saidheader)
					{
						saidheader = true;
						Com_Printf("Available Demos:\n");
					}

					Com_Printf("%s\n", colon);
				}
				else if (!strcmp(start, "ASOURCE"))
				{
					//
					// Print sources.
					//

					if (!saidheader)
					{
						saidheader = true;
						Com_Printf("Available Sources:\n");
					}

					Com_Printf("%s\n", colon);
				}
				else if (!strcmp(start, "AUTH"))
				{
					strlcpy(authmethod, colon, sizeof(authmethod));
				}
				else if (!strcmp(start, "CHALLENGE"))
				{
					strlcpy(challenge, colon, sizeof(challenge));
				}
				else if (!strcmp(start, "BEGIN"))
				{
					streamavailable = true;
				}
				else if (!strcmp(start, QTV_EZQUAKE_EXT))
				{
					qtv_ezquake_ext = atoi(colon);
				}
			}
			else
			{
				// What follows this is a stream.
				if (!strcmp(start, "BEGIN"))
				{
					streamavailable = true;
				}
				else if (!strncmp(start, "QTVSV ", 6))
				{
//					Com_Printf("QTVSV HEADER: %s\n", start);
				}
			}

			// From start to end, we have a line.
			start = end + 1;
		}

		end++;
	}

	// Get the size of the stream chunk.
	chunk_size = qtvrequestsize - (end - qtvrequestbuffer);

	if (chunk_size < 0)
	{
		Com_Printf("Error while parsing qtv request\n");
		QTV_CloseRequest(true);
		return;
	}

	// drop header
	qtvrequestsize = chunk_size;
	memmove(qtvrequestbuffer, end, qtvrequestsize);

//	Com_Printf("memmove: %d\n", qtvrequestsize);

	// We found a stream.
	if (streamavailable)
	{
		// Start playing the QTV stream.
		CL_QTVPlay(qtvrequest, qtvrequestbuffer, qtvrequestsize);
		cls.qtv_svversion = svversion;
		cls.qtv_ezquake_ext = qtv_ezquake_ext;
		qtvrequest = NULL;

		return;
	}

	// we need send auth now
	if (authmethod[0])
	{
		char connrequest[2048];

		if (!strcmp(authmethod, "PLAIN"))
		{
			snprintf(connrequest, sizeof(connrequest), 
					"%s" "AUTH: PLAIN\nPASSWORD: \"%s\"\n\n", QTV_CL_HEADER(QTV_VERSION, QTV_EZQUAKE_EXT_NUM), qtvpassword);

			VFS_WRITE(qtvrequest, connrequest, strlen(connrequest));

			return;
		}
		else if (!strcmp(authmethod, "CCITT"))
		{
			if (strlen(challenge)>=32)
			{
				unsigned short crcvalue;

				snprintf(hash, sizeof(hash), "%s%s", challenge, qtvpassword);
				crcvalue = CRC_Block((byte *)hash, strlen(hash));
				snprintf(hash, sizeof(hash), "0x%X", (unsigned int)CRC_Value(crcvalue));
				snprintf(connrequest, sizeof(connrequest), 
					"%s" "AUTH: CCITT\nPASSWORD: \"%s\"\n\n", QTV_CL_HEADER(QTV_VERSION, QTV_EZQUAKE_EXT_NUM), hash);

				VFS_WRITE(qtvrequest, connrequest, strlen(connrequest));

				return;
			}

			Com_Printf("Wrong challenge for AUTH: %s\n", authmethod);
		}
		else if (!strcmp(authmethod, "MD4"))
		{
			if (strlen(challenge)>=8)
			{
				unsigned int md4sum[4];

				snprintf(hash, sizeof(hash), "%s%s", challenge, qtvpassword);
				Com_BlockFullChecksum (hash, strlen(hash), (unsigned char*)md4sum);
				snprintf(hash, sizeof(hash), "%X%X%X%X", md4sum[0], md4sum[1], md4sum[2], md4sum[3]);
				snprintf(connrequest, sizeof(connrequest), 
					"%s" "AUTH: MD4\nPASSWORD: \"%s\"\n\n", QTV_CL_HEADER(QTV_VERSION, QTV_EZQUAKE_EXT_NUM), hash);

				VFS_WRITE(qtvrequest, connrequest, strlen(connrequest));

				return;
			}

			Com_Printf("Wrong challenge for AUTH: %s\n", authmethod);
		}
		else if (!strcmp(authmethod, "NONE"))
		{
			snprintf(connrequest, sizeof(connrequest),
					"%s" "AUTH: NONE\nPASSWORD: \n\n", QTV_CL_HEADER(QTV_VERSION, QTV_EZQUAKE_EXT_NUM));

			VFS_WRITE(qtvrequest, connrequest, strlen(connrequest));

			return;
		}
		else
		{
			Com_Printf("Unknown auth method %s\n", authmethod);
		}
	}

	QTV_CloseRequest(true);
}

/*
 * Queries a QTV proxy for a list of available stream sources or demos
 * This function is used for both for qtvlist and qtvdemolist
 */
void CL_QTVList_f (void)
{
	char *connrequest;
	vfsfile_t *newf;
	qbool qtvlist = !strcmp("qtvlist", Cmd_Argv(0));

	if (Cmd_Argc() < 2) {
		Com_Printf("Usage: %s hostname[:port] [password]\n", Cmd_Argv(0));
		return;
	}

	// Open the TCP connection to the QTV proxy.
	newf = FS_OpenTCP(Cmd_Argv(1));
	if (newf == NULL) {
		Com_Printf("Couldn't connect to proxy\n");
		return;
	}

	strlcpy(qtvpassword, Cmd_Argv(2), sizeof(qtvpassword));

	// Send the version of QTV the client supports.
	connrequest = QTV_CL_HEADER(QTV_VERSION, QTV_EZQUAKE_EXT_NUM);
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	// Get a source list from the server.
	connrequest = qtvlist ? "SOURCELIST\n" : "DEMOLIST\n";
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	// Send our userinfo
	connrequest = "USERINFO: ";
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	connrequest = cls.userinfo;
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	connrequest =	"\n";
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	/* if we use pass, then send our supported auth methods */
	if (qtvpassword[0]) {
		connrequest = "AUTH: MD4\n" "AUTH: CCITT\n" "AUTH: PLAIN\n" "AUTH: NONE\n";
		VFS_WRITE(newf, connrequest, strlen(connrequest));
	}

	/* "\n\n" will end the session */
	connrequest = "\n";
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	/* Close any old request that might still be open */
	QTV_CloseRequest(true);

	/* Set the current connection to be the QTVRequest to be used later */
	qtvrequest = newf;
}

//
// Plays a QTV stream.
//
void CL_QTVPlay (vfsfile_t *newf, void *buf, int buflen)
{
	// End any current game.
	Host_EndGame();

	// Close the old playback file just in case, and
	// open the "network file" for QTV playback.
	if (playbackfile)
		VFS_CLOSE(playbackfile);
	playbackfile = newf;

	// Reset multiview track slots.
	memset(mv_trackslots, -1, sizeof(mv_trackslots));
	nTrack1duel = nTrack2duel = 0;
	mv_skinsforced = false;

	// We're now playing a demo.
	cls.demoplayback	= true;
	cls.mvdplayback		= QTV_PLAYBACK;
	cls.nqdemoplayback	= false;

	// Init playback buffers.
	CL_Demo_PB_Init(buf, buflen);

	// NetQuake demo support.
	if (cls.nqdemoplayback)
	{
		NQD_StartPlayback (); // Maybe some day QTV will stream NQ demos too...
	}

	// Setup demo playback for the netchan.
	cls.state = ca_demostart;
	Netchan_Setup (NS_CLIENT, &cls.netchan, net_from, 0);
	cls.demotime = 0;
	demostarttime = -1.0;
	olddemotime = nextdemotime = 0;
	cls.findtrack = true;

	cls.qtv_donotbuffer = true; // do not try buffering before "skins" not received

	bufferingtime = 0; // with eztv it correct, since eztv do not send data before we complete connection, so prebuffering is pointless

	// Used for knowing who messages is directed to in MVD's.
	cls.lastto = cls.lasttype = 0;

	CL_ClearPredict();

	// Recording not allowed during mvdplayback.
	if (cls.mvdplayback && cls.demorecording)
	{
		CL_Stop_f();
	}

	TP_ExecTrigger ("f_demostart");

	Com_Printf("Attempting to stream QTV data, buffer is %.1fs\n", (double)(QTVBUFFERTIME));
}

static char prev_qtv_connrequest[512]; /* FIXME: Stupid name, it might as well be ACTUAL streaming address */
static char prev_qtv_password[128];

char *CL_QTV_GetCurrentStream(void)
{
	if (cls.mvdplayback == QTV_PLAYBACK) {
		if (prev_qtv_connrequest[0]) {
			return &prev_qtv_connrequest[0];
		}
	}
	/* Not connected to QTV, no address then */
	return NULL;
}

//
// Reconnects to the previous QTV.
//
void CL_QTVReconnect_f (void)
{
	if (!prev_qtv_connrequest[0])
	{
		Com_Printf("No previous QTV proxy available to connect to.\n");
		return;
	}

	Cbuf_AddText(va("qtvplay %s %s\n", prev_qtv_connrequest, prev_qtv_password));
}

// checks if the argument is of the form http://quakeworld.fi:28000/watch.qtv?sid=8
// if so, issue a new qtvplay command with stream@hostname:port format
static qbool CL_QTVPlay_URL_format(void)
{
	const char *prefix = strstr(Cmd_Argv(1), "http://");
	const char *docpart = strstr(Cmd_Argv(1), "/watch.qtv?sid=");

	if (prefix && docpart && prefix == Cmd_Argv(1) && prefix < docpart) {
		int streamid = Q_atoi(docpart + strlen("/watch.qtv?sid="));
		int hostnamelen = docpart - prefix - strlen("http://");
		Cbuf_AddText(va("qtvplay %d@%.*s\n", streamid, hostnamelen, Cmd_Argv(1) + strlen("http://")));
		return true;
	}
	else {
		return false;
	}
}

//
// Start playback of a QTV stream.
//
void CL_QTVPlay_f (void)
{
	char *connrequest;
	vfsfile_t *newf;
	char stream_host[1024] = {0}, *stream, *host;

	// Show usage.
	if (Cmd_Argc() < 2)
	{
		Com_Printf("Usage: qtvplay [stream@]hostname[:port] [password]\n");
		return;
	}

	if (CL_QTVPlay_URL_format())
		return;

	strlcpy(qtvpassword, Cmd_Argv(2), sizeof(qtvpassword));

	// The stream address.
	connrequest = Cmd_Argv(1);

	// We've succesfully connected to a QTV proxy, save the connrequest string so we can use it to reconnect.
	strlcpy(prev_qtv_connrequest, connrequest, sizeof(prev_qtv_connrequest));
	strlcpy(prev_qtv_password, qtvpassword, sizeof(prev_qtv_password));

	//
	// If a "#" is at the beginning of the given address it refers to a .qtv file.
	//
	if (*connrequest == '#')
	{
		#define QTV_FILE_STREAM     1
		#define QTV_FILE_JOIN       2
		#define QTV_FILE_OBSERVE    3
		#define QTV_FILE_CHALLENGE  4
		int match = 0;

		char buffer[1024];
		char *s;
		FILE *f;

		// Try to open the .qtv file.
		f = fopen(connrequest + 1, "rt");
		if (!f)
		{
			Com_Printf("qtvplay: can't open file %s\n", connrequest + 1);
			return;
		}

		//
		// Read the entire .qtv file and execute the approriate commands
		// Stream, join or observe.
		//
		while (!feof(f))
		{
			if (fgets(buffer, sizeof(buffer) - 1, f) == NULL) {
				Com_Printf("Error reading the QTV file.\n");
				break;
			}

			if (!strncmp(buffer, "Stream=", 7) || !strncmp(buffer, "Stream:", 7))
			{
				match = QTV_FILE_STREAM;
			}

			if (!strncmp(buffer, "Join=", 5) || !strncmp(buffer, "Join:", 5))
			{
				match = QTV_FILE_JOIN;
			}

			if (!strncmp(buffer, "Observe=", 8) || !strncmp(buffer, "Observe:", 8))
			{
				match = QTV_FILE_OBSERVE;
			}

			if (!strncmp(buffer, "Challenge=", 10) || !strncmp(buffer, "Challenge:", 10))
			{
				match = QTV_FILE_CHALLENGE;
			}

			// We found a match in the .qtv file.
			if (match)
			{
				// Strip new line chars.
				for (s = buffer + strlen(buffer)-1; s >= buffer; s--)
				{
					if (*s == '\r' || *s == '\n')
					{
						*s = 0;
					}
					else
					{
						break;
					}
				}

				// Skip the title part.
				s = buffer;
				while(*s && *s != ':' && *s != '=') {
					s++;
				}
				if (*s) {
					s++;
				}

				// Remove any leading white spaces.
				while(*s && *s <= ' ')
				{
					s++;
				}

				// Call the appropriate commands based on the match.
				switch (match)
				{
					case QTV_FILE_STREAM :
						Cbuf_AddText(va("qtvplay \"%s\"\n", s));
						break;
					case QTV_FILE_JOIN :
						Cbuf_AddText(va("join \"%s\"\n", s));
						break;
					case QTV_FILE_OBSERVE :
						Cbuf_AddText(va("observe \"%s\"\n", s));
						break;
					case QTV_FILE_CHALLENGE:
						// URL is passed in, it needs to be further processed by the qwurl command
						Cbuf_AddText(va("qwurl \"%s\"\n", s));
						break;
				}

				// Break the while-loop we found what we want.
				break;
			}
		}

		// Close the file.
		fclose(f);
		return;
	}

	// The argument is the host address for the QTV server.

	// Find the position of the last @ char in the connection string,
	// this is when the user specifies a specific stream # on the QTV proxy
	// that he wants to stream. Default is to stream the first one.
	// [stream@]hostname[:port]
	// (QTV proxies can be chained, so we must get the last @)
	// In other words split stream and host part

	strlcpy(stream_host, connrequest, sizeof(stream_host));

	connrequest = strchrrev(stream_host, '@');
	if (connrequest)
	{
		stream = stream_host;		// Stream part.
		connrequest[0] = 0;			// Truncate.
		host   = connrequest + 1;	// Host part.
	}
	else
	{
		stream = "";				// Use default stream, user not specifie stream part.
		host   = stream_host;		// Arg is just host.
	}

	// Open a TCP socket to the specified host.
	newf = FS_OpenTCP(host);

	// Failed to open the connection.
	if (!newf)
	{
		Com_Printf("Couldn't connect to proxy %s\n", host);
		return;
	}

	// Send a QTV request to the proxy.
	connrequest = QTV_CL_HEADER(QTV_VERSION, QTV_EZQUAKE_EXT_NUM);
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	// If the user specified a specific stream such as "5@hostname:port"
	// we need to send a SOURCE request.
	if (stream[0])
	{
		connrequest =	"SOURCE: ";
		VFS_WRITE(newf, connrequest, strlen(connrequest));
		connrequest =	stream;
		VFS_WRITE(newf, connrequest, strlen(connrequest));
		connrequest =	"\n";
		VFS_WRITE(newf, connrequest, strlen(connrequest));
	}

	// Send our userinfo
	connrequest = "USERINFO: ";
	VFS_WRITE(newf, connrequest, strlen(connrequest));
	connrequest = cls.userinfo;
	VFS_WRITE(newf, connrequest, strlen(connrequest));
	connrequest =	"\n";
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	// if we use pass, then send our supported auth methods
	if (qtvpassword[0])
	{
		connrequest =
						"AUTH: MD4\n"
						"AUTH: CCITT\n"
						"AUTH: PLAIN\n"
						"AUTH: NONE\n";

		VFS_WRITE(newf, connrequest, strlen(connrequest));
	}

	// Two \n\n tells the server we're done.
	connrequest =	"\n";
	VFS_WRITE(newf, connrequest, strlen(connrequest));

	// We're finished requesting, but not done yet so save the
	// socket for the actual streaming :)
	QTV_CloseRequest(false);
	qtvrequest = newf;
}


//=============================================================================
//								DEMO TOOLS
//=============================================================================

//
// Sets the playback speed of a demo.
//
void CL_Demo_SetSpeed_f (void)
{
	extern cvar_t cl_demospeed;

	if (Cmd_Argc() != 2)
	{
		Com_Printf("Usage: %s [speed %%]\n", Cmd_Argv(0));
		return;
	}

	Cvar_SetValue(&cl_demospeed, atof(Cmd_Argv(1)) / 100.0);
}

//
// Cleans up after demo has been rewound to the correct point
//
void CL_Demo_Stop_Rewinding(void) 
{
	// Make sure we keep our tracked players after rewinding.
	memcpy(mv_trackslots, rewind_trackslots, sizeof(mv_trackslots));
	nTrack1duel			= rewind_duel_track1;
	nTrack2duel			= rewind_duel_track2;
	if (rewind_spec_track >= 0) 
	{
		Cam_Lock(rewind_spec_track);
	}
	else 
	{
		// Switch to free-floating camera and restore view
		Cam_Unlock();
		Cam_Pos_Set(rewind_pos[0], rewind_pos[1], rewind_pos[2]);
		Cam_Angles_Set(rewind_angle[0], rewind_angle[1], rewind_angle[2]);
	}
	cls.findtrack		= false;

	R_InitParticles();
	cls.demorewinding   = false;
}

// 
// Checks if demo needs to be rewound to previous point in time
//
void CL_Demo_Check_For_Rewind(float nextdemotime)
{
	// If we're seeking and our seek destination is in the past we need to rewind.
	if (cls.demoseeking && !cls.demorewinding && (cls.demotime < nextdemotime))
	{
		// Restart playback from the start of the file and then demo seek to the rewind spot.
		VFS_SEEK(playbackfile, 0, SEEK_SET);

		// We need to save track information.
		memcpy(rewind_trackslots, mv_trackslots, sizeof(rewind_trackslots));
		rewind_duel_track1 = nTrack1duel;
		rewind_duel_track2 = nTrack2duel;
		rewind_spec_track = WhoIsSpectated(); //spec_track;
		cls.findtrack = false;
		VectorCopy(cl.viewangles, rewind_angle);
		VectorCopy(cl.simorg, rewind_pos);

		// Restart the demo from scratch.
		CL_DemoPlaybackInit();

		prevtime			= 0.0;
		cls.demorewinding	= true;			
	}
	
	if (cls.demorewinding)
	{
		// If we've reached active state, we can set the new demotime
		// to trigger the demo seek to the desired location.
		// Before we're active, cl.demotime will just get overwritten.
		if (cls.state >= ca_active)
		{
			cls.demotime = demostarttime + cls.demo_rewindtime;
			cls.demoseeking = DST_SEEKING_NORMAL;
			//cls.demorewinding = false;

			// We have now finished restarting the demo and will now seek
			// to the new demotime just like we do when seeking forward.
		}
	}
}

//
// Jumps to a specified time in a demo.
//
void CL_Demo_Jump_f (void)
{
    int seconds = 0, seen_col, relative = 0;
    char *text, *s;
	static char *usage_message = "Usage: %s [+|-][m:]<s> (seconds)\n";

	// Cannot jump without playing demo.
	if (!cls.demoplayback)
	{
		Com_Printf("Error: not playing a demo\n");
        return;
	}

	// Must be active to jump.
	if (cls.state < ca_active)
	{
		Com_Printf("Error: demo must be active first\n");
		return;
	}

	// Show usage.
    if (Cmd_Argc() != 2)
	{
        Com_Printf(usage_message, Cmd_Argv(0));
        return;
    }

	// Get the jump string.
    text = Cmd_Argv(1);

	//
	// Parse which direction we're jumping in if
	// we're jumping relativly based on the current time.
	//
	if (text[0] == '-')
	{
		// Jumping backwards.
		text++;
		relative = -1;
	}
	else if (text[0] == '+')
	{
		// Jumping forward.
		text++;
		relative = 1;
	}
	else if (!isdigit(text[0]))
	{
		// Incorrect input, show usage message.
        Com_Printf(usage_message, Cmd_Argv(0));
        return;
	}

	// Find the number of colons (max 2 allowed) and make sure
	// we only have digits in the string.
	for (seen_col = 0, s = text; *s; s++)
	{
		if (*s == ':')
		{
			seen_col++;
		}
		else if (!isdigit(*s))
		{
			// Not a digit, show usage message.
			Com_Printf(usage_message, Cmd_Argv(0));
			return;
		}

		if (seen_col >= 2)
		{
			// More than two colons found, show usage message.
			Com_Printf(usage_message, Cmd_Argv(0));
			return;
		}
	}

	// If there's at least 1 colon we know everything
	// before it is minutes, so add it them to our jump time.
    if (strchr(text, ':'))
	{
        seconds += 60 * atoi(text);
        text = strchr(text, ':') + 1;
    }

	// The numbers after the first colon will be seconds.
    seconds += atoi(text);

	CL_Demo_Jump(seconds, relative, DST_SEEKING_NORMAL);
}

//
// Jumps to a specified time in a demo.
//
void CL_Demo_Jump_Mark_f (void)
{
	int seconds = 99999; // as far as possibile, we have NO idea about time, we search MARK

	// Cannot jump without playing demo.
	if (!cls.demoplayback)
	{
		Com_Printf("Error: not playing a demo\n");
        return;
	}

	// Must be active to jump.
	if (cls.state < ca_active)
	{
		Com_Printf("Error: demo must be active first\n");
		return;
	}

	CL_Demo_Jump(seconds, 0, DST_SEEKING_DEMOMARK);
}

static void CL_Demo_Jump_Status_Free (demoseekingstatus_condition_t *condition)
{
	if (condition == NULL)
		return;

	CL_Demo_Jump_Status_Free(condition->or);
	CL_Demo_Jump_Status_Free(condition->and);

	Q_free(condition);
}

static demoseekingstatus_condition_t *CL_Demo_Jump_Status_Condition_New (demoseekingstatus_matchtype_t type, int stat, int value)
{
	demoseekingstatus_condition_t *condition = Q_malloc(sizeof(demoseekingstatus_condition_t));

	condition->type = type;
	condition->stat = stat;
	condition->value = value;
	condition->or = NULL;
	condition->and = NULL;

	return condition;
}

static void CL_Demo_Jump_Status_Condition_Negate (demoseekingstatus_condition_t *condition)
{
	switch (condition->type) {
		case DEMOSEEKINGSTATUS_MATCH_EQUAL:
			condition->type = DEMOSEEKINGSTATUS_MATCH_NOT_EQUAL;
			break;
		case DEMOSEEKINGSTATUS_MATCH_NOT_EQUAL:
			condition->type = DEMOSEEKINGSTATUS_MATCH_EQUAL;
			break;
		case DEMOSEEKINGSTATUS_MATCH_LESS_THAN:
			condition->type = DEMOSEEKINGSTATUS_MATCH_GREATER_THAN;
			condition->value -= 1;
			break;
		case DEMOSEEKINGSTATUS_MATCH_GREATER_THAN:
			condition->type = DEMOSEEKINGSTATUS_MATCH_LESS_THAN;
			condition->value += 1;
			break;
		case DEMOSEEKINGSTATUS_MATCH_BIT_ON:
			condition->type = DEMOSEEKINGSTATUS_MATCH_BIT_OFF;
			break;
		case DEMOSEEKINGSTATUS_MATCH_BIT_OFF:
			condition->type = DEMOSEEKINGSTATUS_MATCH_BIT_ON;
			break;
		default:
			assert(false);
			break;
	}
}

static qbool CL_Demo_Jump_Status_Match (demoseekingstatus_condition_t *condition)
{
	if (condition->or && CL_Demo_Jump_Status_Match(condition->or))
		return true;

	switch (condition->type) {
		case DEMOSEEKINGSTATUS_MATCH_EQUAL:
			if (cl.stats[condition->stat] != condition->value)
				return false;
			break;
		case DEMOSEEKINGSTATUS_MATCH_NOT_EQUAL:
			if (cl.stats[condition->stat] == condition->value)
				return false;
			break;
		case DEMOSEEKINGSTATUS_MATCH_LESS_THAN:
			if (cl.stats[condition->stat] >= condition->value)
				return false;
			break;
		case DEMOSEEKINGSTATUS_MATCH_GREATER_THAN:
			if (cl.stats[condition->stat] <= condition->value)
				return false;
			break;
		case DEMOSEEKINGSTATUS_MATCH_BIT_ON:
			if (!(cl.stats[condition->stat] & condition->value))
				return false;
			break;
		case DEMOSEEKINGSTATUS_MATCH_BIT_OFF:
			if (cl.stats[condition->stat] & condition->value)
				return false;
			break;
		default:
			assert(false);
			return false;
	}

	if (condition->and != NULL) {
		return CL_Demo_Jump_Status_Match(condition->and);
	} else {
		return true;
	}
}

void CL_Demo_Jump_Status_Check (void)
{
	if (CL_Demo_Jump_Status_Match(cls.demoseekingstatus.conditions)) {
		if (cls.demoseekingstatus.non_matching_found) {
			CL_Demo_Jump_Status_Free(cls.demoseekingstatus.conditions);
			cls.demoseekingstatus.conditions = NULL;
			cls.demoseeking = DST_SEEKING_FOUND;
		}
	} else if (!cls.demoseekingstatus.non_matching_found) {
		cls.demoseekingstatus.non_matching_found = true;
	}
}

static int CL_Demo_Jump_Status_Parse_Weapon (const char *arg)
{
	if (!strcasecmp("axe", arg)) {
		return IT_AXE;
	} else if (!strcasecmp("sg", arg)) {
		return IT_SHOTGUN;
	} else if (!strcasecmp("ssg", arg)) {
		return IT_SUPER_SHOTGUN;
	} else if (!strcasecmp("ng", arg)) {
		return IT_NAILGUN;
	} else if (!strcasecmp("sng", arg)) {
		return IT_SUPER_NAILGUN;
	} else if (!strcasecmp("gl", arg)) {
		return IT_GRENADE_LAUNCHER;
	} else if (!strcasecmp("rl", arg)) {
		return IT_ROCKET_LAUNCHER;
	} else if (!strcasecmp("lg", arg)) {
		return IT_LIGHTNING;
	} else {
		return 0;
	}
}

static int CL_Demo_Jump_Status_Parse_Constraint (const char *arg, int *value)
{
	if (strlen(arg) < 2)
		return -1;

	*value = Q_atoi(arg+1);

	switch (arg[0]) {
		case '=':
			return DEMOSEEKINGSTATUS_MATCH_EQUAL;
		case '<':
			return DEMOSEEKINGSTATUS_MATCH_LESS_THAN;
		case '>':
			return DEMOSEEKINGSTATUS_MATCH_GREATER_THAN;
		default:
			return -1;
	}
}

//
// Jumps to a point in demo based on the status of player in POV
//
static void CL_Demo_Jump_Status_f (void)
{
	int i;
	qbool or = false;
	demoseekingstatus_condition_t *parent = NULL;

	if (Cmd_Argc() < 2) {
		Com_Printf("Usage: %s <conditions>\n", Cmd_Argv(0));
		Com_Printf("\n");
		Com_Printf("Skip forward in the demo until the conditions based on the player in POV are met.\n");
		Com_Printf("\n");
		Com_Printf("Valid conditions are:\n");
		Com_Printf("  Weapon, armor and powerup names (rl, ya, quad etc.), for items held\n");
		Com_Printf("  Weapon names with + in front (+rl), for the weapon in hand\n");
		Com_Printf("  Constraints on health, armor and ammo held with syntax id=value, id<value or id>value\n");
		Com_Printf("    The id can be h for health, a for armor, s for shells, n for nails, r for rockets or c for cells\n");
		Com_Printf("  All the conditions can be negated by inserting a ! character in front\n");
		Com_Printf("  Special value \"or\" can be used to connect two conditions requiring only one of them to be true\n");
		Com_Printf("\n");
		Com_Printf("Example: %s h<1 +rl or +lg\n", Cmd_Argv(0));
		Com_Printf("  Skip to the next position where player in the POV drops a RL or LG pack\n");
		return;
	}

	// Cannot jump without playing demo.
	if (!cls.demoplayback) {
		Com_Printf("Error: not playing a demo\n");
		return;
	}

	// Must be active to jump.
	if (cls.state < ca_active) {
		Com_Printf("Error: demo must be active first\n");
		return;
	}

	cls.demoseekingstatus.non_matching_found = false;
	CL_Demo_Jump_Status_Free(cls.demoseekingstatus.conditions);
	cls.demoseekingstatus.conditions = NULL;

	for (i = 1; i < Cmd_Argc(); i++) {
		demoseekingstatus_condition_t *condition = NULL;
		qbool neg = false;
		char *arg = Cmd_Argv(i);
		int weapon, value;
		int type;

		if (!strcasecmp("or", arg)) {
			if (cls.demoseekingstatus.conditions == NULL) {
				Com_Printf("Error: or can't be the first argument\n");
				return;
			}
			or = true;
			continue;
		}

		if (arg[0] == '!') {
			neg = true;
			arg++;
		}

		if ((weapon = CL_Demo_Jump_Status_Parse_Weapon(arg)) != 0) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, weapon);
		} else if (arg[0] == '+' && (weapon = CL_Demo_Jump_Status_Parse_Weapon(arg+1)) != 0) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_EQUAL, STAT_ACTIVEWEAPON, weapon);
		} else if (arg[0] == 'h' && (type = CL_Demo_Jump_Status_Parse_Constraint(arg+1, &value)) >= 0) {
			condition = CL_Demo_Jump_Status_Condition_New(type, STAT_HEALTH, value);
		} else if (arg[0] == 'a' && (type = CL_Demo_Jump_Status_Parse_Constraint(arg+1, &value)) >= 0) {
			condition = CL_Demo_Jump_Status_Condition_New(type, STAT_ARMOR, value);
		} else if (arg[0] == 's' && (type = CL_Demo_Jump_Status_Parse_Constraint(arg+1, &value)) >= 0) {
			condition = CL_Demo_Jump_Status_Condition_New(type, STAT_SHELLS, value);
		} else if (arg[0] == 'n' && (type = CL_Demo_Jump_Status_Parse_Constraint(arg+1, &value)) >= 0) {
			condition = CL_Demo_Jump_Status_Condition_New(type, STAT_NAILS, value);
		} else if (arg[0] == 'r' && (type = CL_Demo_Jump_Status_Parse_Constraint(arg+1, &value)) >= 0) {
			condition = CL_Demo_Jump_Status_Condition_New(type, STAT_ROCKETS, value);
		} else if (arg[0] == 'c' && (type = CL_Demo_Jump_Status_Parse_Constraint(arg+1, &value)) >= 0) {
			condition = CL_Demo_Jump_Status_Condition_New(type, STAT_CELLS, value);
		} else if (!strcasecmp("ga", arg)) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, IT_ARMOR1);
		} else if (!strcasecmp("ya", arg)) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, IT_ARMOR2);
		} else if (!strcasecmp("ra", arg)) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, IT_ARMOR3);
		} else if (!strcasecmp("quad", arg)) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, IT_QUAD);
		} else if (!strcasecmp("ring", arg)) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, IT_INVISIBILITY);
		} else if (!strcasecmp("pent", arg)) {
			condition = CL_Demo_Jump_Status_Condition_New(DEMOSEEKINGSTATUS_MATCH_BIT_ON, STAT_ITEMS, IT_INVULNERABILITY);
		} else {
			Com_Printf("Error: unknown condition: %s\n", Cmd_Argv(i));
			CL_Demo_Jump_Status_Free(cls.demoseekingstatus.conditions);
			cls.demoseekingstatus.conditions = NULL;
			return;
		}

		if (neg)
			CL_Demo_Jump_Status_Condition_Negate(condition);

		if (parent != NULL) {
			if (or) {
				parent->or = condition;
			} else {
				parent->and = condition;
			}
		} else {
			cls.demoseekingstatus.conditions = condition;
		}
		parent = condition;
		or = false;
	}

	CL_Demo_Jump(99999, 0, DST_SEEKING_STATUS);
}


//
// Jumps to a specified time in a demo. Time specified in seconds.
//
void CL_Demo_Jump(double seconds, int relative, demoseekingtype_t seeking)
{
	// Calculate the new demo time we want to jump to.
	double initialtime = (cls.nqdemoplayback ? cl.servertime : cls.demotime);
	double newdemotime = relative ? (initialtime + (relative * seconds)) : (demostarttime + seconds);

	// We need to rewind.
	if (newdemotime < initialtime)
	{
		cls.demo_rewindtime = newdemotime - demostarttime;
	}

	// Set the new demotime.	
	cls.demotime = newdemotime;

	cls.demoseeking = seeking;
}

double Demo_GetSpeed(void)
{
	if (cls.mvdplayback == QTV_PLAYBACK)
	{
		if (qtv_adjustbuffer.integer)
		{
			extern	unsigned char pb_buf[];
			extern	int		pb_cnt;

			int				ms;
			double			demospeed, desired, current;

			ConsistantMVDDataEx(pb_buf, pb_cnt, &ms);

			desired = max(0.5, QTVBUFFERTIME); // well, we need some reserve for adjusting
			current = 0.001 * ms;

			// qqshka: this is linear version
			demospeed = current / desired;

			// if you unwilling constant speed change, then you can set range with qtv_adjustlowstart and qtv_adjusthighstart
			if (demospeed > bound(0, qtv_adjustlowstart.value, 1) && demospeed < max(1, qtv_adjusthighstart.value))
				demospeed = 1;

			// bound demospeed
			demospeed = bound(qtv_adjustminspeed.value, demospeed, qtv_adjustmaxspeed.value);

			return demospeed;
		}
	}

	return bound(0, cl_demospeed.value, 20);
}

//
// Inits the demo cache and adds demo commands.
//
void CL_Demo_Init(void)
{
	int parm, democache_size;
	byte *democache_buffer;

	//
	// Init the demo cache if the user specified to use one.
	//
	democache_available = false;
	if ((parm = COM_CheckParm("-democache")) && parm + 1 < COM_Argc())
	{
		democache_size = Q_atoi(COM_Argv(parm + 1)) * 1024;
		democache_size = max(democache_size, DEMOCACHE_MINSIZE);
		if ((democache_buffer = (byte *) malloc (democache_size)))
		{
			Com_Printf_State (PRINT_OK, "Democache initialized (%.1f MB)\n", (float) (democache_size) / (1024 * 1024));
			SZ_Init(&democache, democache_buffer, democache_size);
			democache_available = true;
		}
		else
		{
			Com_Printf_State (PRINT_FAIL, "Democache allocation failed\n");
		}
	}

	//
	// Add demo commands.
	//
	Cmd_AddCommand ("record", CL_Record_f);
	Cmd_AddCommand ("recordqwd", CL_Record_f);
	Cmd_AddCommand ("stop", CL_Stop_f);
	Cmd_AddCommand ("stopqwd", CL_Stop_f);
	Cmd_AddCommand ("playdemo", CL_Play_f);
	Cmd_AddCommand ("timedemo", CL_TimeDemo_f);
	Cmd_AddCommand ("easyrecord", CL_EasyRecord_f);

	Cmd_AddCommand("demo_setspeed", CL_Demo_SetSpeed_f);
	Cmd_AddCommand("demo_jump", CL_Demo_Jump_f);
	Cmd_AddCommand("demo_jump_mark", CL_Demo_Jump_Mark_f);
	Cmd_AddCommand("demo_jump_status", CL_Demo_Jump_Status_f);
	Cmd_AddCommand("demo_controls", DemoControls_f);

	//
	// mvd "recording"
	//
	Cmd_AddCommand("mvdrecord", CL_RecordMvd_f);
	Cmd_AddCommand("mvdstop", CL_StopMvd_f);

	//
	// QTV commands.
	//
	Cmd_AddCommand ("qtvplay", CL_QTVPlay_f);
	Cmd_AddCommand ("qtv_query_sourcelist", CL_QTVList_f);
	Cmd_AddCommand ("qtv_query_demolist", CL_QTVList_f);
	Cmd_AddCommand ("qtvreconnect", CL_QTVReconnect_f);

	Cvar_SetCurrentGroup(CVAR_GROUP_DEMO);
#ifdef _WIN32
	Cvar_Register(&demo_format);
#endif
	Cvar_Register(&demo_dir);
	Cvar_Register(&demo_benchmarkdumps);
	Cvar_Register(&cl_startupdemo);

	Cvar_ResetCurrentGroup();
}