summaryrefslogtreecommitdiff
path: root/InfraStack/OSDependent/Linux/wimaxcu/wimaxcu.c
blob: ad187c40ec2ed47522caeabb69acdf1017f8ef80 (plain)
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
/**************************************************************************
Copyright (c) 2007-2008, Intel Corporation. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

 3. Neither the name of the Intel Corporation nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

***************************************************************************/
#include <pthread.h>
#include <unistd.h>
#include <limits.h>
#include <sys/time.h>

#define _XOPEN_SOURCE 600
#include <semaphore.h>
#include <sys/types.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <string.h>

#include <signal.h>
#include <execinfo.h>
#include <sys/types.h>
#include <sys/syslog.h>
#include <unistd.h>
#include <dirent.h>
#include <ctype.h>

#include "wimaxcu_defs.h"

#include "wimaxcu.h"
#include "wimaxcu_util.h"
// Globals...

#define MAX_DEVICE			5
#define MAX_PROFILE			32
#define MAX_LEN				80
#define WMX_SF_STATUS_MAX_NUM		100
#define VERSION_SDK_STR_MAX_SIZE	255
#define MAX_NSP_ID_LEN                  40

// used in Scan process
// Waits SCAN_TIMEOUT_IN_10SEC_ITREATIONS * 10 sec before time out
// Default value is SCAN_TIMEOUT_IN_10SEC_ITREATIONS 30 = 300 sec = 5 min
// can be modified depending upon the no of frequencies available
#define SCAN_TIMEOUT_IN_10SEC_ITREATIONS 60

/* get REG_EIP from ucontext.h */
#define __USE_GNU
#include <ucontext.h>

#define MAX_STR_LEN 256
#define MAX_FILENAME_LEN 256
	
WIMAX_API_DEVICE_ID DeviceID;

//static sem_t semWideScan;
static sem_t semConnectionUtility;
static sem_t semAPDOactivation;
static sem_t semAPDOupdates;
static sem_t semRfState;
static sem_t semConnectCompleted;
static pthread_mutex_t console_owner_mutex;
// static BOOL g_UpaterLaunched = FALSE;

static WIMAX_API_DEVICE_STATUS g_devState;

static char g_sznspName[MAX_SIZE_OF_NSP_NAME];
static char foOperationType[NAME_MAX];
// for user command for activation
void *userinfo(void *ptr);
// time out sem function
int wmxcu_sem_timeout(sem_t* s,int milliseconds);

int g_noNetworksFound = 1;
int g_searchProgress = 0;

// Set preferred NSP
int preferred_NSP_ID = 0;

static char gcLogFilePathName[MAX_FILENAME_LEN];


/*
 * Function:     Initialize
 * Description:  Initialize the WiMAX CommonAPI
 */
WIMAX_API_RET Initialize (WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_HW_DEVICE_ID HwDeviceIdList[MAX_DEVICE];
	UINT32 numDevice = MAX_DEVICE;

	memset(HwDeviceIdList, 0, sizeof(WIMAX_API_HW_DEVICE_ID) * MAX_DEVICE);

	// open the Common API and initialize iwmax sdk, agents
    wmxStatus = WiMaxAPIOpen(pDeviceID);
	if (WIMAX_API_RET_SUCCESS != wmxStatus)
    {
        return wmxStatus;
	}

	// get the list of the device before open the device
	wmxStatus = GetListDevice(pDeviceID,
                              (WIMAX_API_HW_DEVICE_ID_P)HwDeviceIdList,
                              &numDevice);
	if (WIMAX_API_RET_SUCCESS != wmxStatus)
    {
		return wmxStatus;
	}

	pDeviceID->deviceIndex = HwDeviceIdList[0].deviceIndex;

	// Open the device to get the permission
	wmxStatus = WiMaxDeviceOpen(pDeviceID);
	if (WIMAX_API_RET_SUCCESS != wmxStatus)
    {
		return wmxStatus;
	}
	if (pthread_mutex_init(&console_owner_mutex, NULL) != 0) {
		printf("Internal Error!\n");
		return WIMAX_API_RET_FAILED;
	}

	if (sem_init(&semConnectionUtility, 0, 0) == -1) {
		printf("Internal Error!\n");
	return WIMAX_API_RET_FAILED;
	}

	if (sem_init(&semRfState, 0, 0) == -1) {
		printf("Internal Error!\n");
	return WIMAX_API_RET_FAILED;
	}

        if (sem_init(&semConnectCompleted, 0, 0) == -1) {
            printf("Internal Error!\n");
            return WIMAX_API_RET_FAILED;
        }

	wmxStatus = SubscribeDeviceStatusChange(pDeviceID, &IndDeviceUpdateCB);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
      		PrintWmxStatus(wmxStatus);
      		return WIMAX_API_RET_FAILED;
    	}

    return WIMAX_API_RET_SUCCESS;
}

/*
 * Function:     Finalize
 * Description:  Finalize the WiMAX CommonAPI
 */
void Finalize(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	UnsubscribeDeviceStatusChange(pDeviceID);

    	WiMaxDeviceClose(pDeviceID);
    	WiMaxAPIClose(pDeviceID);

	// Let all the call backs get closed before destroying sem
	sem_destroy(&semConnectionUtility);
	sem_destroy(&semRfState);
        sem_destroy(&semConnectCompleted);
	pthread_mutex_destroy(&console_owner_mutex);

}



/*
 * Function:     ResetDevice
 * Description:  Reset the wimax device
 * Return:       0 for success or 1 for failure
 *
 * Note: this will return 1 always for now since not implemented
 */
int ResetDevice(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;

	wmxStatus = CmdResetWimaxDevice(pDeviceID);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        	PrintWmxStatus(wmxStatus);
		return 1;
	}
	return 0;
}

/*
 * Function:     ResetToFactorySettings
 * Description:  Reset to the factory default setting
 * Return:       0 for success or 1 for failure
 */
int ResetToFactorySettings(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;
               
	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	if (DeviceStatus != WIMAX_API_DEVICE_STATUS_RF_OFF_SW) {
		printf("WARNING!! The radio must be turned off to reset to factory setting.\n");
		printf("          This operation will erase previously stored scanned results\n");
		printf("          and you will lose the ability to connect to the preferred NSP.\n");
		return 1;
	}
	
	wmxStatus = CmdResetToFactorySettings(pDeviceID);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	printf("WiMAX system is set to factory settings.\n");
	return 0;
}

/*
 * Function:     GetUserConnectMode
 * Description:  Get the user connection mode
 * Return:       0 for success or 1 for failure
 */
int GetUserConnectMode(WIMAX_API_DEVICE_ID_P pDeviceID)
{
    WIMAX_API_CONNECTION_MODE connectMode;
	WIMAX_API_RET wmxStatus;

    wmxStatus = GetConnectionMode(pDeviceID,&connectMode);
    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	   PrintWmxStatus(wmxStatus);
	return 1;
	}

	PrintUserConnectionMode(connectMode);
    return 0;
}


/*
 * Function:     SetUserConnectMode
 * Description:  Change the user connect mode
 * Return:       0 for success or 1 for failure
 */
int SetUserConnectMode(WIMAX_API_DEVICE_ID_P pDeviceID,
			char *connect_mode, char *scan_mode)
{
	int ret;
	WIMAX_API_RET wmxStatus;
	WIMAX_API_CONNECTION_MODE userConnectMode, currentConnectMode;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

    wmxStatus = GetConnectionMode(pDeviceID, &currentConnectMode);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        PrintWmxStatus(wmxStatus);
	return 1;
	}

    userConnectMode = currentConnectMode;
    ret = ConvertCharToConnectionMode(connect_mode, scan_mode, &userConnectMode);
	if (ret == -1) {
        	printf("Specified Scan/Connect mode(s) not recognized.\n");
		PrintUserConnectionMode(currentConnectMode);
	return 1;
	} else if (ret == -2) {
		printf("WARNING: Invalid connect and scan combination.\n");
		printf("Auto connection requires semi scan mode.\n");
		PrintUserConnectionMode(currentConnectMode);
	return 1;
    }

    if(userConnectMode == currentConnectMode) {
        printf("The specified connect mode is already in place.\n");
        PrintUserConnectionMode(currentConnectMode);
	return 1;
    }

	wmxStatus = SetConnectionMode(pDeviceID,userConnectMode);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		// PrintWmxStatus(wmxStatus);
		if (WIMAX_API_RET_FAILED == wmxStatus) {
			BOOL isEnable;
			wmxStatus = GetConnectedAsCurrentPreferredCapabilityStatus(pDeviceID, &isEnable);
			if(wmxStatus==WIMAX_API_RET_SUCCESS)
			{
				if (isEnable == FALSE)
				{
					printf("Current Connected Network Preferred settings are disabled\n");
					printf("Hence could not set the connect mode to Auto \n");
					printf("Going back to the pprevious connect mode \n");
					wmxStatus = SetConnectionMode(pDeviceID,currentConnectMode);
					if (WIMAX_API_RET_SUCCESS != wmxStatus)
					{
						PrintWmxStatus(wmxStatus);
					}
					else
					{
						PrintUserConnectionMode(currentConnectMode);
					}
					return 1;
				}
				else
				{
					printf("Operation Failed \n");
					return 1;
				}
			}
		}
		PrintWmxStatus(wmxStatus);
		return 1;
	}

    // Unset the preferred NSP
    if(userConnectMode == WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT) {
	preferred_NSP_ID = 0;
	SetCurrentPreferredProfiles(pDeviceID, &preferred_NSP_ID, 0);
    }
    PrintUserConnectionMode(userConnectMode);
    if (ret == 1 ) {
	wmxStatus =
	    GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	    return 2;
	}
	switch (DeviceStatus) {
    		case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW:
	        printf("WARNING: Both HW and SW Radio is OFF.\n");
		break;
		case WIMAX_API_DEVICE_STATUS_RF_OFF_HW:
		printf("WARNING: HW Radio is OFF.\n");
		break;
		case WIMAX_API_DEVICE_STATUS_RF_OFF_SW:
        	printf("WARNING: SW Radio is OFF.\n");
		break;
	default:
	break;
	}
    }
    return 0;
}

/*
 * Function:     GetSystemStatus
 * Description:  Get the WiMAX device status from the GetDeviceStatus API
 * Return:       0 for success or 1 for failure
 */
int GetSystemStatus(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	wmxStatus =
	    GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 1;
	}

	PrintDeviceStatus(DeviceStatus);
    return 0;
}


/*
 * Function:     GetConnectStatus
 * Description:  Get the current connection status of WiMAX Device
 * Return:       0 for success or 1 for failure
 */
int GetConnectStatus(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	wmxStatus =
	    GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 1;
	}

	PrintDeviceStatus(DeviceStatus);

    // if connected or idle, display connected NSP info
    if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Data_Connected)
    {
        GetConnNSP(pDeviceID);
        GetConnTime(pDeviceID);
    }

    return 0;
}

/*
 * Function:     GetRfStatus
 * Description:  Get WiMAX radio status
 * Return:       0 for success or 1 for failure
 */
int GetRfStatus(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	wmxStatus =
	    GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 1;
	}

	printf("Radio Status: ");
    	switch (DeviceStatus) {
        case WIMAX_API_DEVICE_STATUS_UnInitialized:
            printf("Device is not ready\n");
            break;
        case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW:
            printf("HW and SW Radios are OFF\n");
            break;
        case WIMAX_API_DEVICE_STATUS_RF_OFF_HW:
            printf("HW radio is OFF\n");
            break;
        case WIMAX_API_DEVICE_STATUS_RF_OFF_SW:
            printf("SW radio is OFF\n");
            break;
        default:
            printf("HW and SW radios are ON\n");
	}
    return 0;
}

int IsNetworkActivated(WIMAX_API_DEVICE_ID_P pDeviceID,
		       WIMAX_API_NSP_INFO_P nspInfo)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	UINT32 numProfileList = MAX_PROFILE;
	int i = 0;
	WIMAX_API_PROFILE_INFO_P  profilelist= (WIMAX_API_PROFILE_INFO_P)
			malloc(sizeof(WIMAX_API_PROFILE_INFO)*MAX_PROFILE);
	memset(profilelist,0,sizeof(WIMAX_API_PROFILE_INFO)*MAX_PROFILE);

	wmxStatus = GetSelectProfileList(pDeviceID,profilelist,&numProfileList);
	if ( wmxStatus != WIMAX_API_RET_SUCCESS )
	{
		PrintWmxStatus(wmxStatus);
		free (profilelist);
		return 0;
	}
	for ( i = 0; i < numProfileList; i++)
	{
        // check the match
        if  ((nspInfo->NSPid & 0xffffff) == profilelist[i].profileID )
        {
            free (profilelist);
            return 1;
        }
    }
	free (profilelist);
	// get the profile list and compare with nspid and return the result
	return 0;

}
int IsNetworkActivatedEx(WIMAX_API_DEVICE_ID_P pDeviceID,
		       WIMAX_API_NSP_INFO_EX_P nspInfo)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	UINT32 numProfileList = MAX_PROFILE;
	int i = 0;
	WIMAX_API_PROFILE_INFO_P  profilelist= (WIMAX_API_PROFILE_INFO_P)
			malloc(sizeof(WIMAX_API_PROFILE_INFO)*MAX_PROFILE);
	memset(profilelist,0,sizeof(WIMAX_API_PROFILE_INFO)*MAX_PROFILE);

	wmxStatus = GetSelectProfileList(pDeviceID,profilelist,&numProfileList);
	if ( wmxStatus != WIMAX_API_RET_SUCCESS )
	{
		PrintWmxStatus(wmxStatus);
		free (profilelist);
		return 0;
	}
	for ( i = 0; i < numProfileList; i++)
	{
        // check the match
		if  ((nspInfo->NSPid & 0xffffff) == profilelist[i].profileID )
		{
			free (profilelist);
			return 1;
		}
	}
	free (profilelist);
	// get the profile list and compare with nspid and return the result
	return 0;

}

int GetNListEx(WIMAX_API_DEVICE_ID_P pDeviceID, CMD_ARGS scan_mode)
{
	int ret = 0;
	WIMAX_API_RET wmxStatus;
	int time_out = 0;
	WIMAX_API_CONNECTION_MODE connectMode;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;
	WIMAX_API_NSP_INFO_EX_P pNspInfo;

	UINT32 numOfNSPs = 20;
	int i = 0;

	// initialize the variable as No Networks found
	g_noNetworksFound = 1;
	g_searchProgress = 0;
	// get the device status
	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
	}

	switch(DeviceStatus) {
	case WIMAX_API_DEVICE_STATUS_UnInitialized:  /**<  Device is uninitialized */
	  printf("ERROR: Device not Initialized\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW:   /**<  Device RF Off(both H/W and S/W) */
	printf
	    ("WARNING: HW and SW Radios are OFF.\nPlease turn ON the HW and SW Radios to perform a scan.\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_RF_OFF_HW:      /**<  Device RF Off(via H/W switch) */
	printf
	    ("WARNING: HW Radio is OFF.\nPlease turn ON the HW Radio to perform a scan.\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_RF_OFF_SW:      /**<  Device RF Off(via S/W switch) */
	printf
	    ("WARNING: SW Radio is OFF.\nPlease turn ON the SW Radio to perform a scan.\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_Ready:          /**<  Device is ready */
	case WIMAX_API_DEVICE_STATUS_Scanning:       /**<  Device is scanning */
	  break;
	case WIMAX_API_DEVICE_STATUS_Connecting:     /**<  Connection in progress */
	  printf("WARNING: Connection is in progress\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_Data_Connected:	/**<  Layer 2 connected */
	printf
	    ("WARNING: Connection already established!\nPlease disconnect, before attempting to scan.\n");
	return 2;
	default:
	  printf("ERROR: Device status Unknown.\n");
	return 2;
	}



	wmxStatus =
			SubscribeRfTaken(pDeviceID,&IndRFTakenCB);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
	}
	wmxStatus = GetConnectionMode(pDeviceID,&connectMode);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
	}

	if (connectMode == WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT
		   && DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) {
		printf
				("WARNING: Scanning is in progress\nPlease wait for the current scan to complete.\n");
		return 2;
		   }

		   if (scan_mode == CMD_SCAN_ARG_PREFERRED) {

			   wmxStatus = SubscribeNetworkSearchEx(pDeviceID,&IndNetworkSearchCBEx );
			   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				   PrintWmxStatus(wmxStatus);
				   return 2;
			   }
			   /* In Manual mode always scan do not read the cache as we don't know when cache was updated */
			   if (connectMode != WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT) {
				   pNspInfo = (WIMAX_API_NSP_INFO_EX_P )malloc(MAX_LEN * sizeof(WIMAX_API_NSP_INFO_EX));
				   memset(pNspInfo, 0, sizeof(WIMAX_API_NSP_INFO_EX) * MAX_LEN);
				   wmxStatus = GetNetworkListEx(pDeviceID, pNspInfo, &numOfNSPs);
				   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
					   PrintWmxStatus(wmxStatus);
				/*
					   If the Device is already scanning, it won't allow one more AppSrv will reject it
					   with the Operation Falied error
				*/
					   free(pNspInfo);
					   return 1;
				   }

				   if(numOfNSPs != 0) {
					   for (i = 0; i < numOfNSPs; i++)
					   {
						   printf("\nNetwork found.\n");
						   PrintNSPInfoEx(&pNspInfo[i]);
						   if  (IsNetworkActivatedEx(pDeviceID,&pNspInfo[i]) )
							   printf("\tActivated\n");
						   else
							   printf("\tNot Activated\n");
					   }
					   return 0;
				   }
			   }

			   wmxStatus = CmdNetworkSearch(pDeviceID);

			   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				   PrintWmxStatus(wmxStatus);
				   if ((DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) && (wmxStatus == WIMAX_API_RET_FAILED)) {
					   printf("WARNING: Scanning is in progress\nPlease wait for the current scan to complete.\n");
				   }
				   return 1;
			   }

			   printf("Scanning %2d%% Done ", g_searchProgress);
			   fflush(stdout);
			   do {
				   if (wmxcu_sem_timeout(&semConnectionUtility,5*1000) == 1 )
				   {
					   time_out++;
					   if (pthread_mutex_trylock(&console_owner_mutex) == 0) {
						   printf("\r");
						   printf("Scanning %2d%% Done ", g_searchProgress);
					// printf("Scanning %2d% Done [", g_searchProgress);

						   for(i = 0; i<=time_out; i++)
						   {
							   printf("=");
						   }
						   printf("-");
// 					for(i = 0; i<=SCAN_TIMEOUT_IN_10SEC_ITREATIONS - time_out; i++)
// 					{
// 						printf(" ");
// 					}
// 					printf("]");
						   fflush(stdout);
						   pthread_mutex_unlock(&console_owner_mutex);
					   }
					   wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
					   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
						   PrintWmxStatus(wmxStatus);
						   return 2;
					   }
// 				if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) {
					   //
// 				} else {
// 					printf("1No networks found.\n");
// 					break;
// 				}

					   if (time_out > SCAN_TIMEOUT_IN_10SEC_ITREATIONS) {
						   if (g_noNetworksFound == 1) {
							   printf("\n No networks found.\n");
						   } else {
							   printf("\n Scan Operation timeout.\n");
						// As Scan operation timed out
							   ret = 1;
						   }
						   break;
					   }
				   } else {
					   break;
				   }
			   } while (1);

		   } else if (scan_mode == CMD_SCAN_ARG_WIDE) {

			   wmxStatus =SubscribeNetworkSearchWideScanEx(pDeviceID,
					   &IndNetworkSearchWideScanCBEx);
			   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				   PrintWmxStatus(wmxStatus);
				   return 2;
			   }

		// Display the warning message:
			   printf("WARNING: Wide scan may take upto 2 minutes... \n");
			   wmxStatus = CmdNetworkSearchWideScan(pDeviceID);
			   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				   PrintWmxStatus(wmxStatus);
			/*
				   If the Device is already scanning, it won't allow one more AppSrv will reject it
				   with the Operation Falied wrror
			*/
				   if ((DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) && (wmxStatus == WIMAX_API_RET_FAILED)) {
					   printf("WARNING: Scanning is in progress\nPlease wait for the current scan to complete.\n ");

				   }
				   return 1;
			   }

			   if (wmxcu_sem_timeout(&semConnectionUtility,120*1000) == 1 )
				   printf("No networks found.\n");
		   }
		   wmxStatus = UnsubscribeRfTaken(pDeviceID);
		   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			   PrintWmxStatus(wmxStatus);
			   return 2;
		   }
		   wmxStatus = UnsubscribeNetworkSearchEx(pDeviceID);
		   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			   PrintWmxStatus(wmxStatus);
			   return 2;
		   }
		   wmxStatus = UnsubscribeNetworkSearchWideScanEx(pDeviceID);
		   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			   PrintWmxStatus(wmxStatus);
			   return 2;
		   }
		   return ret;
}



/*
Function:
GetNetworkList(WIMAX_API_DEVICE_ID_P pDeviceID)

Purpose:
This API casuses the device to perform a scan operation and returns a list of  detected NSPs.
This is a blocking API. It returns to the caller after a single  full scan cycle is completed.

Parameters:
WIMAX_API_DEVICE_ID_P pDeviceID - device info like device index, permission etc
*/
int GetNList(WIMAX_API_DEVICE_ID_P pDeviceID, CMD_ARGS scan_mode)
{
    int ret = 0;
    WIMAX_API_RET wmxStatus;
	int time_out = 0;
	WIMAX_API_CONNECTION_MODE connectMode;
    	WIMAX_API_DEVICE_STATUS DeviceStatus;
    	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;
    	WIMAX_API_NSP_INFO_P pNspInfo;

    	UINT32 numOfNSPs = 20;
    	int i = 0;

	// initialize the variable as No Networks found
	g_noNetworksFound = 1;
	g_searchProgress = 0;
	// get the device status
    	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
    	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        	PrintWmxStatus(wmxStatus);
	return 2;
    	}

	switch(DeviceStatus) {
	case WIMAX_API_DEVICE_STATUS_UnInitialized:  /**<  Device is uninitialized */
	  printf("ERROR: Device not Initialized\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW:   /**<  Device RF Off(both H/W and S/W) */
	printf
	    ("WARNING: HW and SW Radios are OFF.\nPlease turn ON the HW and SW Radios to perform a scan.\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_RF_OFF_HW:      /**<  Device RF Off(via H/W switch) */
	printf
	    ("WARNING: HW Radio is OFF.\nPlease turn ON the HW Radio to perform a scan.\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_RF_OFF_SW:      /**<  Device RF Off(via S/W switch) */
	printf
	    ("WARNING: SW Radio is OFF.\nPlease turn ON the SW Radio to perform a scan.\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_Ready:          /**<  Device is ready */
	case WIMAX_API_DEVICE_STATUS_Scanning:       /**<  Device is scanning */
	  break;
	case WIMAX_API_DEVICE_STATUS_Connecting:     /**<  Connection in progress */
	  printf("WARNING: Connection is in progress\n");
	return 2;
	case WIMAX_API_DEVICE_STATUS_Data_Connected:	/**<  Layer 2 connected */
	printf
	    ("WARNING: Connection already established!\nPlease disconnect, before attempting to scan.\n");
	return 2;
	default:
	  printf("ERROR: Device status Unknown.\n");
	return 2;
	}


	wmxStatus =
	SubscribeRfTaken(pDeviceID,&IndRFTakenCB);
    	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
      		PrintWmxStatus(wmxStatus);
		return 2;
    	}
 	wmxStatus = GetConnectionMode(pDeviceID,&connectMode);
    	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	   PrintWmxStatus(wmxStatus);
	return 2;
	}

	if (connectMode == WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT
		&& DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) {
	printf
	    ("WARNING: Scanning is in progress\nPlease wait for the current scan to complete.\n");
	return 2;
	}

    	if (scan_mode == CMD_SCAN_ARG_PREFERRED) {
		wmxStatus = SubscribeNetworkSearch(pDeviceID,&IndNetworkSearchCB );
			if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				PrintWmxStatus(wmxStatus);
			return 2;
			}
		/* In Manual mode always scan do not read the cache as we don't know when cache was updated */
		if (connectMode != WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT) {
        		pNspInfo = (WIMAX_API_NSP_INFO_P )malloc(MAX_LEN * sizeof(WIMAX_API_NSP_INFO));
        		memset(pNspInfo, 0, sizeof(WIMAX_API_NSP_INFO) * MAX_LEN);
        		wmxStatus = GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
        		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
            			PrintWmxStatus(wmxStatus);
				/*
				 If the Device is already scanning, it won't allow one more AppSrv will reject it
				 with the Operation Falied error
				*/
        			free(pNspInfo);
		return 1;
        		}

        		if(numOfNSPs != 0) {
            			for (i = 0; i < numOfNSPs; i++)
            			{
						   printf("\nNetwork found.\n");
                			PrintNSPInfo(&pNspInfo[i]);
                			if  (IsNetworkActivated(pDeviceID,&pNspInfo[i]) )
                    				printf("\tActivated\n");
                			else
                    				printf("\tNot Activated\n");
            			}
		return 0;
        		}
  		}

		wmxStatus = CmdNetworkSearch(pDeviceID);

		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			PrintWmxStatus(wmxStatus);
			if ((DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) && (wmxStatus == WIMAX_API_RET_FAILED)) {
					printf("WARNING: Scanning is in progress\nPlease wait for the current scan to complete.\n");
			}
			return 1;
		}

			   printf("Scanning %2d%% Done ", g_searchProgress);
			   fflush(stdout);
			   do {
				   if (wmxcu_sem_timeout(&semConnectionUtility,5*1000) == 1 )
				   {
					   time_out++;
					   if (pthread_mutex_trylock(&console_owner_mutex) == 0) {
						   printf("\r");
						   printf("Scanning %2d%% Done ", g_searchProgress);
					// printf("Scanning %2d% Done [", g_searchProgress);

						   for(i = 0; i<=time_out; i++)
						   {
							   printf("=");
						   }
						   printf("-");
// 					for(i = 0; i<=SCAN_TIMEOUT_IN_10SEC_ITREATIONS - time_out; i++)
// 					{
// 						printf(" ");
// 					}
// 					printf("]");
						   fflush(stdout);
						   pthread_mutex_unlock(&console_owner_mutex);
					   }
					   wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
					   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
						   PrintWmxStatus(wmxStatus);
						   return 2;
					   }
// 				if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) {
					   //
// 				} else {
// 					printf("1No networks found.\n");
// 					break;
// 				}

					   if (time_out > SCAN_TIMEOUT_IN_10SEC_ITREATIONS) {
						   if (g_noNetworksFound == 1) {
							   printf("\n No networks found.\n");
						   } else {
							   printf("\n Scan Operation timeout.\n");
						// As Scan operation timed out
							   ret = 1;
						   }
						   break;
					   }
				   } else {
					   break;
				   }
			   } while (1);

    } else if (scan_mode == CMD_SCAN_ARG_WIDE) {
			   // Get User Connect Mode
			   int userConnectMode;
			   wmxStatus = GetConnectionMode(pDeviceID,&userConnectMode);
			   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				   PrintWmxStatus(wmxStatus);
				   return 1;
			   }

			   if ((connectMode == WIMAX_API_CONNECTION_SEMI_MANUAL_SCAN_AUTO_CONNECT) ||
				(connectMode == WIMAX_API_CONNECTION_AUTO_SCAN_AUTO_CONNECT) ||
				(connectMode == WIMAX_API_CONNECTION_SEMI_MANUAL_SCAN_MANUAL_CONNECT)) {
				   if (connectMode == WIMAX_API_CONNECTION_SEMI_MANUAL_SCAN_MANUAL_CONNECT) {
					   printf("Changing Scan mode to Manual Scan mode \n");
				   } else {
					   	printf("Changing Scan mode to manual \n");
				   		printf("Changing Connect mode to manual \n");
				   }
				   userConnectMode = WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT;
				   wmxStatus = SetConnectionMode(pDeviceID,userConnectMode);
				   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
					   PrintWmxStatus(wmxStatus);
					   return 1;
				   }
				}


			   wmxStatus =SubscribeNetworkSearchWideScan(pDeviceID,
					   &IndNetworkSearchWideScanCB);
			   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				   PrintWmxStatus(wmxStatus);
				   return 2;
			   }


		// Display the warning message:
		printf("WARNING: Wide scan may take upto 2 minutes... \n");
		wmxStatus = CmdNetworkSearchWideScan(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			PrintWmxStatus(wmxStatus);
			/*
			 If the Device is already scanning, it won't allow one more AppSrv will reject it
			 with the Operation Falied wrror
			*/
			if ((DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) && (wmxStatus == WIMAX_API_RET_FAILED)) {
				printf("WARNING: Scanning is in progress\nPlease wait for the current scan to complete.\n ");

			}
            		return 1;
        	}

    		if (wmxcu_sem_timeout(&semConnectionUtility,120*1000) == 1 )
			printf("No networks found.\n");
    	}

	wmxStatus = UnsubscribeRfTaken(pDeviceID);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 2;
	}

	wmxStatus = UnsubscribeNetworkSearch(pDeviceID);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 2;
	}
        wmxStatus = UnsubscribeNetworkSearchWideScan(pDeviceID);
        if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        	PrintWmxStatus(wmxStatus);
	return 2;
    }
    return ret;
        }


void IndDeviceUpdateCB(WIMAX_API_DEVICE_ID_P pDeviceId, WIMAX_API_DEVICE_STATUS systemStatus, WIMAX_API_STATUS_REASON statusReason, WIMAX_API_CONNECTION_PROGRESS_INFO connectionProgressInfo)
{

		g_devState = systemStatus;

		switch(systemStatus)
		{
			case WIMAX_API_DEVICE_STATUS_Ready:
			case WIMAX_API_DEVICE_STATUS_Scanning:
		 	case WIMAX_API_DEVICE_STATUS_Connecting:
			case WIMAX_API_DEVICE_STATUS_Data_Connected:
				sem_post(&semRfState);
				break;

			case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW:
				printf("SW and HW Radion is turned off \n");
				sem_post(&semConnectCompleted);
				sem_post(&semConnectionUtility);
				sem_post(&semRfState);
			break;
			case WIMAX_API_DEVICE_STATUS_RF_OFF_HW:
				printf("HW Radio is turned off\n");
				sem_post(&semConnectCompleted);
				sem_post(&semConnectionUtility);
			break;
			case WIMAX_API_DEVICE_STATUS_RF_OFF_SW:
				printf("SW Radio is turned off \n");
				sem_post(&semConnectCompleted);
				sem_post(&semConnectionUtility);
				sem_post(&semRfState);
			break;
			default:
        break;
    }
}

void IndNetworkSearchWideScanCBEx (WIMAX_API_DEVICE_ID_P  pDeviceID,
        					     WIMAX_API_NSP_INFO_EX_P pNspList,
					             UINT32 listSize)
{
    int i;
    // Scan complete arrived.  Display the netwokr list.
    if(pNspList == NULL || listSize < 1)
    {
        printf("No networks found.\n");
    }
    else
    {
        for (i = 0; i < listSize; i++)
        {
            PrintNSPInfoEx(&pNspList[i]);
            if  (IsNetworkActivatedEx(pDeviceID,&pNspList[i]) )
                printf("\tActivated.\n");
            else
                printf("\tNot Activated.\n");
        }
	// Unset the preferred NSP
	preferred_NSP_ID = 0;
	SetCurrentPreferredProfiles(pDeviceID, &preferred_NSP_ID, 0);
    }
    // release the semaphore
	sem_post(&semConnectionUtility);
}



void IndNetworkSearchWideScanCB (WIMAX_API_DEVICE_ID_P  pDeviceID,
        					     WIMAX_API_NSP_INFO_P  pNspList,
					             UINT32 listSize)
{
    int i;
    // Scan complete arrived.  Display the netwokr list.
    if(pNspList == NULL || listSize < 1)
    {
        printf("No networks found.\n");
    }
    else
    {
        for (i = 0; i < listSize; i++)
        {
            PrintNSPInfo(&pNspList[i]);
            if  (IsNetworkActivated(pDeviceID,&pNspList[i]) )
                printf("\tActivated.\n");
            else
                printf("\tNot Activated.\n");
        }
	// Unset the preferred NSP
	preferred_NSP_ID = 0;
	SetCurrentPreferredProfiles(pDeviceID, &preferred_NSP_ID, 0);
    }
    // release the semaphore
	sem_post(&semConnectionUtility);
}

void IndNetworkSearchCBEx(WIMAX_API_DEVICE_ID_P  pDeviceID,
			  WIMAX_API_NSP_INFO_EX_P pNspList,
     UINT32 listSize,UINT32 searchProgress)
{
	int i;

    // Scan complete arrived.  Display the netwokr list.
	if(pNspList == NULL || listSize < 1)
	{
		g_searchProgress = searchProgress;
	 // printf("No networks found.\n");
	}
	else
	{
		pthread_mutex_lock(&console_owner_mutex);
		if (searchProgress == 100 ) {
			for (i = 0; i < listSize; i++)
			{
				g_noNetworksFound = 0;
				printf("\n");
				printf("Network found.\n");
				PrintNSPInfoEx(&pNspList[i]);
				if  (IsNetworkActivatedEx(pDeviceID,&pNspList[i]) )
					printf("\tActivated.\n");
				else
					printf("\tNot Activated.\n");
			}

		} else {
			g_searchProgress = searchProgress;
		}
		pthread_mutex_unlock(&console_owner_mutex);
	}
	if (searchProgress == 100 ) {
		if (g_noNetworksFound == 1) {
			pthread_mutex_lock(&console_owner_mutex);
			printf("\nNo networks found.\n");
			pthread_mutex_unlock(&console_owner_mutex);
		// release the semaphore
			sem_post(&semConnectionUtility);
		} else {
		// release the semaphore
			pthread_mutex_lock(&console_owner_mutex);
			printf("\nScanning operation completed.\n");
			pthread_mutex_unlock(&console_owner_mutex);
			sem_post(&semConnectionUtility);
		}
	}

}



void IndNetworkSearchCB (WIMAX_API_DEVICE_ID_P  pDeviceID,
					     WIMAX_API_NSP_INFO_P  pNspList,
			 UINT32 listSize, UINT32 searchProgress)
{
    int i;

    // Scan complete arrived.  Display the netwokr list.
    if(pNspList == NULL || listSize < 1)
    {
		g_searchProgress = searchProgress;
	 // printf("No networks found.\n");
    }
    else
    {
		pthread_mutex_lock(&console_owner_mutex);
		if (searchProgress == 100 ) {
        for (i = 0; i < listSize; i++)
        {
				g_noNetworksFound = 0;
				printf("\n");
				printf("Network found.\n");
            PrintNSPInfo(&pNspList[i]);
            if  (IsNetworkActivated(pDeviceID,&pNspList[i]) )
                printf("\tActivated.\n");
            else
                printf("\tNot Activated.\n");
        }

		} else {
			g_searchProgress = searchProgress;
    }
		pthread_mutex_unlock(&console_owner_mutex);
	}
	if (searchProgress == 100 ) {
		if (g_noNetworksFound == 1) {
			pthread_mutex_lock(&console_owner_mutex);
			printf("\nNo networks found.\n");
			pthread_mutex_unlock(&console_owner_mutex);
    // release the semaphore
    sem_post(&semConnectionUtility);
		} else {
		// release the semaphore
			pthread_mutex_lock(&console_owner_mutex);
			printf("\nScanning operation completed.\n");
			pthread_mutex_unlock(&console_owner_mutex);
			sem_post(&semConnectionUtility);
		}
	}

}

void IndRFTakenCB (WIMAX_API_DEVICE_ID_P  pDeviceID)
{
	// int i;

    	// Radio is taken away by WiFi
	printf("Could not complete Scan, Radio is taken by WiFi\n");
	printf("Please try scanning later \n");
    // release the semaphore
    sem_post(&semConnectionUtility);
}


/*
 * Function:     GetStats
 * Description:  Get statistics data
 * Return:       0 for success or 1 for failure
 */
int GetStats(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_CONNECTION_STAT Statistics;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	if (DeviceStatus != WIMAX_API_DEVICE_STATUS_Data_Connected) {
		// Dispaly a proper message and exit
		switch (DeviceStatus) {
		case WIMAX_API_DEVICE_STATUS_UnInitialized:
			printf("ERROR: Device not Initialized\n");
			break;
		case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW:
			printf("WARNING: HW and SW Radio is turned OFF\n");
			break;
		case WIMAX_API_DEVICE_STATUS_RF_OFF_HW:
			printf("WARNING: HW Radio is turned OFF\n");
			break;
		case WIMAX_API_DEVICE_STATUS_RF_OFF_SW:
			printf("WARNING: SW Radio is turned OFF\n");
			break;
		case WIMAX_API_DEVICE_STATUS_Ready:
		case WIMAX_API_DEVICE_STATUS_Scanning:
		case WIMAX_API_DEVICE_STATUS_Connecting:
			printf("WARNING: Network is not Connected\n");
			break;
		default:
			printf("ERROR: Unknown Device Status\n");
		}
	return 1;
	}

	wmxStatus = GetStatistics(pDeviceID, &Statistics);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 1;
	}

	printf("Statistics:\n");
	printf("\tTotal RX Bytes   : %lld bytes\n", Statistics.totalRxByte);
	printf("\tTotal TX Bytes   : %lld bytes\n", Statistics.totalTxByte);
	printf("\tTotal RX Packets : %lld\n", Statistics.totalRxPackets);
	printf("\tTotal TX Packets : %lld\n", Statistics.totalTxPackets);

    return 0;
}

/*
 * Function:     GetDeviceInfo
 * Description:  Retrive the device info
 * Return:
 */
int GetDeviceInfo(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;

	WIMAX_API_DEVICE_INFO device_info;
	WIMAX_API_NVM_VERSION nvm_ver;
	WIMAX_API_WMF_COMPLIANCE_VERSION wmf_ver;

	GetDeviceInformation(pDeviceID, &device_info);
	GetWMFComplianceVersion(&wmf_ver);
	GetNVMImageVersion(pDeviceID, &nvm_ver);

	PrintDeviceInfo(&device_info, &wmf_ver, &nvm_ver);

	return 0;
}

/*
 * Function:     GetVersionInfo
 * Description:  Display the version information
 * Return:
 */
int GetVersionInfo(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;

	WIMAX_API_DEVICE_INFO device_info;
	WIMAX_API_WMF_COMPLIANCE_VERSION wmf_version;

	wmxStatus = GetDeviceInformation(pDeviceID, &device_info);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	wmxStatus = GetWMFComplianceVersion(&wmf_version);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	PrintVersionInfo(&device_info, &wmf_version);

	return 0;
}

/*
 * Function:     GetUserLinkStatus
 * Description:  Get the link status
 * Return:       0 for success (connected) or 1 for failure
 */
int GetUserLinkStatus(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_CONNECTED_NSP_INFO ConnectedNSP;
	WIMAX_API_LINK_STATUS_INFO LinkStatus;
	WIMAX_API_CONNECTION_TIME conntime;

	wmxStatus = GetConnectedNSP(pDeviceID, &ConnectedNSP);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		printf("Link Status: Network is not connected.\n");
		return 1;
	}

	wmxStatus = GetLinkStatus(pDeviceID, &LinkStatus);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 1;
	}

	wmxStatus = GetConnectionTime(pDeviceID, &conntime);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		conntime = 0;
	}

	PrintUserLinkStatus(&LinkStatus);
	PrintConnectionTime(conntime);

    return 0;
}

int GetUserLinkStatusEx(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_CONNECTED_NSP_INFO_EX ConnectedNSP;
	WIMAX_API_LINK_STATUS_INFO_EX LinkStatus;
	WIMAX_API_CONNECTION_TIME conntime;

	wmxStatus = GetConnectedNSPEx(pDeviceID, &ConnectedNSP);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		printf("Link Status: Network is not connected.\n");
		return 1;
	}

	wmxStatus = GetLinkStatusEx(pDeviceID, &LinkStatus);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
	return 1;
	}

	wmxStatus = GetConnectionTime(pDeviceID, &conntime);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		conntime = 0;
	}

	PrintUserLinkStatusEx(&LinkStatus);
	PrintConnectionTime(conntime);

    return 0;
}

void IndConnectToNetworkCallback(WIMAX_API_DEVICE_ID_P pDeviceId,
                                 WIMAX_API_NETWORK_CONNECTION_RESP networkConnectionResponse)
{
    switch(networkConnectionResponse)
    {
        case WIMAX_API_CONNECTION_SUCCESS:
		// Set Connected NSP is current preferred NSP
		if (preferred_NSP_ID != 0 ) {
			SetCurrentPreferredProfiles(pDeviceId, &preferred_NSP_ID, 1);
		}
            printf("Connection successful\n");
		break;
        case WIMAX_API_CONNECTION_FAILURE:
            printf("Connection failure\n");
		break;
        default:
            printf("Unknown Connection status\n");
    }
    sem_post(&semConnectCompleted);

}




int ConnectWithProfileID(WIMAX_API_DEVICE_ID_P pDeviceID,
			  char *profileId_str)
{
	WIMAX_API_RET wmxStatus;
	// int bSuccess = 0;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;
	WIMAX_API_CONNECTION_MODE connectMode;
	WIMAX_API_NSP_INFO nspInfo;
	WIMAX_API_PROFILE_ID profileId = 0;
    int ret = 0;

	if((profileId_str == NULL)) {
		printf("ERROR: Invalid Parameter - missing Profile ID\n");
		return 1;
	}

	wmxStatus =
	    GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		printf("ERROR: Unable to find Device Status - ");
		PrintWmxStatus(wmxStatus);
	return 1;

	}
	wmxStatus = GetConnectionMode(pDeviceID,&connectMode);
    	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	   PrintWmxStatus(wmxStatus);
	return 1;
	}
	if (connectMode == WIMAX_API_CONNECTION_AUTO_SCAN_AUTO_CONNECT) {
	printf("WARNING: The Profile is setup to Auto Connect and Auto Scan, this command would be deferred\n");
	return 1;
	}

	if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Data_Connected) {
	printf("WARNING: Connection already established!\nPlease disconnect from the current network before attempting to connect.\n");

	return 1;
	}

	if (DeviceStatus != WIMAX_API_DEVICE_STATUS_Ready
	&& DeviceStatus != WIMAX_API_DEVICE_STATUS_Scanning ) {
		printf("ERROR: Device is in unknown status - ");
	PrintDeviceStatus(DeviceStatus);

	return 1;
	}

	profileId = atoi(profileId_str);
	// common api get the profile list in their memory
	// We already checked to make sure that device is in
	// scanning or in ready mode, We can get list if any of these modes
	// TODO : Wait here until currecnt scan to complete
	//if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Ready) {
		if (FindNetwork(pDeviceID, profileId, &nspInfo) == 0) {
			printf("ERROR: Attempt to connect Failed. \n");
	    return 1;
		}
	//}
	preferred_NSP_ID = nspInfo.NSPid;
	// Register to connect complete event
	wmxStatus = SubscribeConnectToNetwork (pDeviceID,IndConnectToNetworkCallback);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	  printf("ERROR: Failed to register callback\n");
	  return 1;
	}

	printf("Connecting to %s Network...\n",nspInfo.NSPName);
	wmxStatus = CmdConnectToNetwork(pDeviceID, nspInfo.NSPName, 0, 0);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	  printf("ERROR: Connection to %s network not successfull\n", nspInfo.NSPName);
	  return 1;
	}

	if (wmxcu_sem_timeout(&semConnectCompleted,30*1000) == 1 ) {
	    printf("Connection Fail: time out\n");
	    return 1;
	  }

	wmxStatus = UnsubscribeConnectToNetwork (pDeviceID);

	// checking the connection
	//wmxStatus =
	//    GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	//if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	//	PrintWmxStatus(wmxStatus);
        //ret = 1;
	//} else {
	//	PrintDeviceStatus(DeviceStatus);
        //ret = 0;
	//}

    return ret;
}

int FindNetwork(WIMAX_API_DEVICE_ID_P pDeviceID, int profileId,
		WIMAX_API_NSP_INFO_P nspInfo)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	UINT32 numProfileList = MAX_PROFILE;
	int i = 0,j =0;
	UINT32 numOfNSPs = MAX_DEVICE;
	WIMAX_API_NSP_INFO_P pNspInfo =
	    (WIMAX_API_NSP_INFO_P )malloc(MAX_LEN *
						sizeof(WIMAX_API_NSP_INFO));
	WIMAX_API_PROFILE_INFO_P profilelist =
	    (WIMAX_API_PROFILE_INFO_P)
			malloc(sizeof(WIMAX_API_PROFILE_INFO)*MAX_PROFILE);
	memset(profilelist, 0,
	       sizeof(WIMAX_API_PROFILE_INFO) * MAX_PROFILE);

	//1. Get the profile list and network list
	wmxStatus =
	    GetSelectProfileList(pDeviceID, profilelist, &numProfileList);
	if (wmxStatus != WIMAX_API_RET_SUCCESS) {
		printf("ERROR: Could not fetch the profile list- ");
		PrintWmxStatus(wmxStatus);
		return 0;
	}

	if (numProfileList == 0) {
        printf("WARNING: Profile list is empty \n");
		return 0;
	}

	for (i = 0; i < numProfileList; i++) {
		// check the match
		if (profileId == profilelist[i].profileID) {
//
			// zero the memory
			memset(pNspInfo, 0,
			       sizeof(WIMAX_API_NSP_INFO) * MAX_LEN);
			wmxStatus =
			    GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
			if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				printf
				    ("ERROR: Could not fetch network list - ");
				PrintWmxStatus(wmxStatus);
				free(pNspInfo);
				free (profilelist);
				return 0;
			}
			if (numOfNSPs == 0) {
				printf
				    ("No available networks.\n");
				free (profilelist);
				free(pNspInfo);
				return 0;
			}
			for (j = 0; j < numOfNSPs; j++) {
				if ((pNspInfo[j].NSPid & 0xffffff) == profileId) {
					// match with nspid, if there copy the nsp name and send it back
					memcpy(nspInfo, &pNspInfo[j],
					       sizeof(WIMAX_API_NSP_INFO));
					free(pNspInfo);
					free (profilelist);
					return 1;
				}
			}
		}
	}
	// return the proper status of this function

	free (profilelist);
	free(pNspInfo);
	// get the profile list and compare with nspid and return the result

	return 0;
}


int ConnectWithNSPInfo(WIMAX_API_DEVICE_ID_P pDeviceID,
			char *str_nspid, int activate)
{
  WIMAX_API_RET wmxStatus;
  char tmp_nspID_str[MAX_NSP_ID_LEN];
  UINT32 numOfNSPs = MAX_DEVICE;
   int time_out = 0;
  int i = 0;
  int bSuccess = 0;
  WIMAX_API_DEVICE_STATUS DeviceStatus;
  WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;
  WIMAX_API_CONNECTION_MODE connectMode;
  WIMAX_API_PROFILE_INFO	CurrentPreferredNSPs;
  //currently the listsize for CurrentPerferredNSPs are 1;
  UINT32 listsize =1;


  pthread_t userinputthread;
  int ret = 0;
  BOOL wait = TRUE;
  char *msg = "Waiting for initial provisioning from server...\nPress 'q' to quit.";
  WIMAX_API_NSP_INFO_P pNspInfo =
    (WIMAX_API_NSP_INFO_P )malloc(MAX_LEN * sizeof(WIMAX_API_NSP_INFO));


  // zero the memory
  memset(pNspInfo, 0, sizeof(WIMAX_API_NSP_INFO) * MAX_LEN);

  do {
    wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
      printf("ERROR: Attempt to connect not successfull - ");
      PrintWmxStatus(wmxStatus);
      free(pNspInfo);
	    return 2;
    }

	  if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Data_Connected) {
	    printf("WARNING: Connection already established!\nPlesae disconnect from the current network before attempting to connect\n");
	    free(pNspInfo);
	    return 1;
	  }

	  if (DeviceStatus != WIMAX_API_DEVICE_STATUS_Ready
	      && DeviceStatus != WIMAX_API_DEVICE_STATUS_Scanning ) {
	    printf("ERROR: Attempt to connect not successfull - ");
	    PrintDeviceStatus(DeviceStatus);
	    free(pNspInfo);
	    return 2;
	  }

	wmxStatus = GetConnectionMode(pDeviceID,&connectMode);
    	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	   PrintWmxStatus(wmxStatus);
	return 2;
	}

	
	wmxStatus =GetCurrentPreferredProfiles(pDeviceID,&CurrentPreferredNSPs,&listsize);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	   PrintWmxStatus(wmxStatus);
	return 2;
	}
	if(CurrentPreferredNSPs.profileID!=0){
		
		printf("Current Preferred Profile is:\n");	;
		printf("\tID  : %d\n",CurrentPreferredNSPs.profileID);
		printf("\tName: %s\n",CurrentPreferredNSPs.profileName);
	}

	if ((DeviceStatus == WIMAX_API_DEVICE_STATUS_Ready) && connectMode == WIMAX_API_CONNECTION_MANUAL_SCAN_MANUAL_CONNECT)
	{
		printf("In Manual Scan and Manual Connect Mode\nTrying to find the networks ...\n");
		wmxStatus = SubscribeNetworkSearch(pDeviceID,&IndNetworkSearchCB );
    		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
      		PrintWmxStatus(wmxStatus);
		return 2;
    		}
		wmxStatus = CmdNetworkSearch(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			PrintWmxStatus(wmxStatus);
			return 1;
		}
		  printf("Scanning %2d%% Done ", g_searchProgress);
			   fflush(stdout);
			   do {
				   if (wmxcu_sem_timeout(&semConnectionUtility,5*1000) == 1 )
				   {
					   time_out++;
					   if (pthread_mutex_trylock(&console_owner_mutex) == 0) {
						   printf("\r");
						   printf("Scanning %2d%% Done ", g_searchProgress);
					// printf("Scanning %2d% Done [", g_searchProgress);
					
						   for(i = 0; i<=time_out; i++)
						   {
							   printf("=");
						   }
						   printf("-");
// 					for(i = 0; i<=SCAN_TIMEOUT_IN_10SEC_ITREATIONS - time_out; i++)
// 					{
// 						printf(" ");
// 					}
// 					printf("]");
						   fflush(stdout);
						   pthread_mutex_unlock(&console_owner_mutex);
					   }
					   wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
					   if (WIMAX_API_RET_SUCCESS != wmxStatus) {
						   PrintWmxStatus(wmxStatus);
						   return 2;
					   }
// 				if (DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning) {
					   // 					
// 				} else {
// 					printf("1No networks found.\n");
// 					break;
// 				}

					   if (time_out > SCAN_TIMEOUT_IN_10SEC_ITREATIONS) {
						   if (g_noNetworksFound == 1) {
							   printf("\n No networks found.\n");
						   } else {
							   printf("\n Scan Operation timeout.\n");
						// As Scan operation timed out
							   ret = 1;
						   }
						   break;
					   }
				   } else {
					   break;
				   }	
			   } while (1);	
		
	    wmxStatus = GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
	    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	      printf("ERROR: Attempt to connect not successfull - ");
	      PrintWmxStatus(wmxStatus);
	      free(pNspInfo);
		return 2;
	    
		}
		wmxStatus = UnsubscribeNetworkSearch(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
		}

	}else if ((DeviceStatus == WIMAX_API_DEVICE_STATUS_Ready) || (DeviceStatus == WIMAX_API_DEVICE_STATUS_Scanning)) {
	    wmxStatus = GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
	    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	      printf("ERROR: Attempt to connect not successfull - ");
	      PrintWmxStatus(wmxStatus);
	      free(pNspInfo);
		return 2;
	    }

	  }
	if (numOfNSPs == 0){
		//numOfNSPs is 0 now - it should be set to MAX
		numOfNSPs=MAX_DEVICE;
		printf("Searching....\n");
		wmxStatus = SubscribeNetworkSearch(pDeviceID,&IndNetworkSearchCB );
    		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
      		PrintWmxStatus(wmxStatus);
		return 2;
    		}
		wmxStatus = CmdNetworkSearch(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			PrintWmxStatus(wmxStatus);
			return 1;
		}

		if (wmxcu_sem_timeout(&semConnectionUtility,30*1000) == 1 ){

			printf("ERROR: Attempt to connect not successfull\n");
			free(pNspInfo);
			return 2;
		}
		else{
			wmxStatus = GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
			if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			printf("ERROR: Attempt to connect not successfull - ");
			PrintWmxStatus(wmxStatus);
			free(pNspInfo);
				return 2;
			}
		}
		wmxStatus = UnsubscribeNetworkSearch(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
		}

	}
	    if (numOfNSPs == 0) {
	      printf("Attempt to connect not successfull - No available networks\n");
	      free(pNspInfo);
	      return 1;
	    }
	    else {
	      wait = FALSE;
	  }

		// We should not be polling to get an update on the device state but rely on callback..
		// for now we will sleep in between to give the device some time to do work...
		sleep(1);
	} while (wait == TRUE);

	for (i = 0; i < numOfNSPs; i++) {
	  sprintf(tmp_nspID_str,"%d",pNspInfo[i].NSPid);
	  if (!strcmp(tmp_nspID_str,str_nspid)) {
		if ( activate ) {
		  if ( sem_init(&semAPDOactivation,0,0) == -1 )
		    {
			//Semaphore could not be initialized.
		      printf("ERROR: Activation Failed - Internal failure\n");
		      free(pNspInfo);
			return 2;
		    }
		  printf("WARNING: Starting the Activation Process...\n");
		  wmxStatus = RegisterAPDOCallback(pDeviceID);
		  if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		    printf("ERROR: Activation Failed - ");
		    PrintWmxStatus(wmxStatus);
		    free(pNspInfo);
			return 2;
		  }
		  wmxStatus = RegisterPUMACallback(pDeviceID);
		  if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		    printf("ERROR: Activation Failed - ");
		    PrintWmxStatus(wmxStatus);
		    free(pNspInfo);
			return 2;
		  }
		  // copy to global variable to launch again
		  strcpy (g_sznspName,pNspInfo[i].NSPName);
		}

	      preferred_NSP_ID = pNspInfo[i].NSPid;
              // Register to connect complete event
              wmxStatus = SubscribeConnectToNetwork (pDeviceID,IndConnectToNetworkCallback);
              if (WIMAX_API_RET_SUCCESS != wmxStatus) {
                  printf("ERROR: Failed to register callback\n");
                  free(pNspInfo);
                  return 1;
              }

	    printf("Connecting to %s Network...\n",pNspInfo[i].NSPName);
	    wmxStatus = CmdConnectToNetwork(pDeviceID, pNspInfo[i].NSPName, 0, 0);
	    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
	      printf("ERROR: Connection to %s network not successfull\n",pNspInfo[i].NSPName);
	      free(pNspInfo);
		return 1;
	    }
            if (wmxcu_sem_timeout(&semConnectCompleted,30*1000) == 1 )
            {
                printf("Connection Fail: time out\n");
                free(pNspInfo);
                return 1;
            }
	     wmxStatus = UnsubscribeConnectToNetwork (pDeviceID);

	    if  ( activate )
	      {
		// spin the thread
		ret = pthread_create( &userinputthread, NULL, userinfo, (void*) msg);
		if (wmxcu_sem_timeout(&semAPDOactivation,90*1000) == 1 )
		  printf("ERROR: Activation Server Not Responding (Time Out)\n");

		wmxStatus = UnRegisterAPDOCallback(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		  PrintWmxStatus(wmxStatus);
		  free(pNspInfo);
		    return 2;
		}
		wmxStatus = UnregisterPUMACallback(pDeviceID);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		  PrintWmxStatus(wmxStatus);
		  free(pNspInfo);
		    return 2;
		}
		pthread_cancel(userinputthread);
	      }
	    // checking the connection
	    //wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	    //if (WIMAX_API_RET_SUCCESS != wmxStatus)
	    //  {
	    //PrintWmxStatus(wmxStatus);
	    //  }
	    //else
	    //  {
	    //	PrintDeviceStatus(DeviceStatus);
	    //  }

	    bSuccess = 1;
	  }
	  if ( bSuccess == 1)
	    break;
	}

	if (!bSuccess) {
	  printf("WARNING: Network ID did not match, try issuing a wide scan.\n");
        free(pNspInfo);
        return 1;
    }

    free(pNspInfo);
    return 0;
}

void *userinfo(void *ptr)
{
	int ch = 0;
     	printf("%s \n", (char *)ptr);
	while(ch != 'q' && ch != 'Q')
		ch = getc(stdin);

	sem_post(&semAPDOactivation);
	return (void *) 0;
}

/*
 * Function:     Activate
 * Description:  Connect to un-activated network
 */
int Activate(WIMAX_API_DEVICE_ID_P pDeviceID, char *str_nspid)
{
	if ( str_nspid == NULL  ){
		printf("ERROR: Network ID is not valid\n");
	return 1;
	}

    return ConnectWithNSPInfo(pDeviceID, str_nspid, 1);
}

/*
 * Function:     Deactivate
 * Description:  Deactivate already activated network
 */
int Deactivate(WIMAX_API_DEVICE_ID_P pDeviceID, char *str_nspid)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	int nspid = atoi(str_nspid);
	wmxStatus = CmdDeprovisionProfile(pDeviceID,nspid);
	if  (wmxStatus != WIMAX_API_RET_SUCCESS )
	{
		printf("ERROR: Profile Deactivate unsuccessfull\n");
		PrintWmxStatus(wmxStatus);
        return 1;
	}

    printf("Profile is Deactivated.\n");
    return 0;
}

/*
 * Function:     Disconnect
 * Description:  Disconnect from the currently connected network
 */
int Disconnect(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
    WIMAX_API_DEVICE_STATUS DeviceStatus;
    WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;
    WIMAX_API_CONNECTION_MODE connectMode;

    wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        PrintWmxStatus(wmxStatus);
	return 2;
	}

    if (DeviceStatus != WIMAX_API_DEVICE_STATUS_Data_Connected) {
        printf("WARNING: Network already disconnected.\n");
	return 1;
        }

    // Get current connection mode
    wmxStatus = GetConnectionMode(pDeviceID,&connectMode);
    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        PrintWmxStatus(wmxStatus);
	return 2;
	}

    if (connectMode == WIMAX_API_CONNECTION_SEMI_MANUAL_SCAN_AUTO_CONNECT
        || connectMode == WIMAX_API_CONNECTION_AUTO_SCAN_AUTO_CONNECT)
    {
        ConvertCharToConnectionMode(CMD_STR_MODE_ARGS_CONNECT_OPT_MANUAL, NULL, &connectMode);
        wmxStatus = SetConnectionMode(pDeviceID,connectMode);
        if (WIMAX_API_RET_SUCCESS != wmxStatus) {
            PrintWmxStatus(wmxStatus);
            printf("ERROR: Changing connect mode to manual unsuccessfull\n");
            return 2;
        }
        printf("WARNING: Connect mode is now changed to manual\n");
    }

		wmxStatus = CmdDisconnectFromNetwork(pDeviceID);
		if (wmxStatus != WIMAX_API_RET_SUCCESS) {
			PrintWmxStatus(wmxStatus);
	return 1;
    }

	printf("Network Disconnected.\n");
	return 0;
}

/*
 * Function:     RadioOn
 * Description:  Turn on the Radio
 * Return:       0 for success,
                 1 for failure, or
                 2 for non-command related error
 */
int RadioOn(WIMAX_API_DEVICE_ID_P pDeviceID)
{
    	int ret = 0;
	WIMAX_API_RET wmxStatus;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
	}

	if (DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_SW) {
		wmxStatus = CmdControlPowerManagement(pDeviceID, WIMAX_API_RF_ON);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			PrintWmxStatus(wmxStatus);
            ret = 1;
		} else {
			// Wait 5 secs to get a confirmation of the updated(desired) device state before declaring success
			if ( !wmxcu_sem_timeout(&semRfState,5*1000)  ) {
				if ( (g_devState == WIMAX_API_DEVICE_STATUS_Ready) ||
				  (g_devState == WIMAX_API_DEVICE_STATUS_Scanning) ||
				  (g_devState ==  WIMAX_API_DEVICE_STATUS_Connecting) ||
                     		  (g_devState ==  WIMAX_API_DEVICE_STATUS_Data_Connected) ) {
					printf("SW Radio is turned ON.\n");
                    			ret = 0;
				}
			}
			else {
        			printf("ERROR: Failed to turn SW Radio ON.\n");
                    		ret = 1;
                	}
            }
	} else if ( DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW ||
		        DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_HW ) {
        	printf("HW Radio is OFF.\nDisable HW Kill to turn ON the SW Radio.\n");
        	ret = 1;
    	} else if ( DeviceStatus == WIMAX_API_DEVICE_STATUS_UnInitialized ) {
        	printf("ERROR: Turning the SW Radio ON unsuccessfull - Device is UnInitialized.\n");
        	ret = 1;
	} else {
		printf ("HW and SW Radios are ON.\n");
	}
	return ret;
}

/*
 * Function:     RadioOff
 * Description:  Turn off the radio
 * Return:       0 for success,
                 1 for failure, or
                 2 for non-command related error
 */
int RadioOff(WIMAX_API_DEVICE_ID_P pDeviceID)
{
    int ret = 0;
	WIMAX_API_RET wmxStatus;
	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 2;
	}

	if (DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_HW ){
	        printf("HW Radio is OFF.\nDisable HW Kill to turn OFF the SW Radio.\n");
		return 0;
	}
	else if(DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_SW)
	{
		printf("SW Radio is already turned OFF. \n");
		return 0;
	}
	else if(DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW ){
	        printf("HW and SW Radios are already turned OFF.\n");
		return 0;
	}

	if (DeviceStatus != WIMAX_API_DEVICE_STATUS_UnInitialized) {
		wmxStatus = CmdControlPowerManagement(pDeviceID, WIMAX_API_RF_OFF);
		if (WIMAX_API_RET_SUCCESS != wmxStatus) {
			PrintWmxStatus(wmxStatus);
	    	return 1;
		} else {
			// Wait 5 secs to get a confirmation of the updated(desired) device state before declaring success
			if ( !wmxcu_sem_timeout(&semRfState,5*1000)   ) {
				 if (g_devState == WIMAX_API_DEVICE_STATUS_RF_OFF_SW) {
					// printf("SW Radio is turned OFF\n");
                    			ret = 0;
				}
				else {
        				printf("ERROR: Failed to turn SW Radio OFF.\n");
                    			ret = 1;
                		}
            		}
            		else {
                		printf("ERROR: Failed to turn SW Radio OFF.\n");
                		ret = 1;
            		}
		}
	} else {
        	printf("ERROR: Turning the SW Radion OFF unsuccessfull - Device is UnInitialized.\n");
		ret = 2;
	}
    return ret;
}

/*
 * Function:
 * Description:
 * Param:
 * Return:
 */
void GetConnNSP(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_CONNECTED_NSP_INFO ConnectedNSP;
	WIMAX_API_LINK_STATUS_INFO LinkStatus;

	wmxStatus = GetLinkStatus(pDeviceID, &LinkStatus);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return;
	}

	wmxStatus = GetConnectedNSP(pDeviceID, &ConnectedNSP);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return;
	}
	ConnectedNSP.RSSI = LinkStatus.RSSI;
	ConnectedNSP.CINR = LinkStatus.CINR;
	PrintConnectedNSPInfo(&ConnectedNSP);
}

void GetConnNSPEX(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_CONNECTED_NSP_INFO_EX ConnectedNSP;
	WIMAX_API_LINK_STATUS_INFO_EX LinkStatus;

	wmxStatus = GetLinkStatusEx(pDeviceID, &LinkStatus);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return;
	}

	wmxStatus = GetConnectedNSPEx(pDeviceID, &ConnectedNSP);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return;
	}
	ConnectedNSP.RSSI = LinkStatus.RSSI;
	ConnectedNSP.CINR = LinkStatus.CINR;
	ConnectedNSP.linkQuality = LinkStatus.linkQuality;
	PrintUserLinkStatusEx(&ConnectedNSP);
}


void GetConnTime(WIMAX_API_DEVICE_ID_P pDeviceID)
{
    WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
    WIMAX_API_CONNECTION_TIME connectionTime;

    wmxStatus = GetConnectionTime(pDeviceID, &connectionTime);
    if (WIMAX_API_RET_SUCCESS != wmxStatus) {
        PrintWmxStatus(wmxStatus);
        return;
    }
    PrintConnectionTime(connectionTime);
}

WIMAX_API_RET RegisterAPDOCallback(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	return SubscribeProvisioningOperation(pDeviceID,&IndProvisioningOperationCallBack);
}


WIMAX_API_RET UnRegisterAPDOCallback(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	return UnsubscribeProvisioningOperation(pDeviceID);
}


WIMAX_API_RET RegisterPUMACallback(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	return SubscribePackageUpdate(pDeviceID,&IndPackageUpdateCallBack);
}


WIMAX_API_RET UnregisterPUMACallback(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	return  UnsubscribePackageUpdate(pDeviceID);
}


void IndProvisioningOperationCallBack (WIMAX_API_DEVICE_ID_P  pDeviceID,
				      WIMAX_API_PROV_OPERATION provisoningOperation,
					  WIMAX_API_CONTACT_TYPE contactType)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	int cmd =0;
	int flag  = 0;
	WIMAX_API_CONTACT_INFO_P ContactInfo = NULL;
	UINT32 SizeOfContactList =MAX_PROFILE;
	char browserurl[MAX_SIZE_OF_STRING_BUFFER+MAX_SIZE_OF_STRING_BUFFER] = {0};
	switch(provisoningOperation)
	{
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_STARTED:
		printf("Provisioning Update Started...\n");
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_COMPLETED:
		printf("Provisioning Update Completed.\n");
		// set the event to exit the application
		sem_post(&semAPDOactivation);
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_FAILED_NETWORK_DISCONNECT:
		printf("WARNING: Provisioning Update - Network Disconnected. \n");
		// set the event to exit the application
		sem_post(&semAPDOactivation);
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_FAILED:
		printf("WARNING: Provisioning  Update unsuccessfull.\n");
		// set the event to exit the application
		sem_post(&semAPDOactivation);
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_FAILED_INVALID_PROVISIONING:
		printf("WARNING: Provisioning Update - Invalid Provisioning\n");
		// set the event to exit the application
		sem_post(&semAPDOactivation);
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_FAILED_BAD_AUTHENTICATION:
		printf("WARNING: Provisioning Update - Bad Authentication\n");
		// set the event to exit the application
		sem_post(&semAPDOactivation);
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_REQUEST_INITIAL_PROVISIONING:
		//printf("Initial provisioning\n");
		printf("The Network is attempting to update the WiMAX connection settings.\
			   These settings are critical for the proper operation of WiMAX.\n \
			   Update the WiMAX connection settings now [Y/N]:?");
		cmd = getchar();
		if  (cmd == 'y' || cmd == 'Y')
		{
			wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_ACCEPTED);
			if ( wmxStatus != WIMAX_API_RET_SUCCESS )
			{
				PrintWmxStatus(wmxStatus);
				sem_post(&semAPDOactivation);
			}
		}
		else
		{
			wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_DELAY);
			if ( wmxStatus != WIMAX_API_RET_SUCCESS )
			{
				PrintWmxStatus(wmxStatus);
			}
			sem_post(&semAPDOactivation);
		}
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_REQUEST_ONGOING_PROVISIONING:
		printf("Ongoing Provisioning\n");
		/*
		cmd = system("firefox www.intel.com");
		printf("The network is attempting to update the WiMAX connection settings.\
			   These settings are critical for the proper operation of WiMAX.\n	\
			   \r\n\r\nUpdate the WiMAX connection settings now y/n?");
		cmd = getchar();
		if  (cmd == 'y' || cmd == 'Y')
		{
			wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_ACCEPTED);
			if ( wmxStatus != WIMAX_API_RET_SUCCESS )
			{
				PrintWmxStatus(wmxStatus);
			}
		}
		else
		{
			wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_DELAY);
			if ( wmxStatus != WIMAX_API_RET_SUCCESS )
			{
				PrintWmxStatus(wmxStatus);
			}
		}
		*/
		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_TRIGGER_CONTACT:
		ContactInfo = (WIMAX_API_CONTACT_INFO_P)malloc(sizeof (WIMAX_API_CONTACT_INFO)*MAX_PROFILE);
		wmxStatus = GetContactInformation(pDeviceID,g_sznspName,
				ContactInfo,&SizeOfContactList);
		if  (wmxStatus != WIMAX_API_RET_SUCCESS )
		{
			printf("WARNING: Unable to Retrive the Contact Information\n");
		}
		else
		{
			for ( cmd = 0; cmd <SizeOfContactList; cmd++ )
			{
				if  (contactType == ContactInfo[cmd].contactType)
				{
					// TODO:: find the the browser launch idea for all OS ie midinux, Ubunto etc.,
					printf("Launching the URL %s ...\n",ContactInfo[cmd].URI );
					sprintf(browserurl,"firefox %s",ContactInfo[cmd].URI);
					cmd = system(browserurl);
					flag = 1;
					break;
				}
			}
		}
		free (ContactInfo);
		if  ( flag == 0)
			printf("WARNIGN: Unable to to connect to the URL\n");
		sem_post(&semAPDOactivation);

		break;
	case WIMAX_API_PROV_OPERATION_CFG_UPDATE_REQUEST_RESET_PROVISIONING:
		printf("WARNING: Provisioning Update - request to Reset the Provisioning\n");
		break;
	default:
		sem_post(&semAPDOactivation);
		break;
	}
}


void IndPackageUpdateCallBack(WIMAX_API_DEVICE_ID_P  pDeviceID, WIMAX_API_PACK_UPDATE packageUpdate)
{
	char consent;
	WIMAX_API_RET   wmxStatus;
	//WIMAX_API_PACKAGE_INFO_P pPackageINFO;
	WIMAX_API_PACKAGE_INFO packageINFO;
	//char pathName[PATH_MAX]={0};
	//char packageName[NAME_MAX]={0};
	//char execute [PATH_MAX + NAME_MAX]={0};
	switch (packageUpdate)
	{
	case WIMAX_API_PACK_UPDATE_RECEIVED:
		printf("Package Update - Received \n");
		/*printf("Request to download notification received.\n");
		wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_ACCEPTED);
		if ( wmxStatus != WIMAX_API_RET_SUCCESS )
		{
				PrintWmxStatus(wmxStatus);
		}*/
		break;
	case WIMAX_API_PACK_UPDATE_RECEIVED_LOWER_STACK:
		printf("Package Update - Firmware update Received\n");
		break;
	case WIMAX_API_PACK_UPDATE_RECEIVED_FULL_STACK:
		printf("Package Update - Firmware, SDK and driver updates Received.\n");
		break;

	case WIMAX_API_PACK_UPDATE_RECEIVED_OMA_DM_CLIENT:
		printf("Package Update - OMA-DM client update Received.\n");
		break;

	case  WIMAX_API_PACK_UPDATE_STARTED:
		wmxStatus = GetPackageInformation(pDeviceID, &packageINFO);
		if ( wmxStatus != WIMAX_API_RET_SUCCESS )
		{
					PrintWmxStatus(wmxStatus);
		}
		if((strcmp(foOperationType,SW_UPGRADE_TYPE_DOWNLOAD)==0)||(strcmp(foOperationType,SW_UPGRADE_TYPE_UPDATE)==0))
		{
			printf("Request to install %s downloaded package [Y/N]:",packageINFO.fileName);
			scanf("%c",&consent);
			if((consent=='Y')||(consent=='y'))
			{
				strcat(packageINFO.filePath,"/");

#if 0				// TODO :: IMPORTANT - to be removed
				wmxStatus = InstallAPDOUpdate(pDeviceID,packageINFO.filePath,packageINFO.fileName);

				if ( wmxStatus != WIMAX_API_RET_SUCCESS )
				{
					PrintWmxStatus(wmxStatus);
				}
				//printf("%s\n %s",packageINFO.filePath,packageINFO.fileName);

#endif
				sem_post(&semAPDOupdates);
			}
			else if((consent=='N')||(consent=='n'))
			{

				sem_post(&semAPDOupdates);
			}
		}
		else if(strcmp(foOperationType,SW_UPGRADE_TYPE_DOWNLOAD_AND_UPDATE)==0)
		{
			printf("%s downloaded package will be installed ",packageINFO.fileName);
			strcat(packageINFO.filePath,"/");

#if 0
			wmxStatus = InstallAPDOUpdate(pDeviceID,packageINFO.filePath,packageINFO.fileName);
			if ( wmxStatus != WIMAX_API_RET_SUCCESS )
			{
				PrintWmxStatus(wmxStatus);
			}
#endif
			sem_post(&semAPDOupdates);
		}


		break;/**< Request to install package */
	case WIMAX_API_PACK_UPDATE_COMPLETED:
		printf("Package Update - Successfully Installed.\n");
		sem_post(&semAPDOupdates);
		break;

	case WIMAX_API_PACK_UPDATE_FAILED_NETWORK_DISCONNECTED:
		printf("WARNING: Package Update - Failed to Install - Network Disconnected.\n");
		break;
	case WIMAX_API_PACK_UPDATE_FAILED_INVALID_PACKAGE:
		printf("WARNING: Package Update - Failed to Install - Invalid Package.\n");
		sem_post(&semAPDOupdates);
		break;
	case WIMAX_API_PACK_UPDATE_FAILED_BAD_AUTHENTICATION:
		printf("WARNING: Package Update - Failed to Install - Bad Authentication.\n");
		sem_post(&semAPDOupdates);
		break;
	case  WIMAX_API_PACK_UPDATE_FAILED:
		printf("Package Update - Failed to Install.\n");
		break;
		sem_post(&semAPDOupdates);
	}
}


void RestoreProDB(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	wmxStatus = CmdRestoreBackupProvisioningDatabase(pDeviceID);
	if ( wmxStatus != WIMAX_API_RET_SUCCESS)
	{
		PrintWmxStatus(wmxStatus);
	}

}


/*
 * Function:     ServiceProviderUnlock
 * Description:  Unlock the device
 * Return:       0 for success or 1 for failure, 2 for misc failure
 */
int ServiceProviderUnlock(WIMAX_API_DEVICE_ID_P pDeviceID, char *unlockcode)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_LOCK_STATUS LockStatus = WIMAX_API_DEVICE_UNLOCKED;
	char NSPName[MAX_SIZE_OF_NSP_NAME];

    int length = strlen(unlockcode);
    if (length <= 0) {
        printf("Unlock code is empty\n");
        return 1;
    }

	wmxStatus = GetServiceProviderLockStatus(pDeviceID, &LockStatus,  NSPName);
	if ( wmxStatus == WIMAX_API_RET_SUCCESS) {
		if (LockStatus != WIMAX_API_DEVICE_LOCKED) {
			printf("Device is not locked \n");
	    return 1;
		}
	} else {
		PrintWmxStatus(wmxStatus);
        return 2;
	}

	// First check the serviceprovider locked or not
	// wchar_t *wUnlockcode = NULL;
	// wUnlockcode = (wchar_t *)malloc( (length + 1) * sizeof( wchar_t ));
	/*
	if (! wUnlockcode)
	{
		printf("Memory allocation failure. in Serivceproviderunlock function\n");
		return;
	}

	if  ( mbstowcs(wUnlockcode,unlockcode,length+1)== -1 )
	{
		printf("unable to convert sevice unlock code string to wide character\n");
		free(wUnlockcode) ;
		return ;
	} */
	wmxStatus = SetServiceProviderUnLock(pDeviceID,unlockcode);
	if  ( wmxStatus != WIMAX_API_RET_SUCCESS )
	{
		PrintWmxStatus(wmxStatus);
        return 1;
	}
	// free(wUnlockcode);
    return 0;
}

/*
 * Function:     GetProfileList
 * Description:  Get the profile list
 * Return:       0 for success or 1 for failure
 */
int GetProfileList(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	UINT32 numProfileList = MAX_PROFILE;
    int i = 0;

	WIMAX_API_PROFILE_INFO_P  profilelist= (WIMAX_API_PROFILE_INFO_P)
			malloc(sizeof(WIMAX_API_PROFILE_INFO) * MAX_PROFILE);
	memset(profilelist,0,sizeof(WIMAX_API_PROFILE_INFO) * MAX_PROFILE);

	wmxStatus = GetSelectProfileList(pDeviceID, profilelist, &numProfileList);
	if ( wmxStatus != WIMAX_API_RET_SUCCESS )
	{
		PrintWmxStatus(wmxStatus);
		free (profilelist);
	return 1;
	}

    printf("Profile List:\n");
	for ( i = 0; i < numProfileList; i++)
	{
        printf("\tID  : %d\n",profilelist[i].profileID);
        printf("\tName: %s\n",profilelist[i].profileName);
	}

	free (profilelist);
    return 0;
}

/*
 * Function:     installAPDOUpdates
 * Description:  Install available package
 * Return:       0 for success or 1 for failure
 */
int installAPDOupdates(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	char consent = {0};
	char retbuffer[NAME_MAX] = {0};
	WIMAX_API_RET wmxStatus;


	WIMAX_API_DEVICE_STATUS DeviceStatus;
	WIMAX_API_CONNECTION_PROGRESS_INFO ConnectionProgressInfo;

	//Check to see if HW or SW radio is turned off
	wmxStatus = GetDeviceStatus(pDeviceID, &DeviceStatus, &ConnectionProgressInfo);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	if (DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_SW )
	{
		printf("WARNING: SW Radio is turned OFF\n");
		return 1;
	}
	else if (DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW )
	{
		printf("WARNING: HW and SW Radios are turned OFF\n ");
		return 1;
	}
	else if (DeviceStatus == WIMAX_API_DEVICE_STATUS_RF_OFF_HW)
	{
		printf("WARNING: HW Radio is turned OFF\n");
		return 1;
	}
	else
	{

#if 0 			// TODO :: IMPORTANT -- to be removed (no FUMO functionality)
			wmxStatus = APDOupdates(pDeviceID,retbuffer,NAME_MAX);
#endif
			RegisterPUMACallback(pDeviceID);
			if(retbuffer[0]!=0)
			{
				strcpy(foOperationType,retbuffer);
			}

			if(strcmp(foOperationType,SW_UPGRADE_TYPE_DOWNLOAD_AND_UPDATE)==0)
				printf("\nPackages are available for Download and Install [Y/N]:");

			else if(strcmp(foOperationType,SW_UPGRADE_TYPE_DOWNLOAD)==0)
				printf("\nPackages are available for Download [Y/N]:");
			else if(strcmp(foOperationType,SW_UPGRADE_TYPE_UPDATE)==0)
				printf("\nPackages are available to Install [Y/N]:");
			else {
				printf("No APDO updates are available at this time.\n");
	    return 1;
			}

			scanf("%c",&consent);
			if((consent=='Y')||(consent=='y'))
			{
					if (sem_init(&semAPDOupdates,0, 0) == -1){
					printf("ERROR: Internal failure\n");
		return 1;
				}

				wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_ACCEPTED);
				if ( wmxStatus != WIMAX_API_RET_SUCCESS )
				{
						PrintWmxStatus(wmxStatus);
				}
				sem_wait(&semAPDOupdates);

			}
			if((consent=='N')||(consent=='n'))
			{
				wmxStatus = SetPackageUpdateState(pDeviceID,WIMAX_API_PACKAGE_UPDATE_DENIED);
				if ( wmxStatus != WIMAX_API_RET_SUCCESS )
				{
						PrintWmxStatus(wmxStatus);
				}
			}

			wmxStatus = UnregisterPUMACallback(pDeviceID);
			if (WIMAX_API_RET_SUCCESS != wmxStatus) {
				PrintWmxStatus(wmxStatus);
	}
			}

    return 0;
}

void checkforAPDOupdates(WIMAX_API_DEVICE_ID_P pDeviceID)
{
 	char retbuffer[NAME_MAX];

	WIMAX_API_RET wmxStatus;
#if 0
	wmxStatus = APDOupdates(pDeviceID,retbuffer,NAME_MAX);
#endif
	if(wmxStatus==WIMAX_API_RET_SUCCESS)
	{
		if(retbuffer[0]!=0)
		printf("\nAPDO Updates are Available. Please run \"wimaxcu update\"\n\n");
	}


}

/*
 * Function:     GetProvStatus
 * Description:  Retrive the provisioning status
 * Return:       0 for success,
                 1 for general command failure, or
                 2 for non-command related failure
 */
int GetProvStatus(WIMAX_API_DEVICE_ID_P pDeviceID, char *str_nspid)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_NSP_INFO_P pNspInfo = NULL;
	UINT32 numOfNSPs = MAX_DEVICE;
	char tmp_nspID_str[MAX_NSP_ID_LEN];
	BOOL found_nsp = FALSE;
	BOOL provStatus = FALSE;
	int i;

	pNspInfo = (WIMAX_API_NSP_INFO_P )malloc(MAX_LEN * sizeof(WIMAX_API_NSP_INFO));
	if (pNspInfo == NULL) {
		printf("ERROR: Internal failure\n");
	return 2;
	}

	// find the nsp name from the given nsp id
	wmxStatus = GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		printf("ERROR: Retriving the Network List was unsuccessfull");
		PrintWmxStatus(wmxStatus);
		free(pNspInfo);
	return 2;
	}

	if (numOfNSPs == 0) {
		printf("WARNING: Cannot find any available network.\nPlease run \"wimaxcu scan\" to update the Network List\n");
		free(pNspInfo);
	return 2;
	}

	for (i = 0; i < numOfNSPs; i++) {
		sprintf(tmp_nspID_str,"%d",pNspInfo[i].NSPid);
		if (strcmp(tmp_nspID_str,str_nspid) == 0) {
			found_nsp = TRUE;
			break;
		}
	}

	if (found_nsp == FALSE) {
		printf("WARNING: Network ID (%s) is not in the current known list.\nVerify the Network ID or run \"wimaxcu scan\" to refresh the network list.\n", str_nspid);
		free(pNspInfo);
	return 2;
	}

	wmxStatus = GetProvisioningStatus(pDeviceID, pNspInfo[i].NSPName, &provStatus);
	if  (wmxStatus != WIMAX_API_RET_SUCCESS ) {
		printf("ERROR: Retriving Provisioning status was unsuccessfull\n");
        free (pNspInfo);
        return 1;
	} else {
		printf("Provision Status: %s(%s) is ", pNspInfo[i].NSPName, str_nspid);
		if(provStatus == TRUE)
			printf("Provisioned.\n");
		else
			printf("Not Provisioned.\n");
	}
	free (pNspInfo);
    return 0;
}


/*
 * Function:     GetSPLockStatus
 * Description:  Get the service provider's device lock status
 * Return:       0 for success or 1 for failure
 */
int GetSPLockStatus(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_LOCK_STATUS LockStatus = WIMAX_API_DEVICE_UNLOCKED;
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	char NSPName[MAX_SIZE_OF_NSP_NAME];

	// Get the NSP Name from user
	wmxStatus = GetServiceProviderLockStatus(pDeviceID, &LockStatus,  NSPName);
	if ( wmxStatus == WIMAX_API_RET_SUCCESS) {
		if (LockStatus == WIMAX_API_DEVICE_LOCKED) {
			printf("Lock Status: Device is locked for %s Network\n", NSPName);
		} else {
			printf("Lock Status: Device is unlocked.\n");
		}
	} else {
		PrintWmxStatus(wmxStatus);
        return 1;
    }
    return 0;
}


/*
 * Function:     GetContactInfo
 * Description:  Get the contact info of given NSP
 * Return:       0 for success or 1 for failure
 */
int GetContactInfo(WIMAX_API_DEVICE_ID_P pDeviceID, char *str_nspid)
{
	WIMAX_API_RET wmxStatus = WIMAX_API_RET_SUCCESS;
	WIMAX_API_CONTACT_INFO* pContactInfo = NULL;
	WIMAX_API_NSP_INFO_P pNspInfo = NULL;
	UINT32 SizeOfContactList = MAX_PROFILE;
	UINT32 numOfNSPs = MAX_DEVICE;
	char tmp_nspID_str[MAX_NSP_ID_LEN];
	BOOL found_nsp = FALSE;
	int i, cmd;
    int ret = 0;

	pNspInfo = (WIMAX_API_NSP_INFO_P )malloc(MAX_LEN * sizeof(WIMAX_API_NSP_INFO));
	if (pNspInfo == NULL) {
		printf("ERROR: Internal failure.\n");
	return 1;
	}

	// find the nsp name from the given nsp id
	wmxStatus = GetNetworkList(pDeviceID, pNspInfo, &numOfNSPs);
	if (WIMAX_API_RET_SUCCESS != wmxStatus) {
		printf("ERROR: Retriving the Network list was unsuccessfull");
		PrintWmxStatus(wmxStatus);
	        free(pNspInfo);
	return 1;
	}

	if (numOfNSPs == 0) {
		printf("WARNING: Cannot find any available network.\nPlease run \"wimaxcu scan\" to update the Network List\n");
		free(pNspInfo);
	return 1;
	}

	for (i = 0; i < numOfNSPs; i++) {
		sprintf(tmp_nspID_str,"%d",pNspInfo[i].NSPid);
	  	if (strcmp(tmp_nspID_str,str_nspid) == 0) {
			found_nsp = TRUE;
			break;
		}
	}

	if (found_nsp == FALSE) {
		printf("WARNING: Cannot find the Network ID(%s) in the current known Network list.\nVerify the Network ID or Please run \"wimaxcu scan\" to update the Newtork List.\n", str_nspid);
		free(pNspInfo);
	return 1;
	}

	pContactInfo = (WIMAX_API_CONTACT_INFO_P)malloc(sizeof (WIMAX_API_CONTACT_INFO)*MAX_PROFILE);
	if (pContactInfo == NULL) {
		printf("ERROR: INternal failure\n");
		free(pNspInfo);
	return 1;
	}

	wmxStatus = GetContactInformation(pDeviceID, pNspInfo[i].NSPName, pContactInfo,&SizeOfContactList);
	if  (wmxStatus != WIMAX_API_RET_SUCCESS ) {
		printf("ERROR: Retriving the Contact Information was unsuccessfull\n");
        ret = 1;
	} else {
		printf("%s Contact Information:\n", pNspInfo[i].NSPName);
		if (SizeOfContactList > 0) {
			for ( cmd = 0; cmd <SizeOfContactList; cmd++ ) {
				printf("\tTitle: %s\n", pContactInfo[cmd].textForURI);
				printf("\tURL  : %s\n",pContactInfo[cmd].URI );
			}
            ret = 0;
	} else {
			printf("Contact Information Un-Available.\n");
            ret = 1;
		}
	}

	free (pNspInfo);
	free (pContactInfo);

    return ret;
}

void GetODMInfo(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	int i;
	WIMAX_API_RET wmxStatus;
	WIMAX_API_BINARY_BLOB bin_blob;
	UINT32 bin_blob_size;
	bin_blob_size = sizeof(bin_blob);
	//BinaryBlob = malloc(sizeof(BinaryBlob));
	wmxStatus = GetODMInformation(pDeviceID, bin_blob ,&bin_blob_size);
	if(wmxStatus != WIMAX_API_RET_SUCCESS)
	{
		printf("ERROR: Failed to get ODM version\n");
		PrintWmxStatus(wmxStatus);
		return 1;
	}
	printf("ODM Information\n");
	for(i = 0; i < bin_blob_size; i++) {
		printf("%c",bin_blob[i]);
	}
	printf("\n");
	return 0;
}

void GetNVMInfo(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_NVM_VERSION NVMImageVersion;
	WIMAX_API_RET wmxStatus;
	wmxStatus = GetNVMImageVersion(pDeviceID,&NVMImageVersion);

	if(wmxStatus != WIMAX_API_RET_SUCCESS)
	{
		printf("ERROR: Failed to get NVM image version\n");
		PrintWmxStatus(wmxStatus);
		return 1;
	}

	PrintNVMImageVersion(&NVMImageVersion);

	return 0;
}

void GetIPInterface(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_INTERFACE_INFO InterfaceInfo;
	wmxStatus = GetIPInterfaceIndex(pDeviceID,&InterfaceInfo );
	if(wmxStatus==WIMAX_API_RET_SUCCESS)
	{
		//printf("%s",InterfaceInfo );
	}
}

void SetFastReconnect(WIMAX_API_DEVICE_ID_P pDeviceID,BOOL isEnabled)
{
	WIMAX_API_RET wmxStatus;


	wmxStatus = SetFastReconnectCapabilityStatus(pDeviceID, isEnabled);
	if(wmxStatus==WIMAX_API_RET_SUCCESS)
	{
		if (isEnabled==0)
		printf("Fast Reconnect Disabled\n");
		else
		printf("Fase Reconnect Enabled\n");

	}
	else
	{
		printf("Failed to set Fast Reconnect settings\n");
	}
}

void GetFastReconnect(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	 BOOL isEnabled;

	wmxStatus = GetFastReconnectCapabilityStatus(pDeviceID,&isEnabled);

	if(wmxStatus==WIMAX_API_RET_SUCCESS)
	{
		if (isEnabled==0)
		printf("Fast Reconnect Disabled\n");
		else if(isEnabled ==1)
		printf("Fase Reconnect Enabled\n");

	}
}

void SetConnectedAsCurrent(WIMAX_API_DEVICE_ID_P pDeviceID,BOOL isEnable)
{
	WIMAX_API_RET wmxStatus;
	wmxStatus = SetConnectedAsCurrentPreferredCapabilityStatus(pDeviceID,isEnable);
	if(wmxStatus==WIMAX_API_RET_SUCCESS)
	{
		if (isEnable==0)
		printf("Current Connected Network Preferred settings are disabled\n");
		else if(isEnable ==1)
		printf("Current Connected Network Preferred settings are enabled\n");

	}
	else
		printf("Failed to set preferred settings\n");

}
void GetConnectedAsCurrent(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	BOOL isEnable;
	wmxStatus = GetConnectedAsCurrentPreferredCapabilityStatus(pDeviceID, &isEnable);
	if(wmxStatus==WIMAX_API_RET_SUCCESS)
	{
		if (isEnable == FALSE)
		printf("Current Connected Network Preferred settings are disabled\n");
		else
		printf("Current Connected Network Preferred settings are enabled\n");
	}
    else
    {
        printf("Failed to get preferred settings\n");
	}


}

void GetApiExVersion(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	UINT32 WmxApiExVersion;
	WIMAX_API_RET wmxStatus;
	wmxStatus = GetWmxApiExVersion(&WmxApiExVersion);
	if(wmxStatus == WIMAX_API_RET_SUCCESS)
	{
		printf("%d\n",WmxApiExVersion);
	}
}

void SetCoexMode(WIMAX_API_DEVICE_ID_P pDeviceID,WIMAX_API_COEXISTENCE_MODE coexMode)
{


	WIMAX_API_RET wmxStatus;
	// WSS LINUX START - EVP Specific
	// Kalyan: EVP supports only CM mode
	// So The following code under EVP_SUPPORTS_CM_ONLY is for EVP only
	// The macro EVP_SUPPORTS_CM_ONLY is defined in Makefile
#ifdef EVP_SUPPORTS_CM_ONLY
	if (coexMode == MODE_CM) {
#endif
	// WSS LINUX End
	wmxStatus = SetCoexistenceMode(pDeviceID,coexMode);
	// WSS LINUX START - EVP Specific
#ifdef EVP_SUPPORTS_CM_ONLY
	} else {
		printf("Could not change Coex to XOR Mode\n");
		printf("EVP hardware does not support XOR Mode\n");
		return;
	}
#endif
	// WSS LINUX End
	if(wmxStatus == WIMAX_API_RET_SUCCESS)
	{
		switch(coexMode)
		{
			case MODE_XOR:
				printf("Coex changed to XOR Mode\n");
			break;
			case MODE_CM:
				printf("Coex changed to CM Mode\n");
			break;
		}
	}
	else
		printf("Failed to set the Co-Ex Mode\n");
}


void GetCoexMode(WIMAX_API_DEVICE_ID_P pDeviceID)
{
	WIMAX_API_RET wmxStatus;
	WIMAX_API_COEXISTENCE_MODE CoexMode;
	wmxStatus = GetCoexistenceMode(pDeviceID, &CoexMode);
	if(wmxStatus == WIMAX_API_RET_SUCCESS)
	{
		switch(CoexMode)
		{
			case MODE_XOR:
				printf("Coex is set to MODE_XOR\n");
			break;
			case MODE_CM:
				printf("Coex is set to MODE_CM\n");
			break;
		}
	}
}


void Help()
{
    printf("Usage: wimaxcu [OPTION]\n\n");
    printf("Option: Use on of the following options\n");
    printf("\tactivate <network_id>\t\tactivate a specific network\n");
    printf("\tgetipinterface\t\tDisplays the IP of an interface.[Currently not supported]\n");
    printf("\tupdate\t\tUpdates any APDO related packages. [Currently not supported]\n");
    printf("\tconnect profile <profile_id>\t\tconnect with a specific profile\n");
    printf("\tconnect network <network_id>\t\tconnect with a specific network\n");
    printf("\tconnectmode connect [auto|manual] scan [semi|manual]\t\tdisplay or change the connection/scan mode\n");
    printf("\tdconnect\t\tdisconnect from a network\n");
    printf("\tdeactivate <profile_id>\t\tdeactivate a specific profile\n");
    printf("\tinfo [version|device|stats|contact <network_id>]\t\tdisplay the various information\n");
    printf("\tscan [wide|preferred]\t\tdisplay the available network list\n");
    printf("\tplist\t\tdisplay the profile list\n");
    printf("\treset [factory | device [curently not implemented]]\t\tresets to factory or deivce settings\n");	
    printf("\troff\t\tturn off the radio\n");
    printf("\tron\t\tturn on the radio\n");
    printf("\tstatus [system|connect|link|radio|lock]\t\tdisplay the various status information\n");
    printf("\tgetccap\t\tdisplay the current connected preferred network settings\n");
    printf("\tsetccap [enable|disable]\t\tenable/disable the current connected preferred network settings\n");
    printf("\tsetfastreconnect [enable/disable]\t\tenable/disable the fast reconnect mode.\n");
    printf("\tgetfastreconnect\t\tdisplay the current settings for fast reconnectmode.\n");
    printf("\tunlock <unlock_code>\t\tunlocks the device.\n");
    printf("\thelp\t\tdisplays help\n");
}

void print_callstack_to_file(int sig, siginfo_t *info,
				   void *secret) 
{
	void *trace[16];
  	char **messages = (char **)NULL;
  	int i, trace_size = 0;
	//static int flag=0;
  	ucontext_t *uc = (ucontext_t *)secret;
	FILE *fp;	
	BOOL res;
//	 printf("Came here %d\n", __LINE__);
	char command[MAX_STR_LEN + MAX_FILENAME_LEN];
	 /* Do something useful with siginfo_t */
  	if ((sig != SIGSEGV) && (sig != SIGINT)) {
		syslog(LOG_ERR,"Got signal %d#92", sig);
//		 printf("Came here %d\n", __LINE__);
		return;
	}
	res = GetConfig_LogPath(gcLogFilePathName, MAX_FILENAME_LEN);   
	if (res == FALSE) {
//		 printf("Came here %d\n", __LINE__);
		OSAL_sprintf(gcLogFilePathName, "/tmp");
	}
	strcat(gcLogFilePathName, "/callstack_wimaxcu.log");
	if(OSAL_fopen(&fp, gcLogFilePathName, "a", 0) < 0) {
		syslog(LOG_ERR, "Got signal %d, faulty address is %p, "
		"from %p", sig, info->si_addr, 
		 uc->uc_mcontext.gregs[REG_EIP]);
		syslog(LOG_ERR, "Could not open a file %s to log call stack");
//		printf("Came here %d\n", __LINE__);
		
  		return;
	}
	sprintf(command, "/bin/date > %s",gcLogFilePathName); 
	 //printf("Came here %d\n", __LINE__);
	system(command); 
	fprintf(fp, "==================================================================================\n");
	fprintf(fp, "If Faulty address is in wimaxd excution segment \n");
	fprintf(fp, "Use addr2line to decode the address info into file name and line no\n");
	fprintf(fp, "For Example \n");
	fprintf(fp, "$> sudo addr2line -e /usr/bin/wimaxd 806f5fe \n");
	fprintf(fp, "If Faulty address is in shared object file \n");
	fprintf(fp, "$> sudo objdump -l -d -M intel /usr/lib/libWmxInstrument.so.0 > ./libinstru_dis\n");
	fprintf(fp, "Use the function name and offset to function and search file above for the line no \n");
	fprintf(fp, "==================================================================================\n\n");
	
	fprintf(fp, "Got signal %d, faulty address is %p, "
		"from %p\n", sig, info->si_addr, 
		 uc->uc_mcontext.gregs[REG_EIP]);
	// printf("Came here %d\n", __LINE__);
  	
  	trace_size = backtrace(trace, 16);
  	/* overwrite sigaction with caller's address */
  	trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];

  	messages = backtrace_symbols(trace, trace_size);
  	/* skip first stack frame (points here) */
  	fprintf(fp,"[bt] Execution path: \n");	
  	for (i=1; i<trace_size; ++i)
		fprintf(fp, "[bt] %s  \n", messages[i]);
	
	
 	fclose(fp);
	
}

void wimaxcu_stop_signal_handler(int sig)
{
    	// signals are captured
    	syslog(LOG_INFO, ":wimaxcu recieved signal %d", sig);
	Finalize(&DeviceID);
	exit(0);
    	// sleep(20);
}

void wimaxcu_signal_handler(int sig, siginfo_t *info,
				   void *secret) 
{
    // signals are captured
  	static no_of_signals = 0;
	
	if(no_of_signals >= 1)  {
		printf("wimaxcu recieved second signal no %d \n", sig);
		print_callstack_to_file(sig, info, secret);
		exit(0);
	} else {
		printf("wimaxcu recieved first signal no %d \n",sig);
	}

	no_of_signals++;
	printf("Call stack is added to file \n");
	printf("Please check /var/log/wimax folder \n");

 	print_callstack_to_file(sig, info, secret);
	
	
	// kalyan
	// If wimaxcu recieved segmentation fault 
	// Stack might be corrupted
	// So it is good idea to just exit
	// This may recives some system resources hanging

	if(sig == SIGSEGV) {
		printf("Exit \n");
		exit(0);
	}
		

	wimaxcu_stop_signal_handler(sig);
	
}

/*
 * Function: main
 * Description: main function
*/
int main(int argc, char *argv[])
{
    int ret = 0;
    WIMAX_API_RET wmxStatus;

	parsed_cmd out_cmd;
	struct sigaction sa;


    // checking user priviledge
	// Disabled permission checking so non-root can run it
    //if (geteuid() != (uid_t) 0) {
//	fprintf(stderr,
//		"ERROR: You do not possess sufficient privileges to perform this action.\n");
//		return 1;
//	}


    // validate user command
    if (validate_cmd(argc, argv, &out_cmd) != 0) {
        	Help();
        	return 1;
    	}

    if (out_cmd.cmd == CMD_HELP) {
        	Help();
	return 0;
    	}

	sa.sa_sigaction = (void *)wimaxcu_signal_handler;
    	sigemptyset (&sa.sa_mask);
    	sa.sa_flags = SA_RESTART | SA_SIGINFO;

    	sigaction(SIGSEGV, &sa, NULL);
    	sigaction(SIGUSR1, &sa, NULL);  

    	signal(SIGINT, wimaxcu_stop_signal_handler);
    	signal(SIGTERM, wimaxcu_stop_signal_handler);
    	signal(SIGPIPE, SIG_IGN);
    	signal(SIGUSR1, SIG_IGN); 

	    memset(&DeviceID, 0, sizeof(WIMAX_API_DEVICE_ID));
	DeviceID.privilege = WIMAX_API_PRIVILEGE_READ_WRITE;

    // Initialize the SDK (CommonAPI)
    wmxStatus = Initialize(&DeviceID);
    if(WIMAX_API_RET_SUCCESS != wmxStatus) {
        printf("ERROR: Make sure WiMAX Network Service is running.\n");
        return 1;
    }
	// Kalyan 5.0.09 merge
	// This delay will allow the Initialize to init everything in its threads
	//sleep(1);
  	// Execute the command
    ret = cmd_handler(&DeviceID, &out_cmd);


    // Finalize the SDK
    	Finalize(&DeviceID);

    return ret;
}

int wmxcu_sem_timeout(sem_t* s,int milliseconds)
{
#define TIMEVAL_TO_TIMESPEC(tv, ts)	{	\
	(ts)->tv_sec = (tv)->tv_sec;	\
	(ts)->tv_nsec = (tv)->tv_usec * 1000; 	\
}

	struct timespec ts;
	struct timeval tv;
	int ret = -1;

 	gettimeofday(&tv, NULL);
	TIMEVAL_TO_TIMESPEC(&tv, &ts);

	// Split the incoming millisecs into seconds and nano-seconds struct as required by the timedjoin method

	ts.tv_sec += (milliseconds / 1000);
	ts.tv_nsec += ((milliseconds % 1000) * 1000 * 1000);	// 1 ms = 1000000 ns
	if (ts.tv_nsec >= 1000000000) {
		ts.tv_nsec -= 1000000000;
		++ts.tv_sec;
	}
	while ((ret = sem_timedwait(s, &ts)) == -1 && errno == EINTR)
 		continue; /* Restart when interrupted by handler */

	if (ret == -1)
	{
		if (errno == ETIMEDOUT)
		{
			 return 1;
		}
		 else
			printf ("ERROR: Internal failure\n");

	 }
	return 0;
}