elpa2_compute_real_template.X90 240 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
#if 0
!    This file is part of ELPA.
!
!    The ELPA library was originally created by the ELPA consortium,
!    consisting of the following organizations:
!
!    - Max Planck Computing and Data Facility (MPCDF), fomerly known as
!      Rechenzentrum Garching der Max-Planck-Gesellschaft (RZG),
!    - Bergische Universität Wuppertal, Lehrstuhl für angewandte
!      Informatik,
!    - Technische Universität München, Lehrstuhl für Informatik mit
!      Schwerpunkt Wissenschaftliches Rechnen ,
!    - Fritz-Haber-Institut, Berlin, Abt. Theorie,
!    - Max-Plack-Institut für Mathematik in den Naturwissenschaftrn,
!      Leipzig, Abt. Komplexe Strukutren in Biologie und Kognition,
!      and
!    - IBM Deutschland GmbH
!
!    This particular source code file contains additions, changes and
!    enhancements authored by Intel Corporation which is not part of
!    the ELPA consortium.
!
!    More information can be found here:
!    http://elpa.mpcdf.mpg.de/
!
!    ELPA is free software: you can redistribute it and/or modify
!    it under the terms of the version 3 of the license of the
!    GNU Lesser General Public License as published by the Free
!    Software Foundation.
!
!    ELPA is distributed in the hope that it will be useful,
!    but WITHOUT ANY WARRANTY; without even the implied warranty of
!    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
!    GNU Lesser General Public License for more details.
!
!    You should have received a copy of the GNU Lesser General Public License
!    along with ELPA.  If not, see <http://www.gnu.org/licenses/>
!
!    ELPA reflects a substantial effort on the part of the original
!    ELPA consortium, and we ask you to respect the spirit of the
!    license that we chose: i.e., please contribute any changes you
!    may have back to the original ELPA library distribution, and keep
!    any derivatives of ELPA under the same license that we chose for
!    the original distribution, the GNU Lesser General Public License.
!
!
! ELPA1 -- Faster replacements for ScaLAPACK symmetric eigenvalue routines
!
! Copyright of the original code rests with the authors inside the ELPA
! consortium. The copyright of any additional modifications shall rest
! with their original authors, but shall adhere to the licensing terms
! distributed along with the original code in the file "COPYING".



! ELPA2 -- 2-stage solver for ELPA
!
! Copyright of the original code rests with the authors inside the ELPA
! consortium. The copyright of any additional modifications shall rest
! with their original authors, but shall adhere to the licensing terms
! distributed along with the original code in the file "COPYING".
#endif

#ifdef DOUBLE_PRECISION_REAL
    subroutine bandred_real_double(na, a, lda, nblk, nbw, matrixCols, numBlocks, mpi_comm_rows, mpi_comm_cols, &
                            tmat, wantDebug, useGPU, success, useQR)
#else
    subroutine bandred_real_single(na, a, lda, nblk, nbw, matrixCols, numBlocks, mpi_comm_rows, mpi_comm_cols, &
                            tmat, wantDebug, useGPU, success, useQR)
#endif

  !-------------------------------------------------------------------------------
  !  bandred_real: Reduces a distributed symmetric matrix to band form
  !
  !  Parameters
  !
  !  na          Order of matrix
  !
  !  a(lda,matrixCols)    Distributed matrix which should be reduced.
  !              Distribution is like in Scalapack.
  !              Opposed to Scalapack, a(:,:) must be set completely (upper and lower half)
  !              a(:,:) is overwritten on exit with the band and the Householder vectors
  !              in the upper half.
  !
  !  lda         Leading dimension of a
  !  matrixCols  local columns of matrix a
  !
  !  nblk        blocksize of cyclic distribution, must be the same in both directions!
  !
  !  nbw         semi bandwith of output matrix
  !
  !  mpi_comm_rows
  !  mpi_comm_cols
  !              MPI-Communicators for rows/columns
  !
  !  tmat(nbw,nbw,numBlocks)    where numBlocks = (na-1)/nbw + 1
  !              Factors for the Householder vectors (returned), needed for back transformation
  !
  !-------------------------------------------------------------------------------

      use cuda_functions
      use iso_c_binding
      use elpa1_compute
#ifdef HAVE_DETAILED_TIMINGS
      use timings
#endif
#ifdef WITH_OPENMP
      use omp_lib
#endif
      use precision
      implicit none

      integer(kind=ik)           :: na, lda, nblk, nbw, matrixCols, numBlocks, mpi_comm_rows, mpi_comm_cols
#ifdef DESPERATELY_WANT_ASSUMED_SIZE
      real(kind=REAL_DATATYPE)              :: a(lda,*), tmat(nbw,nbw,*)
#else
      real(kind=REAL_DATATYPE)              :: a(lda,matrixCols), tmat(nbw,nbw,numBlocks)
#endif
      real(kind=REAL_DATATYPE)              :: eps
      logical, intent(in)        :: useGPU

      integer(kind=ik)           :: my_prow, my_pcol, np_rows, np_cols, mpierr
      integer(kind=ik)           :: l_cols, l_rows, vmrCols
      integer(kind=ik)           :: i, j, lcs, lce, lrs, lre, lc, lr, cur_pcol, n_cols, nrow
      integer(kind=ik)           :: istep, ncol, lch, lcx, nlc, mynlc
      integer(kind=ik)           :: tile_size, l_rows_tile, l_cols_tile

      real(kind=REAL_DATATYPE)              :: vnorm2, xf, aux1(nbw), aux2(nbw), vrl, tau, vav(nbw,nbw)

      real(kind=REAL_DATATYPE), allocatable :: tmpCUDA(:),  vmrCUDA(:),  umcCUDA(:)
      real(kind=REAL_DATATYPE), allocatable :: tmpCPU(:,:), vmrCPU(:,:), umcCPU(:,:)
      real(kind=REAL_DATATYPE), allocatable :: vr(:)
      ! needed for blocked QR decomposition
      integer(kind=ik)           :: PQRPARAM(11), work_size
      real(kind=REAL_DATATYPE)              :: dwork_size(1)
      real(kind=REAL_DATATYPE), allocatable :: work_blocked(:), tauvector(:), blockheuristic(:)

      integer(kind=C_intptr_T)   :: a_dev, vmr_dev, umc_dev, tmat_dev, vav_dev
#ifdef WITH_MPI
      integer(kind=ik), external :: numroc
#endif
      integer(kind=ik)           :: ierr
      integer(kind=ik)           :: cur_l_rows, cur_l_cols, vmr_size, umc_size
      integer(kind=c_size_t)     :: lc_start, lc_end
      integer(kind=ik)           :: lr_end
      integer(kind=ik)           :: na_rows, na_cols

      logical, intent(in)        :: wantDebug
      logical, intent(out)       :: success
      logical                    :: successCUDA
      integer(kind=ik)           :: istat
      character(200)             :: errorMessage

      logical, intent(in)        :: useQR

      integer(kind=ik)           :: mystart, myend, m_way, n_way, work_per_thread, m_id, n_id, n_threads, ii, pp, transformChunkSize

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
      call timer%start("bandred_real_double")
#else
      call timer%start("bandred_real_single")
#endif
#endif
      call mpi_comm_rank(mpi_comm_rows,my_prow,mpierr)
      call mpi_comm_size(mpi_comm_rows,np_rows,mpierr)
      call mpi_comm_rank(mpi_comm_cols,my_pcol,mpierr)
      call mpi_comm_size(mpi_comm_cols,np_cols,mpierr)
      success = .true.


      ! Semibandwith nbw must be a multiple of blocksize nblk
      if (mod(nbw,nblk)/=0) then
        if (my_prow==0 .and. my_pcol==0) then
          if (wantDebug) then
            write(error_unit,*) 'ELPA2_bandred_real: ERROR: nbw=',nbw,', nblk=',nblk
            write(error_unit,*) 'ELPA2_bandred_real: ELPA2 works only for nbw==n*nblk'
          endif
          success = .false.
          return
        endif
      endif

      if (useGPU) then
#ifdef WITH_MPI
        na_rows = numroc(na, nblk, my_prow, 0, np_rows)
        na_cols = numroc(na, nblk, my_pcol, 0, np_cols)
#else
        na_rows = na
        na_cols = na
#endif
      endif

      ! Matrix is split into tiles; work is done only for tiles on the diagonal or above

      tile_size = nblk*least_common_multiple(np_rows,np_cols) ! minimum global tile size
      tile_size = ((128*max(np_rows,np_cols)-1)/tile_size+1)*tile_size ! make local tiles at least 128 wide

      l_rows_tile = tile_size/np_rows ! local rows of a tile
      l_cols_tile = tile_size/np_cols ! local cols of a tile

      if (useQR) then

        if (useGPU) then
          print *,"qr decomposition at the moment not supported with GPU"
          stop
        endif

        if (which_qr_decomposition == 1) then
          call qr_pqrparam_init(pqrparam(1:11),    nblk,'M',0,   nblk,'M',0,   nblk,'M',1,'s')
          allocate(tauvector(na), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating tauvector "//errorMessage
            stop
          endif

          allocate(blockheuristic(nblk), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating blockheuristic "//errorMessage
            stop
          endif

          l_rows = local_index(na, my_prow, np_rows, nblk, -1)
          allocate(vmrCPU(max(l_rows,1),na), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating vmrCPU "//errorMessage
            stop
          endif

          vmrCols = na
#ifdef DOUBLE_PRECISION_REAL

#ifdef DESPERATELY_WANT_ASSUMED_SIZE_QR
          call qr_pdgeqrf_2dcomm_double(a, lda, matrixCols, vmrCPU, max(l_rows,1), vmrCols, tauvector(1), na, tmat(1,1,1), &
                                 nbw, nbw, dwork_size, 1, -1, na, nbw, nblk, nblk, na, na, 1, 0, PQRPARAM(1:11), &
                                 mpi_comm_rows, mpi_comm_cols, blockheuristic)

#else
          call qr_pdgeqrf_2dcomm_double(a(1:lda,1:matrixCols), matrixCols, lda, vmrCPU(1:max(l_rows,1),1:vmrCols), max(l_rows,1), &
                                 vmrCols, tauvector(1:na), na, tmat(1:nbw,1:nbw,1), nbw, &
                                 nbw, dwork_size(1:1), 1, -1, na, nbw, nblk, nblk, na, na, 1, 0, PQRPARAM(1:11), &
                                 mpi_comm_rows, mpi_comm_cols, blockheuristic)
#endif

#else /* DOUBLE_PRECISION_REAL */

#ifdef DESPERATELY_WANT_ASSUMED_SIZE_QR
          call qr_pdgeqrf_2dcomm_single(a, lda, matrixCols, vmrCPU, max(l_rows,1), vmrCols, tauvector(1), na, tmat(1,1,1), &
                                 nbw, nbw, dwork_size, 1, -1, na, nbw, nblk, nblk, na, na, 1, 0, PQRPARAM(1:11), &
                                 mpi_comm_rows, mpi_comm_cols, blockheuristic)

#else
          call qr_pdgeqrf_2dcomm_single(a(1:lda,1:matrixCols), matrixCols, lda, vmrCPU(1:max(l_rows,1),1:vmrCols), max(l_rows,1), &
                                 vmrCols, tauvector(1:na), na, tmat(1:nbw,1:nbw,1), nbw, &
                                 nbw, dwork_size(1:1), 1, -1, na, nbw, nblk, nblk, na, na, 1, 0, PQRPARAM(1:11), &
                                 mpi_comm_rows, mpi_comm_cols, blockheuristic)
#endif


#endif /* DOUBLE_PRECISION_REAL */
          work_size = dwork_size(1)
          allocate(work_blocked(work_size), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating work_blocked "//errorMessage
            stop
          endif
#ifdef DOUBLE_PRECISION_REAL
          work_blocked = 0.0_rk8
#else
          work_blocked = 0.0_rk4
#endif
          deallocate(vmrCPU, stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when deallocating vmrCPU "//errorMessage
            stop
          endif

        endif ! which_qr_decomposition

      endif ! useQr

      if (useGPU) then
        ! Here we convert the regular host array into a pinned host array
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(a_dev, lda*na_cols*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(a_dev, lda*na_cols*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"bandred_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(tmat_dev, nbw*nbw*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(tmat_dev, nbw*nbw*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"bandred_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(vav_dev, nbw*nbw*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(vav_dev, nbw*nbw*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"bandred_real: error in cudaMalloc"
          stop
        endif

        cur_l_rows = 0
        cur_l_cols = 0
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_memcpy(a_dev, loc(a(1,1)), (lda)*(na_cols)*size_of_double_real_datatype, cudaMemcpyHostToDevice)
#else
        successCUDA = cuda_memcpy(a_dev, loc(a(1,1)), (lda)*(na_cols)*size_of_single_real_datatype, cudaMemcpyHostToDevice)
#endif
        if (.not.(successCUDA)) then
          print *,"bandred_real: error in cudaMemcpy"
          stop
        endif
      endif ! useGPU


      do istep = (na-1)/nbw, 1, -1

        n_cols = MIN(na,(istep+1)*nbw) - istep*nbw ! Number of columns in current step

        ! Number of local columns/rows of remaining matrix
        l_cols = local_index(istep*nbw, my_pcol, np_cols, nblk, -1)
        l_rows = local_index(istep*nbw, my_prow, np_rows, nblk, -1)

        if (useGPU) then
          cur_l_rows = max(l_rows, 1)
          cur_l_cols = max(l_cols, 1)

          vmr_size = cur_l_rows * 2 * n_cols
          umc_size = cur_l_cols * 2 * n_cols

          ! Allocate vmr and umc only if the inew size exceeds their current capacity
          ! Added for FORTRAN CALLS
          if ((.not. allocated(vr)) .or. (l_rows + 1 .gt. ubound(vr, dim=1))) then
            if (allocated(vr)) then
              deallocate(vr, stat=istat, errmsg=errorMessage)
              if (istat .ne. 0) then
                print *,"bandred_real: error when deallocating vr "//errorMessage
                stop
              endif
            endif
            allocate(vr(l_rows + 1), stat=istat, errmsg=errorMessage)
            if (istat .ne. 0) then
              print *,"bandred_real: error when allocating vr "//errorMessage
              stop
            endif

          endif

          if ((.not. allocated(vmrCUDA)) .or. (vmr_size .gt. ubound(vmrCUDA, dim=1))) then
            if (allocated(vmrCUDA)) then
              deallocate(vmrCUDA, stat=istat, errmsg=errorMessage)
              if (istat .ne. 0) then
                print *,"bandred_real: error when allocating vmrCUDA "//errorMessage
                stop
              endif

              successCUDA = cuda_free(vmr_dev)
              if (.not.(successCUDA)) then
                print *,"bandred_real: error in cuda_free"
                stop
              endif
            endif

            allocate(vmrCUDA(vmr_size), stat=istat, errmsg=errorMessage)
            if (istat .ne. 0) then
              print *,"bandred_real: error when allocating vmrCUDA "//errorMessage
              stop
            endif
#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_malloc(vmr_dev, vmr_size*size_of_double_real_datatype)
#else
            successCUDA = cuda_malloc(vmr_dev, vmr_size*size_of_single_real_datatype)
#endif
            if (.not.(successCUDA)) then
              print *,"bandred_real: error in cudaMalloc"
              stop
            endif

          endif

          if ((.not. allocated(umcCUDA)) .or. (umc_size .gt. ubound(umcCUDA, dim=1))) then
            if (allocated(umcCUDA)) then
              deallocate(umcCUDA, stat=istat, errmsg=errorMessage)
              if (istat .ne. 0) then
                print *,"bandred_real: error when deallocating umcCUDA "//errorMessage
                stop
              endif

              successCUDA = cuda_free(umc_dev)
              if (.not.(successCUDA)) then
                 print *,"bandred_real: error in cudaFree"
                 stop
              endif

            endif

            allocate(umcCUDA(umc_size), stat=istat, errmsg=errorMessage)
            if (istat .ne. 0) then
              print *,"bandred_real: error when deallocating umcCUDA "//errorMessage
              stop
            endif
#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_malloc(umc_dev, umc_size*size_of_double_real_datatype)
#else
            successCUDA = cuda_malloc(umc_dev, umc_size*size_of_single_real_datatype)
#endif
            if (.not.(successCUDA)) then
              print *,"bandred_real: error in cudaMalloc"
              stop
            endif

          endif
        else ! GPU not used
          ! Allocate vmr and umc to their exact sizes so that they can be used in bcasts and reduces

          allocate(vmrCPU(max(l_rows,1),2*n_cols), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating vmrCPU "//errorMessage
            stop
          endif

          allocate(umcCPU(max(l_cols,1),2*n_cols), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating umcCPU "//errorMessage
            stop
          endif

          allocate(vr(l_rows+1), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"bandred_real: error when allocating vr "//errorMessage
            stop
          endif
        endif ! use GPU
#ifdef DOUBLE_PRECISION_REAL
        if (useGPU) then
          vmrCUDA(1 : cur_l_rows * n_cols) = 0._rk8
        else
          vmrCPU(1:l_rows,1:n_cols) = 0._rk8
        endif
        vr(:) = 0._rk8
        tmat(:,:,istep) = 0._rk8

#else
        if (useGPU) then
          vmrCUDA(1 : cur_l_rows * n_cols) = 0._rk4
        else
          vmrCPU(1:l_rows,1:n_cols) = 0._rk4
        endif
        vr(:) = 0._rk4
        tmat(:,:,istep) = 0._rk4
#endif

        if (useGPU) then
#ifdef DOUBLE_PRECISION_REAL
          umcCUDA(1 : umc_size) = 0._rk8
#else
          umcCUDA(1 : umc_size) = 0._rk4
#endif
          lc_start = local_index(istep*nbw+1, my_pcol, np_cols, nblk, -1)
          lc_end   = local_index(istep*nbw+n_cols, my_pcol, np_cols, nblk, -1)
          lr_end   = local_index((istep-1)*nbw + n_cols, my_prow, np_rows, nblk, -1)

          if(lc_start .le. 0) lc_start = 1

          ! Here we assume that the processor grid and the block grid are aligned
          cur_pcol = pcol(istep*nbw+1, nblk, np_cols)

          if(my_pcol == cur_pcol) then
#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_memcpy2d(loc(a(1, lc_start)), lda*size_of_double_real_datatype,         &
                                       (a_dev + ((lc_start-1) * lda*size_of_double_real_datatype)),    &
                                       lda*size_of_double_real_datatype, lr_end*size_of_double_real_datatype, &
                                       (lc_end - lc_start+1), cudaMemcpyDeviceToHost)
#else
            successCUDA = cuda_memcpy2d(loc(a(1, lc_start)), lda*size_of_single_real_datatype,         &
                                       (a_dev + ((lc_start-1) * lda*size_of_single_real_datatype)),    &
                                       lda*size_of_single_real_datatype, lr_end*size_of_single_real_datatype, &
                                       (lc_end - lc_start+1), cudaMemcpyDeviceToHost)

#endif
            if (.not.(successCUDA)) then
              print *,"bandred_real: error in cudaMemcpy2d"
              stop
            endif

          endif
        endif ! useGPU

        ! Reduce current block to lower triangular form

        if (useQR) then
          if (which_qr_decomposition == 1) then
            vmrCols = 2*n_cols
#ifdef DOUBLE_PRECISION_REAL

#ifdef DESPERATELY_WANT_ASSUMED_SIZE_QR
            call qr_pdgeqrf_2dcomm_double(a, lda, matrixCols, vmrCPU, max(l_rows,1), vmrCols, tauvector(1), &
                                   na, tmat(1,1,istep), nbw, nbw, work_blocked, work_size,        &
                                     work_size, na, n_cols, nblk, nblk,        &
                                     istep*nbw+n_cols-nbw, istep*nbw+n_cols, 1,&
                                     0, PQRPARAM(1:11), mpi_comm_rows, mpi_comm_cols,&
                                     blockheuristic)

#else
            call qr_pdgeqrf_2dcomm_double(a(1:lda,1:matrixCols), lda, matrixCols, vmrCPU(1:max(l_rows,1),1:vmrCols) ,   &
                                    max(l_rows,1), vmrCols, tauvector(1:na), na, &
                                     tmat(1:nbw,1:nbw,istep), nbw, nbw, work_blocked(1:work_size), work_size, &
                                     work_size, na, n_cols, nblk, nblk,        &
                                     istep*nbw+n_cols-nbw, istep*nbw+n_cols, 1,&
                                     0, PQRPARAM(1:11), mpi_comm_rows, mpi_comm_cols,&
                                     blockheuristic)
#endif

#else /* DOUBLE_PRECISION_REAL */

#ifdef DESPERATELY_WANT_ASSUMED_SIZE_QR
            call qr_pdgeqrf_2dcomm_single(a, lda, matrixCols, vmrCPU, max(l_rows,1), vmrCols, tauvector(1), &
                                   na, tmat(1,1,istep), nbw, nbw, work_blocked, work_size,        &
                                     work_size, na, n_cols, nblk, nblk,        &
                                     istep*nbw+n_cols-nbw, istep*nbw+n_cols, 1,&
                                     0, PQRPARAM(1:11), mpi_comm_rows, mpi_comm_cols,&
                                     blockheuristic)

#else
            call qr_pdgeqrf_2dcomm_single(a(1:lda,1:matrixCols), lda, matrixCols, vmrCPU(1:max(l_rows,1),1:vmrCols) ,   &
                                    max(l_rows,1), vmrCols, tauvector(1:na), na, &
                                     tmat(1:nbw,1:nbw,istep), nbw, nbw, work_blocked(1:work_size), work_size, &
                                     work_size, na, n_cols, nblk, nblk,        &
                                     istep*nbw+n_cols-nbw, istep*nbw+n_cols, 1,&
                                     0, PQRPARAM(1:11), mpi_comm_rows, mpi_comm_cols,&
                                     blockheuristic)
#endif


#endif /* DOUBLE_PRECISION_REAL */
          endif
       else !useQR

         do lc = n_cols, 1, -1

           ncol = istep*nbw + lc ! absolute column number of householder vector
           nrow = ncol - nbw ! Absolute number of pivot row

           lr  = local_index(nrow, my_prow, np_rows, nblk, -1) ! current row length
           lch = local_index(ncol, my_pcol, np_cols, nblk, -1) ! HV local column number

           tau = 0

           if (nrow == 1) exit ! Nothing to do

           cur_pcol = pcol(ncol, nblk, np_cols) ! Processor column owning current block

           if (my_pcol==cur_pcol) then

             ! Get vector to be transformed; distribute last element and norm of
             ! remaining elements to all procs in current column

             vr(1:lr) = a(1:lr,lch) ! vector to be transformed

             if (my_prow==prow(nrow, nblk, np_rows)) then
               aux1(1) = dot_product(vr(1:lr-1),vr(1:lr-1))
               aux1(2) = vr(lr)
             else
               aux1(1) = dot_product(vr(1:lr),vr(1:lr))
#ifdef DOUBLE_PRECISION_RAEL
               aux1(2) = 0._rk8
#else
               aux1(2) = 0._rk4
#endif
             endif

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
             call mpi_allreduce(aux1, aux2, 2, MPI_REAL8, MPI_SUM, mpi_comm_rows, mpierr)
#else
             call mpi_allreduce(aux1, aux2, 2, MPI_REAL4, MPI_SUM, mpi_comm_rows, mpierr)
#endif

#else /* WITH_MPI */
              aux2 = aux1 ! this should be optimized
#endif /* WITH_MPI */

             vnorm2 = aux2(1)
             vrl    = aux2(2)

             ! Householder transformation
#ifdef DOUBLE_PRECISION_REAL
             call hh_transform_real_double(vrl, vnorm2, xf, tau)
#else
             call hh_transform_real_single(vrl, vnorm2, xf, tau)
#endif
             ! Scale vr and store Householder vector for back transformation

             vr(1:lr) = vr(1:lr) * xf
             if (my_prow==prow(nrow, nblk, np_rows)) then
               a(1:lr-1,lch) = vr(1:lr-1)
               a(lr,lch) = vrl
#ifdef DOUBLE_PRECISION_REAL
               vr(lr) = 1._rk8
#else
               vr(lr) = 1._rk4
#endif
             else
               a(1:lr,lch) = vr(1:lr)
             endif

           endif

           ! Broadcast Householder vector and tau along columns

           vr(lr+1) = tau
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
           call MPI_Bcast(vr, lr+1, MPI_REAL8, cur_pcol, mpi_comm_cols, mpierr)
#else
           call MPI_Bcast(vr, lr+1, MPI_REAL4, cur_pcol, mpi_comm_cols, mpierr)
#endif

#endif /* WITH_MPI */
           if (useGPU) then
             vmrCUDA(cur_l_rows * (lc - 1) + 1 : cur_l_rows * (lc - 1) + lr) = vr(1:lr)
           else
             vmrCPU(1:lr,lc) = vr(1:lr)
           endif

           tau = vr(lr+1)
           tmat(lc,lc,istep) = tau ! Store tau in diagonal of tmat

           ! Transform remaining columns in current block with Householder vector
           ! Local dot product

           aux1 = 0

#ifdef WITH_OPENMP
           !Open up one omp region to avoid paying openmp overhead.
           !This does not help performance due to the addition of two openmp barriers around the MPI call,
           !But in the future this may be beneficial if these barriers are replaced with a faster implementation

           !$omp parallel private(mynlc, j, lcx, ii, pp ) shared(aux1)
           mynlc = 0 ! number of local columns

           !This loop does not have independent iterations,
           !'mynlc' is incremented each iteration, and it is difficult to remove this dependency
           !Thus each thread executes every iteration of the loop, except it only does the work if it 'owns' that iteration
           !That is, a thread only executes the work associated with an iteration if its thread id is congruent to
           !the iteration number modulo the number of threads
           do j=1,lc-1
             lcx = local_index(istep*nbw+j, my_pcol, np_cols, nblk, 0)
             if (lcx>0 ) then
               mynlc = mynlc+1
               if ( mod((j-1), omp_get_num_threads()) .eq. omp_get_thread_num() ) then
                   if (lr>0) aux1(mynlc) = dot_product(vr(1:lr),a(1:lr,lcx))
               endif
             endif
           enddo

           ! Get global dot products

           !$omp barrier
           !$omp single
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
           if (mynlc>0) call mpi_allreduce(aux1, aux2, mynlc, MPI_REAL8, MPI_SUM, mpi_comm_rows, mpierr)
#else
           if (mynlc>0) call mpi_allreduce(aux1, aux2, mynlc, MPI_REAL4, MPI_SUM, mpi_comm_rows, mpierr)
#endif

#else /* WITH_MPI */
           if (mynlc>0) aux2 = aux1

#endif /* WITH_MPI */
           !$omp end single
           !$omp barrier

           ! Transform
           transformChunkSize=32
           mynlc = 0
           do j=1,lc-1
             lcx = local_index(istep*nbw+j, my_pcol, np_cols, nblk, 0)
             if (lcx>0) then
               mynlc = mynlc+1
               !This loop could be parallelized with an openmp pragma with static scheduling and chunk size 32
               !However, for some reason this is slower than doing it manually, so it is parallelized as below.
               do ii=omp_get_thread_num()*transformChunkSize,lr,omp_get_num_threads()*transformChunkSize
                  do pp = 1,transformChunkSize
                      if (pp + ii > lr) exit
                          a(ii+pp,lcx) = a(ii+pp,lcx) - tau*aux2(mynlc)*vr(ii+pp)
                  enddo
               enddo
             endif
           enddo
           !$omp end parallel
#else /* WITH_OPENMP */
           nlc = 0 ! number of local columns
           do j=1,lc-1
             lcx = local_index(istep*nbw+j, my_pcol, np_cols, nblk, 0)
             if (lcx>0) then
               nlc = nlc+1
               if (lr>0) aux1(nlc) = dot_product(vr(1:lr),a(1:lr,lcx))
             endif
           enddo

           ! Get global dot products
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
           if (nlc>0) call mpi_allreduce(aux1, aux2, nlc, MPI_REAL8, MPI_SUM, mpi_comm_rows, mpierr)
#else
           if (nlc>0) call mpi_allreduce(aux1, aux2, nlc, MPI_REAL4, MPI_SUM, mpi_comm_rows, mpierr)
#endif

#else /* WITH_MPI */
           if (nlc>0) aux2=aux1
#endif /* WITH_MPI */
           ! Transform

           nlc = 0
           do j=1,lc-1
             lcx = local_index(istep*nbw+j, my_pcol, np_cols, nblk, 0)
             if (lcx>0) then
               nlc = nlc+1
               a(1:lr,lcx) = a(1:lr,lcx) - tau*aux2(nlc)*vr(1:lr)
             endif
           enddo
#endif /* WITH_OPENMP */
         enddo ! lc

         if (useGPU) then
           ! store column tiles back to GPU
           cur_pcol = pcol(istep*nbw+1, nblk, np_cols)
           if (my_pcol == cur_pcol) then
#ifdef DOUBLE_PRECISION_REAL
             successCUDA = cuda_memcpy2d((a_dev+((lc_start-1)*lda*size_of_double_real_datatype)),          &
                                          lda*size_of_double_real_datatype, loc(a(1, lc_start)),           &
                                          lda*size_of_double_real_datatype,  lr_end*size_of_double_real_datatype, &
                                          (lc_end - lc_start+1),cudaMemcpyHostToDevice)
#else
             successCUDA = cuda_memcpy2d((a_dev+((lc_start-1)*lda*size_of_single_real_datatype)),          &
                                          lda*size_of_single_real_datatype, loc(a(1, lc_start)),           &
                                          lda*size_of_single_real_datatype,  lr_end*size_of_single_real_datatype, &
                                          (lc_end - lc_start+1),cudaMemcpyHostToDevice)
#endif
             if (.not.(successCUDA)) then
               print *,"bandred_real: error in cudaMemcpy2d"
               stop
             endif

           endif
         endif

         ! Calculate scalar products of stored Householder vectors.
         ! This can be done in different ways, we use dsyrk

         vav = 0

#ifdef DOUBLE_PRECISION_REAL
         if (useGPU) then
           if (l_rows>0) &
             call dsyrk('U', 'T', n_cols, l_rows, 1.0_rk8, vmrCUDA, cur_l_rows, 0.0_rk8, vav, ubound(vav,dim=1))
         else
           if (l_rows>0) &
             call dsyrk('U', 'T', n_cols, l_rows, 1.0_rk8, vmrCPU, ubound(vmrCPU,dim=1), 0.0_rk8, vav, ubound(vav,dim=1))
         endif
#else
         if (useGPU) then
           if (l_rows>0) &
             call ssyrk('U', 'T', n_cols, l_rows, 1.0_rk4, vmrCUDA, cur_l_rows, 0.0_rk4, vav, ubound(vav,dim=1))
         else
           if (l_rows>0) &
             call ssyrk('U', 'T', n_cols, l_rows, 1.0_rk4, vmrCPU, ubound(vmrCPU,dim=1), 0.0_rk4, vav, ubound(vav,dim=1))
         endif
#endif

#ifdef DOUBLE_PRECISION_REAL
         call symm_matrix_allreduce_double(n_cols,vav, nbw, nbw,mpi_comm_rows)
#else
         call symm_matrix_allreduce_single(n_cols,vav, nbw, nbw,mpi_comm_rows)
#endif
         ! Calculate triangular matrix T for block Householder Transformation

         do lc=n_cols,1,-1
           tau = tmat(lc,lc,istep)
           if (lc<n_cols) then
#ifdef DOUBLE_PRECISION_REAL
             call dtrmv('U', 'T', 'N', n_cols-lc, tmat(lc+1,lc+1,istep), ubound(tmat,dim=1), vav(lc+1,lc), 1)
#else
             call strmv('U', 'T', 'N', n_cols-lc, tmat(lc+1,lc+1,istep), ubound(tmat,dim=1), vav(lc+1,lc), 1)
#endif
             tmat(lc,lc+1:n_cols,istep) = -tau * vav(lc+1:n_cols,lc)
           endif
         enddo
       endif

       ! Transpose vmr -> vmc (stored in umc, second half)

       if (useGPU) then
#ifdef DOUBLE_PRECISION_REAL
         call elpa_transpose_vectors_real_double  (vmrCUDA, cur_l_rows, mpi_comm_rows, &
                                            umcCUDA(cur_l_cols * n_cols + 1), cur_l_cols, mpi_comm_cols, &
                                            1, istep*nbw, n_cols, nblk)
#else
         call elpa_transpose_vectors_real_single  (vmrCUDA, cur_l_rows, mpi_comm_rows, &
                                            umcCUDA(cur_l_cols * n_cols + 1), cur_l_cols, mpi_comm_cols, &
                                            1, istep*nbw, n_cols, nblk)
#endif
       else
#ifdef DOUBLE_PRECISION_REAL
         call elpa_transpose_vectors_real_double  (vmrCPU, ubound(vmrCPU,dim=1), mpi_comm_rows, &
                                            umcCPU(1,n_cols+1), ubound(umcCPU,dim=1), mpi_comm_cols, &
                                            1, istep*nbw, n_cols, nblk)
#else
         call elpa_transpose_vectors_real_single  (vmrCPU, ubound(vmrCPU,dim=1), mpi_comm_rows, &
                                            umcCPU(1,n_cols+1), ubound(umcCPU,dim=1), mpi_comm_cols, &
                                            1, istep*nbw, n_cols, nblk)
#endif
       endif

       ! Calculate umc = A**T * vmr
       ! Note that the distributed A has to be transposed
       ! Opposed to direct tridiagonalization there is no need to use the cache locality
       ! of the tiles, so we can use strips of the matrix

       ! here the GPU version and CPU version diverged substantially, due to the newest
       ! optimizations due to Intel. The GPU version has to be re-written
       if (useGPU) then
#ifdef DOUBLE_PRECISION_REAL
         umcCUDA(1 : l_cols * n_cols) = 0.0_rk8
         vmrCUDA(cur_l_rows * n_cols + 1 : cur_l_rows * n_cols * 2) = 0._rk8
#else
         umcCUDA(1 : l_cols * n_cols) = 0.0_rk4
         vmrCUDA(cur_l_rows * n_cols + 1 : cur_l_rows * n_cols * 2) = 0._rk4
#endif

         if (l_cols>0 .and. l_rows>0) then
#ifdef DOUBLE_PRECISION_REAL
           successCUDA = cuda_memcpy(vmr_dev, loc(vmrCUDA(1)), vmr_size*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
           successCUDA = cuda_memcpy(vmr_dev, loc(vmrCUDA(1)), vmr_size*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
           if (.not.(successCUDA)) then
             print *,"bandred_real: error in cudaMemcpy"
             stop
           endif
#ifdef DOUBLE_PRECISION_REAL
           successCUDA = cuda_memcpy(umc_dev, loc(umcCUDA(1)), umc_size*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
           successCUDA = cuda_memcpy(umc_dev, loc(umcCUDA(1)), umc_size*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
           if (.not.(successCUDA)) then
             print *,"bandred_real: error in cudaMemcpy"
             stop
           endif

           do i=0,(istep*nbw-1)/tile_size

             lcs = i*l_cols_tile+1
             lce = min(l_cols,(i+1)*l_cols_tile)
             if (lce<lcs) cycle

             lre = min(l_rows,(i+1)*l_rows_tile)
#ifdef DOUBLE_PRECISION_REAL
             call cublas_dgemm('T', 'N', lce-lcs+1, n_cols, lre, &
                               1.0_rk8, (a_dev + ((lcs-1)*lda*size_of_double_real_datatype)), lda, vmr_dev,cur_l_rows, &
                               1.0_rk8, (umc_dev+ (lcs-1)*size_of_double_real_datatype), cur_l_cols)
#else
             call cublas_sgemm('T', 'N', lce-lcs+1, n_cols, lre, &
                               1.0_rk4, (a_dev + ((lcs-1)*lda*size_of_single_real_datatype)), lda, vmr_dev,cur_l_rows, &
                               1.0_rk4, (umc_dev+ (lcs-1)*size_of_single_real_datatype), cur_l_cols)
#endif
             if(i==0) cycle
             lre = min(l_rows,i*l_rows_tile)
#ifdef DOUBLE_PRECISION_REAL
             call cublas_dgemm('N', 'N', lre,n_cols, lce-lcs+1,&
                               1.0_rk8, (a_dev+ ((lcs-1)*lda*size_of_double_real_datatype)), lda,                  &
                               (umc_dev+(cur_l_cols * n_cols+lcs-1)*size_of_double_real_datatype), cur_l_cols, &
                               1.0_rk8, (vmr_dev+(cur_l_rows * n_cols)*size_of_double_real_datatype), cur_l_rows)
#else
             call cublas_sgemm('N', 'N', lre,n_cols, lce-lcs+1,&
                               1.0_rk4, (a_dev+ ((lcs-1)*lda*size_of_single_real_datatype)), lda,                  &
                               (umc_dev+(cur_l_cols * n_cols+lcs-1)*size_of_single_real_datatype), cur_l_cols, &
                               1.0_rk4, (vmr_dev+(cur_l_rows * n_cols)*size_of_single_real_datatype), cur_l_rows)
#endif
           enddo
#ifdef DOUBLE_PRECISION_REAL
           successCUDA = cuda_memcpy(loc(vmrCUDA(1)), vmr_dev,vmr_size*size_of_double_real_datatype,cudaMemcpyDeviceToHost)
#else
           successCUDA = cuda_memcpy(loc(vmrCUDA(1)), vmr_dev,vmr_size*size_of_single_real_datatype,cudaMemcpyDeviceToHost)
#endif
           if (.not.(successCUDA)) then
             print *,"bandred_real: error in cudaMemcpy"
             stop
           endif
#ifdef DOUBLE_PRECISION_REAL
           successCUDA = cuda_memcpy(loc(umcCUDA(1)), umc_dev, umc_size*size_of_double_real_datatype,cudaMemcpyDeviceToHost)
#else
           successCUDA = cuda_memcpy(loc(umcCUDA(1)), umc_dev, umc_size*size_of_single_real_datatype,cudaMemcpyDeviceToHost)
#endif
           if (.not.(successCUDA)) then
             print *,"bandred_real: error in cudaMemcpy"
             stop
           endif

         endif ! l_cols>0 .and. l_rows>0

       else ! do not useGPU version
         !Code for Algorithm 4

         n_way = 1
#ifdef WITH_OPENMP
         n_way = omp_get_max_threads()
#endif
         !umc(1:l_cols,1:n_cols) = 0.d0
         !vmr(1:l_rows,n_cols+1:2*n_cols) = 0
#ifdef WITH_OPENMP
         !$omp parallel private( i,lcs,lce,lrs,lre)
#endif
         if (n_way > 1) then
           !$omp do
           do i=1,min(l_cols_tile, l_cols)
#ifdef DOUBLE_PRECISION_REAL
             umcCPU(i,1:n_cols) = 0.0_rk8
#else
             umcCPU(i,1:n_cols) = 0.0_rk4
#endif
           enddo

           !$omp do
           do i=1,l_rows
#ifdef DOUBLE_PRECISION_REAL
             vmrCPU(i,n_cols+1:2*n_cols) = 0.0_rk8
#else
             vmrCPU(i,n_cols+1:2*n_cols) = 0.0_rk4
#endif
           enddo
           if (l_cols>0 .and. l_rows>0) then

             !SYMM variant 4
             !Partitioned Matrix Expression:
             ! Ct = Atl Bt + Atr Bb
             ! Cb = Atr' Bt + Abl Bb
             !
             !Loop invariant:
             ! Ct = Atl Bt + Atr Bb
             !
             !Update:
             ! C1 = A10'B0 + A11B1 + A21 B2
             !
             !This algorithm chosen because in this algoirhtm, the loop around the dgemm calls
             !is easily parallelized, and regardless of choise of algorithm,
             !the startup cost for parallelizing the dgemms inside the loop is too great

             !$omp do schedule(static,1)
             do i=0,(istep*nbw-1)/tile_size
               lcs = i*l_cols_tile+1                   ! local column start
               lce = min(l_cols, (i+1)*l_cols_tile)    ! local column end

               lrs = i*l_rows_tile+1                   ! local row start
               lre = min(l_rows, (i+1)*l_rows_tile)    ! local row end

               !C1 += [A11 A12] [B1
               !                 B2]
               if ( lre > lrs .and. l_cols > lcs ) then
#ifdef DOUBLE_PRECISION_REAL
                 call DGEMM('N', 'N', lre-lrs+1, n_cols, l_cols-lcs+1,          &
                            1.0_rk8, a(lrs,lcs), ubound(a,dim=1),                 &
                                  umcCPU(lcs,n_cols+1), ubound(umcCPU,dim=1),  &
                            0.0_rk8, vmrCPU(lrs,n_cols+1), ubound(vmrCPU,dim=1))
#else
                 call SGEMM('N', 'N', lre-lrs+1, n_cols, l_cols-lcs+1,          &
                            1.0_rk4, a(lrs,lcs), ubound(a,dim=1),                 &
                                  umcCPU(lcs,n_cols+1), ubound(umcCPU,dim=1),  &
                            0.0_rk4, vmrCPU(lrs,n_cols+1), ubound(vmrCPU,dim=1))
#endif
               endif

               ! C1 += A10' B0
               if ( lce > lcs .and. i > 0 ) then
#ifdef DOUBLE_PRECISION_REAL
                 call DGEMM('T', 'N', lce-lcs+1, n_cols, lrs-1,           &
                            1.0_rk8, a(1,lcs),   ubound(a,dim=1),           &
                                  vmrCPU(1,1),   ubound(vmrCPU,dim=1),   &
                            0.0_rk8, umcCPU(lcs,1), ubound(umcCPU,dim=1))
#else
                 call SGEMM('T', 'N', lce-lcs+1, n_cols, lrs-1,           &
                            1.0_rk4, a(1,lcs),   ubound(a,dim=1),           &
                                  vmrCPU(1,1),   ubound(vmrCPU,dim=1),   &
                            0.0_rk4, umcCPU(lcs,1), ubound(umcCPU,dim=1))
#endif
               endif
             enddo
           endif ! l_cols>0 .and. l_rows>0
         else ! n_way > 1
#ifdef DOUBLE_PRECISION_REAL
           umcCPU(1:l_cols,1:n_cols) = 0.0_rk8
           vmrCPU(1:l_rows,n_cols+1:2*n_cols) = 0._rk8
#else
           umcCPU(1:l_cols,1:n_cols) = 0.0_rk4
           vmrCPU(1:l_rows,n_cols+1:2*n_cols) = 0._rk4
#endif
           if (l_cols>0 .and. l_rows>0) then
             do i=0,(istep*nbw-1)/tile_size

               lcs = i*l_cols_tile+1
               lce = min(l_cols,(i+1)*l_cols_tile)
               if (lce<lcs) cycle

               lre = min(l_rows,(i+1)*l_rows_tile)
#ifdef DOUBLE_PRECISION_REAL
               call DGEMM('T', 'N', lce-lcs+1, n_cols, lre, 1.0_rk8, a(1,lcs), ubound(a,dim=1), &
                            vmrCPU, ubound(vmrCPU,dim=1), 1.0_rk8, umcCPU(lcs,1), ubound(umcCPU,dim=1))

               if (i==0) cycle
                 lre = min(l_rows,i*l_rows_tile)
                 call DGEMM('N', 'N', lre, n_cols, lce-lcs+1, 1.0_rk8, a(1,lcs), lda, &
                            umcCPU(lcs,n_cols+1), ubound(umcCPU,dim=1), 1.0_rk8, vmrCPU(1,n_cols+1), ubound(vmrCPU,dim=1))
#else
               call SGEMM('T', 'N', lce-lcs+1, n_cols, lre, 1.0_rk4, a(1,lcs), ubound(a,dim=1), &
                            vmrCPU, ubound(vmrCPU,dim=1), 1.0_rk4, umcCPU(lcs,1), ubound(umcCPU,dim=1))

               if (i==0) cycle
                 lre = min(l_rows,i*l_rows_tile)
                 call SGEMM('N', 'N', lre, n_cols, lce-lcs+1, 1.0_rk4, a(1,lcs), lda, &
                            umcCPU(lcs,n_cols+1), ubound(umcCPU,dim=1), 1.0_rk4, vmrCPU(1,n_cols+1), ubound(vmrCPU,dim=1))
#endif


             enddo
           endif
         endif ! n_way > 1
#ifdef WITH_OPENMP
        !$omp end parallel
#endif
       endif ! do not useGPU version

       ! Sum up all ur(:) parts along rows and add them to the uc(:) parts
       ! on the processors containing the diagonal
       ! This is only necessary if ur has been calculated, i.e. if the
       ! global tile size is smaller than the global remaining matrix

       if (useGPU) then
         ! here the GPU version and CPU version divereged due to the same reasons as above

         if (tile_size < istep*nbw) then
#ifdef DOUBLE_PRECISION_REAL
           call elpa_reduce_add_vectors_real_double  (vmrCUDA(cur_l_rows * n_cols + 1),cur_l_rows,mpi_comm_rows, &
                                               umcCUDA, cur_l_cols, mpi_comm_cols, &
                                               istep*nbw, n_cols, nblk)
#else
           call elpa_reduce_add_vectors_real_single  (vmrCUDA(cur_l_rows * n_cols + 1),cur_l_rows,mpi_comm_rows, &
                                               umcCUDA, cur_l_cols, mpi_comm_cols, &
                                               istep*nbw, n_cols, nblk)
#endif
         endif

         if (l_cols>0) then
           allocate(tmpCUDA(l_cols * n_cols), stat=istat, errmsg=errorMessage)
           if (istat .ne. 0) then
             print *,"bandred_real: error when allocating tmpCUDA "//errorMessage
             stop
           endif

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
           call mpi_allreduce(umcCUDA, tmpCUDA, l_cols*n_cols, MPI_REAL8, MPI_SUM, mpi_comm_rows, ierr)
#else
           call mpi_allreduce(umcCUDA, tmpCUDA, l_cols*n_cols, MPI_REAL4, MPI_SUM, mpi_comm_rows, ierr)
#endif

#else /* WITH_MPI */
           tmpCUDA(1 : l_cols * n_cols) = umcCUDA(1 : l_cols * n_cols)
#endif /* WITH_MPI */
           umcCUDA(1 : l_cols * n_cols) = tmpCUDA(1 : l_cols * n_cols)

           if (allocated(tmpCUDA)) then
             deallocate(tmpCUDA, stat=istat, errmsg=errorMessage)
             if (istat .ne. 0) then
               print *,"bandred_real: error when deallocating tmpCUDA "//errorMessage
               stop
             endif
           endif
         endif ! l_cols

         ! U = U * Tmat**T
#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(umc_dev, loc(umcCUDA(1)), umc_size*size_of_double_real_datatype, cudaMemcpyHostToDevice)
#else
         successCUDA = cuda_memcpy(umc_dev, loc(umcCUDA(1)), umc_size*size_of_single_real_datatype, cudaMemcpyHostToDevice)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif
#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(tmat_dev,loc(tmat(1,1,istep)),nbw*nbw*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
         successCUDA = cuda_memcpy(tmat_dev,loc(tmat(1,1,istep)),nbw*nbw*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif
#ifdef DOUBLE_PRECISION_REAL
         call cublas_dtrmm('Right', 'Upper', 'Trans', 'Nonunit', l_cols, n_cols, &
                           1.0_rk8, tmat_dev, nbw, umc_dev, cur_l_cols)
#else
         call cublas_strmm('Right', 'Upper', 'Trans', 'Nonunit', l_cols, n_cols, &
                           1.0_rk4, tmat_dev, nbw, umc_dev, cur_l_cols)
#endif
         ! VAV = Tmat * V**T * A * V * Tmat**T = (U*Tmat**T)**T * V * Tmat**T
#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(vav_dev,loc(vav(1,1)), nbw*nbw*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
         successCUDA = cuda_memcpy(vav_dev,loc(vav(1,1)), nbw*nbw*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif
#ifdef DOUBLE_PRECISION_REAL
         call cublas_dgemm('T', 'N', n_cols, n_cols, l_cols, &
                           1.0_rk8, umc_dev, cur_l_cols, (umc_dev+(cur_l_cols * n_cols )*size_of_double_real_datatype),cur_l_cols, &
                           0.0_rk8, vav_dev, nbw)

         call cublas_dtrmm('Right', 'Upper', 'Trans', 'Nonunit', n_cols, n_cols, &
                           1.0_rk8, tmat_dev, nbw, vav_dev, nbw)
#else
         call cublas_sgemm('T', 'N', n_cols, n_cols, l_cols, &
                           1.0_rk4, umc_dev, cur_l_cols, (umc_dev+(cur_l_cols * n_cols )*size_of_single_real_datatype),cur_l_cols, &
                           0.0_rk4, vav_dev, nbw)

         call cublas_strmm('Right', 'Upper', 'Trans', 'Nonunit', n_cols, n_cols, &
                           1.0_rk4, tmat_dev, nbw, vav_dev, nbw)
#endif

#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(loc(vav(1,1)), vav_dev, nbw*nbw*size_of_double_real_datatype, cudaMemcpyDeviceToHost)
#else
         successCUDA = cuda_memcpy(loc(vav(1,1)), vav_dev, nbw*nbw*size_of_single_real_datatype, cudaMemcpyDeviceToHost)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif

#ifdef DOUBLE_PRECISION_REAL
         call symm_matrix_allreduce_double(n_cols,vav, nbw,nbw,mpi_comm_cols)
#else
         call symm_matrix_allreduce_single(n_cols,vav, nbw,nbw,mpi_comm_cols)
#endif

#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(vav_dev, loc(vav(1,1)), nbw*nbw*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
         successCUDA = cuda_memcpy(vav_dev, loc(vav(1,1)), nbw*nbw*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif

         ! U = U - 0.5 * V * VAV
#ifdef DOUBLE_PRECISION_REAL
         call cublas_dgemm('N', 'N', l_cols, n_cols, n_cols,&
                           -0.5_rk8, (umc_dev+(cur_l_cols * n_cols )*size_of_double_real_datatype),cur_l_cols, vav_dev,nbw,&
                           1.0_rk8, umc_dev, cur_l_cols)

         successCUDA = cuda_memcpy(loc(umcCUDA(1)), umc_dev, umc_size*size_of_double_real_datatype, cudaMemcpyDeviceToHost)

#else
         call cublas_sgemm('N', 'N', l_cols, n_cols, n_cols,&
                           -0.5_rk4, (umc_dev+(cur_l_cols * n_cols )*size_of_single_real_datatype),cur_l_cols, vav_dev,nbw,&
                           1.0_rk4, umc_dev, cur_l_cols)

         successCUDA = cuda_memcpy(loc(umcCUDA(1)), umc_dev, umc_size*size_of_single_real_datatype, cudaMemcpyDeviceToHost)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif

         ! Transpose umc -> umr (stored in vmr, second half)
#ifdef DOUBLE_PRECISION_REAL
         call elpa_transpose_vectors_real_double  (umcCUDA, cur_l_cols, mpi_comm_cols, &
                                            vmrCUDA(cur_l_rows * n_cols + 1), cur_l_rows, mpi_comm_rows, &
                                            1, istep*nbw, n_cols, nblk)
#else
         call elpa_transpose_vectors_real_single  (umcCUDA, cur_l_cols, mpi_comm_cols, &
                                            vmrCUDA(cur_l_rows * n_cols + 1), cur_l_rows, mpi_comm_rows, &
                                            1, istep*nbw, n_cols, nblk)
#endif

#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(vmr_dev, loc(vmrCUDA(1)), vmr_size*size_of_double_real_datatype, cudaMemcpyHostToDevice)
#else
         successCUDA = cuda_memcpy(vmr_dev, loc(vmrCUDA(1)), vmr_size*size_of_single_real_datatype, cudaMemcpyHostToDevice)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif

#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(umc_dev, loc(umcCUDA(1)), umc_size*size_of_double_real_datatype, cudaMemcpyHostToDevice)
#else
         successCUDA = cuda_memcpy(umc_dev, loc(umcCUDA(1)), umc_size*size_of_single_real_datatype, cudaMemcpyHostToDevice)
#endif
         if (.not.(successCUDA)) then
           print *,"bandred_real: error in cudaMemcpy"
           stop
         endif

         ! A = A - V*U**T - U*V**T
         do i=0,(istep*nbw-1)/tile_size
           lcs = i*l_cols_tile+1
           lce = min(l_cols,(i+1)*l_cols_tile)
           lre = min(l_rows,(i+1)*l_rows_tile)
           if (lce<lcs .or. lre<1) cycle
#ifdef DOUBLE_PRECISION_REAL
           call cublas_dgemm('N', 'T', lre, lce-lcs+1, 2*n_cols, -1.0_rk8, &
                             vmr_dev, cur_l_rows, (umc_dev +(lcs-1)*size_of_double_real_datatype), cur_l_cols, &
                             1.0_rk8, (a_dev+(lcs-1)*lda*size_of_double_real_datatype), lda)
#else
           call cublas_sgemm('N', 'T', lre, lce-lcs+1, 2*n_cols, -1.0_rk4, &
                             vmr_dev, cur_l_rows, (umc_dev +(lcs-1)*size_of_single_real_datatype), cur_l_cols, &
                             1.0_rk4, (a_dev+(lcs-1)*lda*size_of_single_real_datatype), lda)
#endif
         enddo
       else ! do not useGPU
         ! Or if we used the Algorithm 4
         if (tile_size < istep*nbw .or. n_way > 1) then
#ifdef DOUBLE_PRECISION_REAL
           call elpa_reduce_add_vectors_real_double  (vmrCPU(1,n_cols+1),ubound(vmrCPU,dim=1),mpi_comm_rows, &
                                             umcCPU, ubound(umcCPU,dim=1), mpi_comm_cols, &
                                             istep*nbw, n_cols, nblk)
#else
           call elpa_reduce_add_vectors_real_single  (vmrCPU(1,n_cols+1),ubound(vmrCPU,dim=1),mpi_comm_rows, &
                                             umcCPU, ubound(umcCPU,dim=1), mpi_comm_cols, &
                                             istep*nbw, n_cols, nblk)
#endif
         endif

         if (l_cols>0) then
           allocate(tmpCPU(l_cols,n_cols), stat=istat, errmsg=errorMessage)
           if (istat .ne. 0) then
             print *,"bandred_real: error when allocating tmpCPU "//errorMessage
             stop
           endif

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
           call mpi_allreduce(umcCPU, tmpCPU, l_cols*n_cols, MPI_REAL8, MPI_SUM, mpi_comm_rows, mpierr)
#else
           call mpi_allreduce(umcCPU, tmpCPU, l_cols*n_cols, MPI_REAL4, MPI_SUM, mpi_comm_rows, mpierr)
#endif

#else /* WITH_MPI */
           tmpCPU(1:l_cols,1:n_cols) = umcCPU(1:l_cols,1:n_cols)
#endif /* WITH_MPI */
           umcCPU(1:l_cols,1:n_cols) = tmpCPU(1:l_cols,1:n_cols)

           deallocate(tmpCPU, stat=istat, errmsg=errorMessage)
           if (istat .ne. 0) then
             print *,"bandred_real: error when deallocating tmpCPU "//errorMessage
             stop
           endif
         endif

         ! U = U * Tmat**T
#ifdef DOUBLE_PRECISION_REAL
         call dtrmm('Right', 'Upper', 'Trans', 'Nonunit', l_cols,n_cols, 1.0_rk8, tmat(1,1,istep), ubound(tmat,dim=1), &
                    umcCPU, ubound(umcCPU,dim=1))

         ! VAV = Tmat * V**T * A * V * Tmat**T = (U*Tmat**T)**T * V * Tmat**T

         call dgemm('T', 'N', n_cols, n_cols, l_cols, 1.0_rk8, umcCPU, ubound(umcCPU,dim=1), umcCPU(1,n_cols+1), &
                    ubound(umcCPU,dim=1), 0.0_rk8, vav, ubound(vav,dim=1))

         call dtrmm('Right', 'Upper', 'Trans', 'Nonunit', n_cols, n_cols, 1.0_rk8, tmat(1,1,istep),    &
                    ubound(tmat,dim=1), vav, ubound(vav,dim=1))
#else
         call strmm('Right', 'Upper', 'Trans', 'Nonunit', l_cols,n_cols, 1.0_rk4, tmat(1,1,istep), ubound(tmat,dim=1), &
                    umcCPU, ubound(umcCPU,dim=1))

         ! VAV = Tmat * V**T * A * V * Tmat**T = (U*Tmat**T)**T * V * Tmat**T

         call sgemm('T', 'N', n_cols, n_cols, l_cols, 1.0_rk4, umcCPU, ubound(umcCPU,dim=1), umcCPU(1,n_cols+1), &
                    ubound(umcCPU,dim=1), 0.0_rk4, vav, ubound(vav,dim=1))

         call strmm('Right', 'Upper', 'Trans', 'Nonunit', n_cols, n_cols, 1.0_rk4, tmat(1,1,istep),    &
                    ubound(tmat,dim=1), vav, ubound(vav,dim=1))
#endif

#ifdef DOUBLE_PRECISION_REAL
         call symm_matrix_allreduce_double(n_cols,vav, nbw, nbw ,mpi_comm_cols)
#else
         call symm_matrix_allreduce_single(n_cols,vav, nbw, nbw ,mpi_comm_cols)
#endif

         ! U = U - 0.5 * V * VAV
#ifdef DOUBLE_PRECISION_REAL
         call dgemm('N', 'N', l_cols, n_cols, n_cols, -0.5_rk8, umcCPU(1,n_cols+1), ubound(umcCPU,dim=1), vav, &
                     ubound(vav,dim=1), 1.0_rk8, umcCPU, ubound(umcCPU,dim=1))
#else
         call sgemm('N', 'N', l_cols, n_cols, n_cols, -0.5_rk4, umcCPU(1,n_cols+1), ubound(umcCPU,dim=1), vav, &
                     ubound(vav,dim=1), 1.0_rk4, umcCPU, ubound(umcCPU,dim=1))
#endif

         ! Transpose umc -> umr (stored in vmr, second half)
#ifdef DOUBLE_PRECISION_REAL
         call elpa_transpose_vectors_real_double(umcCPU, ubound(umcCPU,dim=1), mpi_comm_cols, &
                                         vmrCPU(1,n_cols+1), ubound(vmrCPU,dim=1), mpi_comm_rows, &
                                         1, istep*nbw, n_cols, nblk)
#else
         call elpa_transpose_vectors_real_single(umcCPU, ubound(umcCPU,dim=1), mpi_comm_cols, &
                                         vmrCPU(1,n_cols+1), ubound(vmrCPU,dim=1), mpi_comm_rows, &
                                         1, istep*nbw, n_cols, nblk)
#endif
         ! A = A - V*U**T - U*V**T
#ifdef WITH_OPENMP
         !$omp parallel private( ii, i, lcs, lce, lre, n_way, m_way, m_id, n_id, work_per_thread, mystart, myend  )
         n_threads = omp_get_num_threads()
         if (mod(n_threads, 2) == 0) then
           n_way = 2
         else
           n_way = 1
         endif

         m_way = n_threads / n_way

         m_id = mod(omp_get_thread_num(),  m_way)
         n_id = omp_get_thread_num() / m_way

         do ii=n_id*tile_size,(istep*nbw-1),tile_size*n_way
           i = ii / tile_size
           lcs = i*l_cols_tile+1
           lce = min(l_cols,(i+1)*l_cols_tile)
           lre = min(l_rows,(i+1)*l_rows_tile)
           if (lce<lcs .or. lre<1) cycle

           !Figure out this thread's range
           work_per_thread = lre / m_way
           if (work_per_thread * m_way < lre) work_per_thread = work_per_thread + 1
           mystart = m_id * work_per_thread + 1
           myend   = mystart + work_per_thread - 1
           if ( myend > lre ) myend = lre
           if ( myend-mystart+1 < 1) cycle
#ifdef DOUBLE_PRECISION_REAL
           call dgemm('N', 'T', myend-mystart+1, lce-lcs+1, 2*n_cols, -1.0_rk8, &
                      vmrCPU(mystart, 1), ubound(vmrCPU,1), umcCPU(lcs,1), ubound(umcCPU,1), &
                       1.0_rk8, a(mystart,lcs), ubound(a,1))
#else
           call sgemm('N', 'T', myend-mystart+1, lce-lcs+1, 2*n_cols, -1.0_rk4, &
                      vmrCPU(mystart, 1), ubound(vmrCPU,1), umcCPU(lcs,1), ubound(umcCPU,1), &
                       1.0_rk4, a(mystart,lcs), ubound(a,1))
#endif
         enddo
         !$omp end parallel
#else /* WITH_OPENMP */
         do i=0,(istep*nbw-1)/tile_size
           lcs = i*l_cols_tile+1
           lce = min(l_cols,(i+1)*l_cols_tile)
           lre = min(l_rows,(i+1)*l_rows_tile)
           if (lce<lcs .or. lre<1) cycle
#ifdef DOUBLE_PRECISION_REAL
           call dgemm('N', 'T', lre,lce-lcs+1, 2*n_cols, -1.0_rk8, &
                       vmrCPU, ubound(vmrCPU,dim=1), umcCPU(lcs,1), ubound(umcCPU,dim=1), &
                       1.0_rk8, a(1,lcs), lda)
#else
           call sgemm('N', 'T', lre,lce-lcs+1, 2*n_cols, -1.0_rk4, &
                       vmrCPU, ubound(vmrCPU,dim=1), umcCPU(lcs,1), ubound(umcCPU,dim=1), &
                       1.0_rk4, a(1,lcs), lda)
#endif

         enddo
#endif /* WITH_OPENMP */

       endif ! useGPU

       if (.not.(useGPU)) then
         if (allocated(vr)) then
           deallocate(vr, stat=istat, errmsg=errorMessage)
           if (istat .ne. 0) then
             print *,"bandred_real: error when deallocating vr "//errorMessage
             stop
           endif
         endif

         if (allocated(umcCPU)) then
           deallocate(umcCPU, stat=istat, errmsg=errorMessage)
           if (istat .ne. 0) then
             print *,"bandred_real: error when deallocating vmrCPU "//errorMessage
             stop
           endif
         endif

         if (allocated(vmrCPU)) then
           deallocate(vmrCPU, stat=istat, errmsg=errorMessage)
           if (istat .ne. 0) then
             print *,"bandred_real: error when deallocating vmrCPU "//errorMessage
             stop
           endif
         endif

       endif !useGPU

     enddo ! istep

     if (useGPU) then
#ifdef DOUBLE_PRECISION_REAL
       successCUDA = cuda_memcpy ( loc (a), a_dev, lda*na_cols*size_of_double_real_datatype,cudaMemcpyDeviceToHost)
#else
       successCUDA = cuda_memcpy ( loc (a), a_dev, lda*na_cols*size_of_single_real_datatype,cudaMemcpyDeviceToHost)
#endif
       if (.not.(successCUDA)) then
         print *,"bandred_real: error in cudaMemcpy"
         stop
       endif

       successCUDA = cuda_free(a_dev)
       if (.not.(successCUDA)) then
         print *,"bandred_real: error in cudaFree"
         stop
       endif

       successCUDA = cuda_free(tmat_dev)
       if (.not.(successCUDA)) then
         print *,"bandred_real: error in cudaFree"
         stop
       endif

       successCUDA = cuda_free(vav_dev)
       if (.not.(successCUDA)) then
         print *,"bandred_real: error in cudaFree"
         stop
       endif
     endif ! useGPU

     if (allocated(vr)) then
       deallocate(vr, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"bandred_real: error when deallocating vr "//errorMessage
         stop
       endif
     endif

     if (allocated(umcCPU)) then
       deallocate(umcCPU, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"bandred_real: error when deallocating umcCPU "//errorMessage
         stop
       endif
     endif

     if (allocated(vmrCPU)) then
       deallocate(vmrCPU, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"bandred_real: error when deallocating vmrCPU "//errorMessage
         stop
       endif
     endif

     if (useGPU) then
       successCUDA = cuda_free(vmr_dev)
       if (.not.(successCUDA)) then
         print *,"bandred_real: error in cudaFree"
         stop
       endif

       successCUDA = cuda_free(umc_dev)
       if (.not.(successCUDA)) then
         print *,"bandred_real: error in cudaFree"
         stop
       endif
       if (allocated(umcCUDA)) then
         deallocate(umcCUDA, stat=istat, errmsg=errorMessage)
         if (istat .ne. 0) then
           print *,"bandred_real: error when deallocating umcCUDA "//errorMessage
           stop
         endif
       endif
       if (allocated(vmrCUDA)) then
         deallocate(vmrCUDA, stat=istat, errmsg=errorMessage)
         if (istat .ne. 0) then
           print *,"bandred_real: error when deallocating vmrCUDA "//errorMessage
           stop
         endif
       endif

     endif ! useGPU

     if (useQR) then
       if (which_qr_decomposition == 1) then
         deallocate(work_blocked, stat=istat, errmsg=errorMessage)
         if (istat .ne. 0) then
           print *,"bandred_real: error when deallocating work_blocked "//errorMessage
           stop
         endif

         deallocate(tauvector, stat=istat, errmsg=errorMessage)
         if (istat .ne. 0) then
           print *,"bandred_real: error when deallocating tauvector "//errorMessage
           stop
         endif
       endif
     endif

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
     call timer%stop("bandred_real_double")
#else
     call timer%stop("bandred_real_single")
#endif
#endif

#ifdef DOUBLE_PRECISION_REAL
   end subroutine bandred_real_double ! slower for gpu on 10000 10000 ???
#else
   end subroutine bandred_real_single ! slower for gpu on 10000 10000 ???
#endif

#ifdef DOUBLE_PRECISION_REAL
    subroutine symm_matrix_allreduce_double(n,a,lda,ldb,comm)
#else
    subroutine symm_matrix_allreduce_single(n,a,lda,ldb,comm)
#endif
    !-------------------------------------------------------------------------------
    !  symm_matrix_allreduce: Does an mpi_allreduce for a symmetric matrix A.
    !  On entry, only the upper half of A needs to be set
    !  On exit, the complete matrix is set
    !-------------------------------------------------------------------------------
#ifdef HAVE_DETAILED_TIMINGS
      use timings
#endif
      use precision
      implicit none
      integer(kind=ik)  :: n, lda, ldb, comm
#ifdef DESPERATELY_WANT_ASSUMED_SIZE
      real(kind=REAL_DATATYPE)     :: a(lda,*)
#else
      real(kind=REAL_DATATYPE)     :: a(lda,ldb)
#endif
      integer(kind=ik)  :: i, nc, mpierr
      real(kind=REAL_DATATYPE)     :: h1(n*n), h2(n*n)

#ifdef HAVE_DETAILED_TIMINGS

#ifdef DOUBLE_PRECISION_REAL
      call timer%start("symm_matrix_allreduce_double")
#else
      call timer%start("symm_matrix_allreduce_single")
#endif

#endif

      nc = 0
      do i=1,n
        h1(nc+1:nc+i) = a(1:i,i)
        nc = nc+i
      enddo

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
      call mpi_allreduce(h1, h2, nc, MPI_REAL8, MPI_SUM, comm, mpierr)
#else
      call mpi_allreduce(h1, h2, nc, MPI_REAL4, MPI_SUM, comm, mpierr)
#endif

#else /* WITH_MPI */
      h2=h1
#endif /* WITH_MPI */
      nc = 0
      do i=1,n
        a(1:i,i) = h2(nc+1:nc+i)
        a(i,1:i-1) = a(1:i-1,i)
        nc = nc+i
      enddo

#ifdef HAVE_DETAILED_TIMINGS

#ifdef DOUBLE_PRECISION_REAL
      call timer%stop("symm_matrix_allreduce_double")
#else
      call timer%stop("symm_matrix_allreduce_single")
#endif

#endif

#ifdef DOUBLE_PRECISION_REAL
    end subroutine symm_matrix_allreduce_double
#else
    end subroutine symm_matrix_allreduce_single
#endif

#ifdef DOUBLE_PRECISION_REAL
    subroutine trans_ev_band_to_full_real_double(na, nqc, nblk, nbw, a, lda, tmat, q, ldq, matrixCols, numBlocks, mpi_comm_rows, &
                                      mpi_comm_cols, useGPU, useQR)
#else
    subroutine trans_ev_band_to_full_real_single(na, nqc, nblk, nbw, a, lda, tmat, q, ldq, matrixCols, numBlocks, mpi_comm_rows, &
                                      mpi_comm_cols, useGPU, useQR)
#endif
    !-------------------------------------------------------------------------------
    !  trans_ev_band_to_full_real:
    !  Transforms the eigenvectors of a band matrix back to the eigenvectors of the original matrix
    !
    !  Parameters
    !
    !  na          Order of matrix a, number of rows of matrix q
    !
    !  nqc         Number of columns of matrix q
    !
    !  nblk        blocksize of cyclic distribution, must be the same in both directions!
    !
    !  nbw         semi bandwith
    !
    !  a(lda,matrixCols)    Matrix containing the Householder vectors (i.e. matrix a after bandred_real)
    !              Distribution is like in Scalapack.
    !
    !  lda         Leading dimension of a
    !  matrixCols  local columns of matrix a and q
    !
    !  tmat(nbw,nbw,numBlocks) Factors returned by bandred_real
    !
    !  q           On input: Eigenvectors of band matrix
    !              On output: Transformed eigenvectors
    !              Distribution is like in Scalapack.
    !
    !  ldq         Leading dimension of q
    !
    !  mpi_comm_rows
    !  mpi_comm_cols
    !              MPI-Communicators for rows/columns
    !
    !-------------------------------------------------------------------------------
#ifdef HAVE_DETAILED_TIMINGS
      use timings
#endif
      use precision
      use cuda_functions
      use iso_c_binding

      implicit none

      integer(kind=ik)            :: na, nqc, lda, ldq, nblk, nbw, matrixCols, numBlocks, mpi_comm_rows, mpi_comm_cols
#ifdef DESPERATELY_WANT_ASSUMED_SIZE
      real(kind=REAL_DATATYPE)               :: a(lda,*), q(ldq,*), tmat(nbw,nbw,*)
#else
      real(kind=REAL_DATATYPE)               :: a(lda,matrixCols), q(ldq,matrixCols), tmat(nbw, nbw, numBlocks)
#endif
      integer(kind=ik)            :: my_prow, my_pcol, np_rows, np_cols, mpierr
      integer(kind=ik)            :: max_blocks_row, max_blocks_col, max_local_rows, &
                                     max_local_cols
      integer(kind=ik)            :: l_cols, l_rows, l_colh, n_cols
      integer(kind=ik)            :: istep, lc, ncol, nrow, nb, ns

      real(kind=REAL_DATATYPE), allocatable  :: tmp1(:), tmp2(:), hvb(:), hvm(:,:)

      integer(kind=C_intptr_T)    :: hvm_dev, q_dev, tmp_dev, tmat_dev

      integer(kind=ik)            :: i

      real(kind=REAL_DATATYPE), allocatable  :: tmat_complete(:,:), t_tmp(:,:), t_tmp2(:,:)
      integer(kind=ik)            :: cwy_blocking, t_blocking, t_cols, t_rows
      logical, intent(in)         :: useQR, useGPU
      integer(kind=ik)            :: istat
      character(200)              :: errorMessage
      logical                     :: successCUDA

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
      call timer%start("trans_ev_band_to_full_real_double")
#else
      call timer%start("trans_ev_band_to_full_real_single")
#endif
#endif
      call mpi_comm_rank(mpi_comm_rows,my_prow,mpierr)
      call mpi_comm_size(mpi_comm_rows,np_rows,mpierr)
      call mpi_comm_rank(mpi_comm_cols,my_pcol,mpierr)
      call mpi_comm_size(mpi_comm_cols,np_cols,mpierr)
      max_blocks_row = ((na -1)/nblk)/np_rows + 1  ! Rows of A
      max_blocks_col = ((nqc-1)/nblk)/np_cols + 1  ! Columns of q!

      max_local_rows = max_blocks_row*nblk
      max_local_cols = max_blocks_col*nblk

      if (useGPU) then
        ! here the GPU and CPU version diverged: the CPU version now always uses the useQR path which
        ! is not implemented in the GPU version
        allocate(tmp1(max_local_cols*nbw), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"trans_ev_band_to_full_real: error when allocating tmp1 "//errorMessage
          stop
        endif

        allocate(tmp2(max_local_cols*nbw), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"trans_ev_band_to_full_real: error when allocating tmp2 "//errorMessage
          stop
        endif

        allocate(hvb(max_local_rows*nbw), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"trans_ev_band_to_full_real: error when allocating hvb "//errorMessage
          stop
        endif

        allocate(hvm(max_local_rows,nbw), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"trans_ev_band_to_full_real: error when allocating hvm "//errorMessage
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(hvm_dev, (max_local_rows)*nbw*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(hvm_dev, (max_local_rows)*nbw*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(tmp_dev, (max_local_cols)*nbw*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(tmp_dev, (max_local_cols)*nbw*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(tmat_dev, nbw*nbw*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(tmat_dev, nbw*nbw*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_malloc(q_dev, ldq*matrixCols*size_of_double_real_datatype)
#else
        successCUDA = cuda_malloc(q_dev, ldq*matrixCols*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaMalloc"
          stop
        endif

  !      q_temp(:,:) = 0.0
  !      q_temp(1:ldq,1:na_cols) = q(1:ldq,1:na_cols)
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_memcpy(q_dev, loc(q), (ldq)*(matrixCols)*size_of_double_real_datatype, cudaMemcpyHostToDevice)
#else
        successCUDA = cuda_memcpy(q_dev, loc(q), (ldq)*(matrixCols)*size_of_single_real_datatype, cudaMemcpyHostToDevice)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        successCUDA = cuda_memset(hvm_dev, 0, (max_local_rows)*(nbw)*size_of_double_real_datatype)
#else
        successCUDA = cuda_memset(hvm_dev, 0, (max_local_rows)*(nbw)*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaMalloc"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
        hvm = 0.0_rk8   ! Must be set to 0 !!!

        hvb = 0.0_rk8   ! Safety only
#else
        hvm = 0.0_rk4   ! Must be set to 0 !!!

        hvb = 0.0_rk4   ! Safety only
#endif
        l_cols = local_index(nqc, my_pcol, np_cols, nblk, -1) ! Local columns of q

        do istep=1,(na-1)/nbw

          n_cols = MIN(na,(istep+1)*nbw) - istep*nbw ! Number of columns in current step

          ! Broadcast all Householder vectors for current step compressed in hvb

          nb = 0
          ns = 0

          do lc = 1, n_cols
            ncol = istep*nbw + lc ! absolute column number of householder vector
            nrow = ncol - nbw ! absolute number of pivot row

            l_rows = local_index(nrow-1, my_prow, np_rows, nblk, -1) ! row length for bcast
            l_colh = local_index(ncol  , my_pcol, np_cols, nblk, -1) ! HV local column number

            if (my_pcol==pcol(ncol, nblk, np_cols)) hvb(nb+1:nb+l_rows) = a(1:l_rows,l_colh)

            nb = nb+l_rows

            if (lc==n_cols .or. mod(ncol,nblk)==0) then
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
              call MPI_Bcast(hvb(ns+1), nb-ns, MPI_REAL8, pcol(ncol, nblk, np_cols), mpi_comm_cols, mpierr)
#else
              call MPI_Bcast(hvb(ns+1), nb-ns, MPI_REAL4, pcol(ncol, nblk, np_cols), mpi_comm_cols, mpierr)
#endif

#endif /* WITH_MPI */
              ns = nb
            endif
          enddo

          ! Expand compressed Householder vectors into matrix hvm

          nb = 0
          do lc = 1, n_cols
            nrow = (istep-1)*nbw+lc ! absolute number of pivot row
            l_rows = local_index(nrow-1, my_prow, np_rows, nblk, -1) ! row length for bcast

            hvm(1:l_rows,lc) = hvb(nb+1:nb+l_rows)
#ifdef DOUBLE_PRECISION_REAL
            if (my_prow==prow(nrow, nblk, np_rows)) hvm(l_rows+1,lc) = 1._rk8
#else
            if (my_prow==prow(nrow, nblk, np_rows)) hvm(l_rows+1,lc) = 1._rk4
#endif

            nb = nb+l_rows
          enddo
#ifdef DOUBLE_PRECISION_REAL
          successCUDA = cuda_memcpy(hvm_dev, loc(hvm), ((max_local_rows)*nbw*size_of_double_real_datatype),cudaMemcpyHostToDevice)
#else
          successCUDA = cuda_memcpy(hvm_dev, loc(hvm), ((max_local_rows)*nbw*size_of_single_real_datatype),cudaMemcpyHostToDevice)
#endif

          if (.not.(successCUDA)) then
            print *,"trans_ev_band_to_full_real: error in cudaMemcpy"
            stop

          endif

          l_rows = local_index(MIN(na,(istep+1)*nbw), my_prow, np_rows, nblk, -1)

          ! Q = Q - V * T**T * V**T * Q

          if (l_rows>0) then
#ifdef DOUBLE_PRECISION_REAL
            call cublas_dgemm('T', 'N', n_cols, l_cols, l_rows, 1.0_rk8, hvm_dev, max_local_rows, &
                              q_dev, ldq , 0.0_rk8, tmp_dev, n_cols)
#else
            call cublas_sgemm('T', 'N', n_cols, l_cols, l_rows, 1.0_rk4, hvm_dev, max_local_rows, &
                              q_dev, ldq , 0.0_rk4, tmp_dev, n_cols)
#endif

#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_memcpy(loc(tmp1), tmp_dev, l_cols*n_cols*size_of_double_real_datatype, cudaMemcpyDeviceToHost)
#else
            successCUDA = cuda_memcpy(loc(tmp1), tmp_dev, l_cols*n_cols*size_of_single_real_datatype, cudaMemcpyDeviceToHost)
#endif
            if (.not.(successCUDA)) then
              print *,"trans_ev_band_to_full_real: error in cudaMemcpy"
              stop
            endif

          else
            !#ifdef WITH_GPU_VERSION
            !         istat = cuda_memset(tmp_dev, 0, l_cols*n_cols*size_of_real_datatype)
            !         if (istat .ne. 0) then
            !           print *,"trans_ev_band_to_full_real: error in cudaMemset"
            !           stop
            !         endif
            !
            !#else
            tmp1(1:l_cols*n_cols) = 0
            !#endif
          endif

          !#ifdef WITH_GPU_VERSION
          !       istat = cuda_memcpy(loc(tmp1), tmp_dev, max_local_cols*nbw*size_of_real_datatype,cudaMemcpyDeviceToHost)
          !       if (istat .ne. 0) then
          !         print *,"error in cudaMemcpy"
          !         stop
          !       endif
          !#endif
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
          call mpi_allreduce(tmp1, tmp2, n_cols*l_cols, MPI_REAL8, MPI_SUM, mpi_comm_rows, mpierr)
#else
          call mpi_allreduce(tmp1, tmp2, n_cols*l_cols, MPI_REAL4, MPI_SUM, mpi_comm_rows, mpierr)
#endif

#else /* WITH_MPI */
          tmp2(1:n_cols*l_cols) = tmp1(n_cols*l_cols)
#endif /* WITH_MPI */
          !#ifdef WITH_GPU_VERSION
          !       istat = cuda_memcpy(tmp_dev, loc(tmp2), max_local_cols*nbw*size_of_real_datatype,cudaMemcpyHostToDevice)
          !       if (istat .ne. 0) then
          !         print *,"error in cudaMemcpy"
          !         stop
          !       endif
          !#endif

          if (l_rows>0) then
#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_memcpy(tmp_dev, loc(tmp2), n_cols*l_cols*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
            successCUDA = cuda_memcpy(tmp_dev, loc(tmp2), n_cols*l_cols*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
            if (.not.(successCUDA)) then
              print *,"trans_ev_band_to_full_real: error in cudaMemcpy"
              stop
            endif
#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_memcpy(tmat_dev, loc(tmat(1,1,istep)), nbw*nbw*size_of_double_real_datatype,cudaMemcpyHostToDevice)
#else
            successCUDA = cuda_memcpy(tmat_dev, loc(tmat(1,1,istep)), nbw*nbw*size_of_single_real_datatype,cudaMemcpyHostToDevice)
#endif
            if (.not.(successCUDA)) then
              print *,"trans_ev_band_to_full_real: error in cudaMemcpy"
              stop
            endif
#ifdef DOUBLE_PRECISION_REAL
            call cublas_dtrmm('L', 'U', 'T', 'N', n_cols, l_cols, 1.0_rk8, tmat_dev, nbw, tmp_dev, n_cols)
            call cublas_dgemm('N', 'N', l_rows, l_cols, n_cols, -1.0_rk8, hvm_dev, max_local_rows, &
                              tmp_dev, n_cols, 1.0_rk8, q_dev, ldq)
#else
            call cublas_strmm('L', 'U', 'T', 'N', n_cols, l_cols, 1.0_rk4, tmat_dev, nbw, tmp_dev, n_cols)
            call cublas_sgemm('N', 'N', l_rows, l_cols, n_cols, -1.0_rk4, hvm_dev, max_local_rows, &
                              tmp_dev, n_cols, 1.0_rk4, q_dev, ldq)
#endif

#ifdef DOUBLE_PRECISION_REAL
            successCUDA = cuda_memcpy(loc(hvm), hvm_dev, ((max_local_rows)*nbw*size_of_double_real_datatype),cudaMemcpyDeviceToHost)
#else
            successCUDA = cuda_memcpy(loc(hvm), hvm_dev, ((max_local_rows)*nbw*size_of_single_real_datatype),cudaMemcpyDeviceToHost)
#endif
            if (.not.(successCUDA)) then
              print *,"trans_ev_band_to_full_real: error in cudaMemcpy"
              stop
            endif

          endif ! l_rows > 0
          !#ifdef WITH_GPU_VERSION
          !       istat = cuda_memcpy(loc(hvm), hvm_dev, ((max_local_rows)*nbw*size_of_real_datatype),cudaMemcpyDeviceToHost)
          !       if (istat .ne. 0) then
          !         print *,"error in cudaMemcpy"
          !         stop
          !       endif
          !
          !#endif
        enddo ! istep

      else ! do not useGPU

        ! t_blocking was formerly 2; 3 is a better choice
        t_blocking = 3 ! number of matrices T (tmat) which are aggregated into a new (larger) T matrix (tmat_complete) and applied at once

        ! we only use the t_blocking if we could call it fully, this is might be better but needs to benchmarked.
!       if ( na >= ((t_blocking+1)*nbw) ) then
        cwy_blocking = t_blocking * nbw

        allocate(tmp1(max_local_cols*cwy_blocking))
        allocate(tmp2(max_local_cols*cwy_blocking))
        allocate(hvb(max_local_rows*cwy_blocking))
        allocate(hvm(max_local_rows,cwy_blocking))
        allocate(tmat_complete(cwy_blocking,cwy_blocking))
        allocate(t_tmp(cwy_blocking,nbw))
        allocate(t_tmp2(cwy_blocking,nbw))
!        else
!          allocate(tmp1(max_local_cols*nbw))
!          allocate(tmp2(max_local_cols*nbw))
!          allocate(hvb(max_local_rows*nbw))
!          allocate(hvm(max_local_rows,nbw))
!        endif
#ifdef DOUBLE_PRECISION_REAL
        hvm = 0._rk8   ! Must be set to 0 !!!
        hvb = 0._rk8   ! Safety only
#else
        hvm = 0._rk4   ! Must be set to 0 !!!
        hvb = 0._rk4   ! Safety only
#endif
        l_cols = local_index(nqc, my_pcol, np_cols, nblk, -1) ! Local columns of q

!       if ( na >= ((t_blocking+1)*nbw) ) then

        do istep=1,((na-1)/nbw-1)/t_blocking + 1
          ! This the call when using  na >= ((t_blocking+1)*nbw)
          !      n_cols = MIN(na,istep*cwy_blocking+nbw) - (istep-1)*cwy_blocking - nbw ! Number of columns in current step
          ! As an alternative we add some special case handling if na < cwy_blocking
          IF (na < cwy_blocking) THEN
            n_cols = MAX(0, na-nbw)
            IF ( n_cols .eq. 0 ) THEN
              EXIT
            END IF
          ELSE
            n_cols = MIN(na,istep*cwy_blocking+nbw) - (istep-1)*cwy_blocking - nbw ! Number of columns in current step
          END IF
          ! Broadcast all Householder vectors for current step compressed in hvb

          nb = 0
          ns = 0

          do lc = 1, n_cols
            ncol = (istep-1)*cwy_blocking + nbw + lc ! absolute column number of householder vector
            nrow = ncol - nbw ! absolute number of pivot row

            l_rows = local_index(nrow-1, my_prow, np_rows, nblk, -1) ! row length for bcast
            l_colh = local_index(ncol  , my_pcol, np_cols, nblk, -1) ! HV local column number

            if (my_pcol==pcol(ncol, nblk, np_cols)) hvb(nb+1:nb+l_rows) = a(1:l_rows,l_colh)

            nb = nb+l_rows

            if (lc==n_cols .or. mod(ncol,nblk)==0) then
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
              call MPI_Bcast(hvb(ns+1), nb-ns, MPI_REAL8, pcol(ncol, nblk, np_cols), mpi_comm_cols, mpierr)
#else
              call MPI_Bcast(hvb(ns+1), nb-ns, MPI_REAL4, pcol(ncol, nblk, np_cols), mpi_comm_cols, mpierr)
#endif

#endif /* WITH_MPI */
              ns = nb
            endif
          enddo

          ! Expand compressed Householder vectors into matrix hvm

          nb = 0
          do lc = 1, n_cols
            nrow = (istep-1)*cwy_blocking + lc ! absolute number of pivot row
            l_rows = local_index(nrow-1, my_prow, np_rows, nblk, -1) ! row length for bcast

            hvm(1:l_rows,lc) = hvb(nb+1:nb+l_rows)
#ifdef DOUBLE_PRECISION_REAL
            if (my_prow==prow(nrow, nblk, np_rows)) hvm(l_rows+1,lc) = 1._rk8
#else
            if (my_prow==prow(nrow, nblk, np_rows)) hvm(l_rows+1,lc) = 1._rk4
#endif

            nb = nb+l_rows
          enddo

          l_rows = local_index(MIN(na,(istep+1)*cwy_blocking), my_prow, np_rows, nblk, -1)

          ! compute tmat2 out of tmat(:,:,)
          tmat_complete = 0
          do i = 1, t_blocking
            t_cols = MIN(nbw, n_cols - (i-1)*nbw)
            if (t_cols <= 0) exit
            t_rows = (i - 1) * nbw
            tmat_complete(t_rows+1:t_rows+t_cols,t_rows+1:t_rows+t_cols) = tmat(1:t_cols,1:t_cols,(istep-1)*t_blocking + i)
            if (i > 1) then
#ifdef DOUBLE_PRECISION_REAL
              call dgemm('T', 'N', t_rows, t_cols, l_rows, 1.0_rk8, hvm(1,1), max_local_rows, hvm(1,(i-1)*nbw+1), &
                        max_local_rows, 0.0_rk8, t_tmp, cwy_blocking)
#ifdef WITH_MPI
              call mpi_allreduce(t_tmp, t_tmp2, cwy_blocking*nbw, MPI_REAL8, MPI_SUM, mpi_comm_rows, mpierr)
#else
              t_tmp2(1:cwy_blocking,1:nbw) = t_tmp(1:cwy_blocking,1:nbw)
#endif
              call dtrmm('L', 'U', 'N', 'N', t_rows, t_cols, 1.0_rk8, tmat_complete, cwy_blocking, t_tmp2, cwy_blocking)
              call dtrmm('R', 'U', 'N', 'N', t_rows, t_cols, -1.0_rk8, tmat_complete(t_rows+1,t_rows+1), cwy_blocking, &
                         t_tmp2, cwy_blocking)
#else /* DOUBLE_PRECISION_REAL */
              call sgemm('T', 'N', t_rows, t_cols, l_rows, 1.0_rk4, hvm(1,1), max_local_rows, hvm(1,(i-1)*nbw+1), &
                        max_local_rows, 0.0_rk4, t_tmp, cwy_blocking)
#ifdef WITH_MPI
              call mpi_allreduce(t_tmp, t_tmp2, cwy_blocking*nbw, MPI_REAL4, MPI_SUM, mpi_comm_rows, mpierr)
#else
              t_tmp2(1:cwy_blocking,1:nbw) = t_tmp(1:cwy_blocking,1:nbw)
#endif
              call strmm('L', 'U', 'N', 'N', t_rows, t_cols, 1.0_rk4, tmat_complete, cwy_blocking, t_tmp2, cwy_blocking)
              call strmm('R', 'U', 'N', 'N', t_rows, t_cols, -1.0_rk4, tmat_complete(t_rows+1,t_rows+1), &
                          cwy_blocking, t_tmp2, cwy_blocking)
#endif /* DOUBLE_PRECISION_REAL */

              tmat_complete(1:t_rows,t_rows+1:t_rows+t_cols) = t_tmp2(1:t_rows,1:t_cols)
             endif
          enddo

          ! Q = Q - V * T**T * V**T * Q

          if (l_rows>0) then
#ifdef DOUBLE_PRECISION_REAL
            call dgemm('T', 'N', n_cols, l_cols, l_rows, 1.0_rk8, hvm, ubound(hvm,dim=1), &
                       q, ldq, 0.0_rk8, tmp1, n_cols)
#else
            call sgemm('T', 'N', n_cols, l_cols, l_rows, 1.0_rk4, hvm, ubound(hvm,dim=1), &
                       q, ldq, 0.0_rk4, tmp1, n_cols)
#endif

          else
#ifdef DOUBLE_PRECISION_REAL
            tmp1(1:l_cols*n_cols) = 0._rk8
#else
            tmp1(1:l_cols*n_cols) = 0._rk4
#endif
          endif
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
          call mpi_allreduce(tmp1, tmp2, n_cols*l_cols, MPI_REAL8, MPI_SUM, mpi_comm_rows ,mpierr)
#else
          call mpi_allreduce(tmp1, tmp2, n_cols*l_cols, MPI_REAL4, MPI_SUM, mpi_comm_rows ,mpierr)
#endif

#else /* WITH_MPI */
          tmp2 = tmp1

#endif /* WITH_MPI */

          if (l_rows>0) then
#ifdef DOUBLE_PRECISION_REAL
            call dtrmm('L', 'U', 'T', 'N', n_cols, l_cols, 1.0_rk8, tmat_complete, cwy_blocking, tmp2, n_cols)
            call dgemm('N', 'N', l_rows, l_cols, n_cols, -1.0_rk8, hvm, ubound(hvm,dim=1), tmp2, n_cols, 1.0_rk8, q, ldq)
#else
            call strmm('L', 'U', 'T', 'N', n_cols, l_cols, 1.0_rk4, tmat_complete, cwy_blocking, tmp2, n_cols)
            call sgemm('N', 'N', l_rows, l_cols, n_cols, -1.0_rk4, hvm, ubound(hvm,dim=1), tmp2, n_cols, 1.0_rk4, q, ldq)
#endif

          endif
        enddo ! istep

      endif ! useGPU

      deallocate(tmp1, tmp2, hvb, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"trans_ev_band_to_full_real: error when deallocating tmp1 tmp2 hvb "//errorMessage
        stop
      endif

      if (useGPU) then
        successCUDA = cuda_free(hvm_dev)
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaFree"
          stop
        endif

        successCUDA = cuda_free(tmp_dev)
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaFree"
          stop
        endif

        successCUDA = cuda_free(tmat_dev)
        if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaFree"
          stop
        endif
#ifdef DOUBLE_PRECISION_REAL
         successCUDA = cuda_memcpy(loc(q), q_dev, ldq*matrixCols*size_of_double_real_datatype, cudaMemcpyDeviceToHost)
#else
         successCUDA = cuda_memcpy(loc(q), q_dev, ldq*matrixCols*size_of_single_real_datatype, cudaMemcpyDeviceToHost)
#endif
         if (.not.(successCUDA)) then
          print *,"trans_ev_band_to_full_real: error in cudaFree"
          stop
         endif

         !   q(1:ldq,1:na_cols) = q_temp(1:ldq,1:na_cols)

         successCUDA = cuda_free(q_dev)
         if (.not.(successCUDA)) then
           print *,"trans_ev_band_to_full_real: error in cudaFree"
           stop
         endif

         !   deallocate(q_temp, stat=istat, errmsg=errorMessage)
         !   if (istat .ne. 0) then
         !     print *,"error when deallocating q_temp "//errorMessage
         !     stop
         !   endif
         !   deallocate(tmat_temp, stat=istat, errmsg=errorMessage)
         !   if (istat .ne. 0) then
         !     print *,"trans_ev_band_to_full_real: error when deallocating tmat_temp "//errorMessage
         !     stop
         !   endif

      endif ! useGPU

      deallocate(hvm, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"trans_ev_band_to_full_real: error when deallocating hvm "//errorMessage
        stop
      endif

      if (useQr) then
        deallocate(tmat_complete, t_tmp, t_tmp2, stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"trans_ev_band_to_full_real: error when deallocating tmat_complete, t_tmp, t_tmp2 "//errorMessage
          stop
        endif

      endif

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
      call timer%stop("trans_ev_band_to_full_real_double")
#else
      call timer%stop("trans_ev_band_to_full_real_single")
#endif
#endif

#ifdef DOUBLE_PRECISION_REAL
    end subroutine trans_ev_band_to_full_real_double
#else
    end subroutine trans_ev_band_to_full_real_single
#endif

#ifdef DOUBLE_PRECISION_REAL
    subroutine tridiag_band_real_double(na, nb, nblk, a, lda, d, e, matrixCols, hh_trans_real, &
                                 mpi_comm_rows, mpi_comm_cols, mpi_comm)
#else
    subroutine tridiag_band_real_single(na, nb, nblk, a, lda, d, e, matrixCols, hh_trans_real, &
                                 mpi_comm_rows, mpi_comm_cols, mpi_comm)
#endif
    !-------------------------------------------------------------------------------
    ! tridiag_band_real:
    ! Reduces a real symmetric band matrix to tridiagonal form
    !
    !  na          Order of matrix a
    !
    !  nb          Semi bandwith
    !
    !  nblk        blocksize of cyclic distribution, must be the same in both directions!
    !
    !  a(lda,matrixCols)    Distributed system matrix reduced to banded form in the upper diagonal
    !
    !  lda         Leading dimension of a
    !  matrixCols  local columns of matrix a
    !
    !  d(na)       Diagonal of tridiagonal matrix, set only on PE 0 (output)
    !
    !  e(na)       Subdiagonal of tridiagonal matrix, set only on PE 0 (output)
    !
    !  mpi_comm_rows
    !  mpi_comm_cols
    !              MPI-Communicators for rows/columns
    !  mpi_comm
    !              MPI-Communicator for the total processor set
    !-------------------------------------------------------------------------------
#ifdef HAVE_DETAILED_TIMINGS
      use timings
#endif
      use precision
      implicit none

      integer(kind=ik), intent(in)  ::  na, nb, nblk, lda, matrixCols, mpi_comm_rows, mpi_comm_cols, mpi_comm
#ifdef DESPERATELY_WANT_ASSUMED_SIZE
      real(kind=REAL_DATATYPE), intent(in)     :: a(lda,*)
#else
      real(kind=REAL_DATATYPE), intent(in)     :: a(lda,matrixCols)
#endif
      real(kind=REAL_DATATYPE), intent(out)    :: d(na), e(na) ! set only on PE 0
      real(kind=REAL_DATATYPE), intent(out), &
          allocatable               :: hh_trans_real(:,:)

      real(kind=REAL_DATATYPE)                 :: vnorm2, hv(nb), tau, x, h(nb), ab_s(1+nb), hv_s(nb), hv_new(nb), tau_new, hf
      real(kind=REAL_DATATYPE)                 :: hd(nb), hs(nb)

      integer(kind=ik)              :: i, j, n, nc, nr, ns, ne, istep, iblk, nblocks_total, nblocks, nt
      integer(kind=ik)              :: my_pe, n_pes, mpierr
      integer(kind=ik)              :: my_prow, np_rows, my_pcol, np_cols
      integer(kind=ik)              :: ireq_ab, ireq_hv
      integer(kind=ik)              :: na_s, nx, num_hh_vecs, num_chunks, local_size, max_blk_size, n_off
#ifdef WITH_OPENMP
      integer(kind=ik)              :: max_threads, my_thread, my_block_s, my_block_e, iter
#ifdef WITH_MPI
      integer(kind=ik)              :: mpi_status(MPI_STATUS_SIZE)
#endif
      integer(kind=ik), allocatable :: mpi_statuses(:,:), global_id_tmp(:,:)
      integer(kind=ik), allocatable :: omp_block_limits(:)
      real(kind=REAL_DATATYPE), allocatable    :: hv_t(:,:), tau_t(:)
#endif
      integer(kind=ik), allocatable :: ireq_hhr(:), ireq_hhs(:), global_id(:,:), hh_cnt(:), hh_dst(:)
      integer(kind=ik), allocatable :: limits(:), snd_limits(:,:)
      integer(kind=ik), allocatable :: block_limits(:)
      real(kind=REAL_DATATYPE), allocatable    :: ab(:,:), hh_gath(:,:,:), hh_send(:,:,:)

#ifdef WITH_OPENMP
      integer(kind=ik)              :: omp_get_max_threads
#endif
      integer                       :: istat
      character(200)                :: errorMessage

#ifndef WITH_MPI
      integer(kind=ik)              :: startAddr
#endif

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
      call timer%start("tridiag_band_real_double")
#else
      call timer%start("tridiag_band_real_single")
#endif
#endif
      call mpi_comm_rank(mpi_comm,my_pe,mpierr)
      call mpi_comm_size(mpi_comm,n_pes,mpierr)

      call mpi_comm_rank(mpi_comm_rows,my_prow,mpierr)
      call mpi_comm_size(mpi_comm_rows,np_rows,mpierr)
      call mpi_comm_rank(mpi_comm_cols,my_pcol,mpierr)
      call mpi_comm_size(mpi_comm_cols,np_cols,mpierr)
      ! Get global_id mapping 2D procssor coordinates to global id

      allocate(global_id(0:np_rows-1,0:np_cols-1), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating global_id "//errorMessage
        stop
      endif


      global_id(:,:) = 0
      global_id(my_prow, my_pcol) = my_pe
#ifdef WITH_OPENMP
      allocate(global_id_tmp(0:np_rows-1,0:np_cols-1), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating global_id_tmp "//errorMessage
        stop
      endif
#endif

#ifdef WITH_MPI

#ifndef WITH_OPENMP
      call mpi_allreduce(mpi_in_place, global_id, np_rows*np_cols, mpi_integer, mpi_sum, mpi_comm, mpierr)
#else
      global_id_tmp(:,:) = global_id(:,:)
      call mpi_allreduce(global_id_tmp, global_id, np_rows*np_cols, mpi_integer, mpi_sum, mpi_comm, mpierr)
      deallocate(global_id_tmp, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when deallocating global_id_tmp "//errorMessage
        stop
      endif
#endif /* WITH_OPENMP */

#endif /* WITH_MPI */
      ! Total number of blocks in the band:

      nblocks_total = (na-1)/nb + 1

      ! Set work distribution

      allocate(block_limits(0:n_pes), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating block_limits"//errorMessage
        stop
      endif

      call divide_band(nblocks_total, n_pes, block_limits)

      ! nblocks: the number of blocks for my task
      nblocks = block_limits(my_pe+1) - block_limits(my_pe)

      ! allocate the part of the band matrix which is needed by this PE
      ! The size is 1 block larger than needed to avoid extensive shifts
      allocate(ab(2*nb,(nblocks+1)*nb), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating ab"//errorMessage
        stop
      endif

      ab = 0 ! needed for lower half, the extra block should also be set to 0 for safety

      ! n_off: Offset of ab within band
      n_off = block_limits(my_pe)*nb

      ! Redistribute band in a to ab
#ifdef DOUBLE_PRECISION_REAL
      call redist_band_real_double(a, lda, na, nblk, nb, matrixCols, mpi_comm_rows, mpi_comm_cols, mpi_comm, ab)
#else
      call redist_band_real_single(a, lda, na, nblk, nb, matrixCols, mpi_comm_rows, mpi_comm_cols, mpi_comm, ab)
#endif
      ! Calculate the workload for each sweep in the back transformation
      ! and the space requirements to hold the HH vectors

      allocate(limits(0:np_rows), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating limits"//errorMessage
        stop
      endif

      call determine_workload(na, nb, np_rows, limits)
      max_blk_size = maxval(limits(1:np_rows) - limits(0:np_rows-1))

      num_hh_vecs = 0
      num_chunks  = 0
      nx = na
      do n = 1, nblocks_total
        call determine_workload(nx, nb, np_rows, limits)
        local_size = limits(my_prow+1) - limits(my_prow)
        ! add to number of householder vectors
        ! please note: for nx==1 the one and only HH vector is 0 and is neither calculated nor send below!
        if (mod(n-1,np_cols) == my_pcol .and. local_size>0 .and. nx>1) then
          num_hh_vecs = num_hh_vecs + local_size
          num_chunks  = num_chunks+1
        endif
        nx = nx - nb
      enddo

      ! Allocate space for HH vectors

      allocate(hh_trans_real(nb,num_hh_vecs), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating hh_trans_real"//errorMessage
        stop
      endif


      ! Allocate and init MPI requests

      allocate(ireq_hhr(num_chunks), stat=istat, errmsg=errorMessage) ! Recv requests
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating ireq_hhr"//errorMessage
        stop
      endif
      allocate(ireq_hhs(nblocks), stat=istat, errmsg=errorMessage)    ! Send requests
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating ireq_hhs"//errorMessage
        stop
      endif

      num_hh_vecs = 0
      num_chunks  = 0
      nx = na
      nt = 0
      do n = 1, nblocks_total
        call determine_workload(nx, nb, np_rows, limits)
        local_size = limits(my_prow+1) - limits(my_prow)
        if (mod(n-1,np_cols) == my_pcol .and. local_size>0 .and. nx>1) then
          num_chunks  = num_chunks+1
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
          call mpi_irecv(hh_trans_real(1,num_hh_vecs+1), nb*local_size, mpi_real8, nt, &
                           10+n-block_limits(nt), mpi_comm, ireq_hhr(num_chunks), mpierr)
#else
          call mpi_irecv(hh_trans_real(1,num_hh_vecs+1), nb*local_size, mpi_real4, nt, &
                           10+n-block_limits(nt), mpi_comm, ireq_hhr(num_chunks), mpierr)
#endif

#else /* WITH_MPI */
          ! carefull non-block recv data copy must be done at wait or send
          ! hh_trans_real(1:nb*local_size,num_hh_vecs+1) = hh_send(1:nb*hh_cnt(iblk),1,iblk)
#endif /* WITH_MPI */
          num_hh_vecs = num_hh_vecs + local_size
        endif
        nx = nx - nb
        if (n == block_limits(nt+1)) then
          nt = nt + 1
        endif
      enddo
#ifdef WITH_MPI
      ireq_hhs(:) = MPI_REQUEST_NULL
#endif
      ! Buffers for gathering/sending the HH vectors

      allocate(hh_gath(nb,max_blk_size,nblocks), stat=istat, errmsg=errorMessage) ! gathers HH vectors
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating hh_gath"//errorMessage
        stop
      endif

      allocate(hh_send(nb,max_blk_size,nblocks), stat=istat, errmsg=errorMessage) ! send buffer for HH vectors
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating hh_send"//errorMessage
        stop
      endif
#ifdef DOUBLE_PRECISION_REAL
      hh_gath(:,:,:) = 0._rk8
      hh_send(:,:,:) = 0._rk8
#else
      hh_gath(:,:,:) = 0._rk4
      hh_send(:,:,:) = 0._rk4
#endif

      ! Some counters

      allocate(hh_cnt(nblocks), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating hh_cnt"//errorMessage
        stop
      endif

      allocate(hh_dst(nblocks), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating hh_dst"//errorMessage
        stop
      endif

      hh_cnt(:) = 1 ! The first transfomation vector is always 0 and not calculated at all
      hh_dst(:) = 0 ! PE number for receive
#ifdef WITH_MPI
      ireq_ab = MPI_REQUEST_NULL
      ireq_hv = MPI_REQUEST_NULL
#endif
      ! Limits for sending

      allocate(snd_limits(0:np_rows,nblocks), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating snd_limits"//errorMessage
        stop
      endif
      do iblk=1,nblocks
        call determine_workload(na-(iblk+block_limits(my_pe)-1)*nb, nb, np_rows, snd_limits(:,iblk))
      enddo

#ifdef WITH_OPENMP
      ! OpenMP work distribution:

      max_threads = 1
      max_threads = omp_get_max_threads()
      ! For OpenMP we need at least 2 blocks for every thread
      max_threads = MIN(max_threads, nblocks/2)
      if (max_threads==0) max_threads = 1

      allocate(omp_block_limits(0:max_threads), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating omp_block_limits"//errorMessage
        stop
      endif

      ! Get the OpenMP block limits
      call divide_band(nblocks, max_threads, omp_block_limits)

      allocate(hv_t(nb,max_threads), tau_t(max_threads), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating hv_t, tau_t"//errorMessage
        stop
      endif

      hv_t = 0
      tau_t = 0
#endif /* WITH_OPENMP */
      ! ---------------------------------------------------------------------------
      ! Start of calculations

      na_s = block_limits(my_pe)*nb + 1

      if (my_pe>0 .and. na_s<=na) then
        ! send first column to previous PE
        ! Only the PE owning the diagonal does that (sending 1 element of the subdiagonal block also)
        ab_s(1:nb+1) = ab(1:nb+1,na_s-n_off)
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
        call mpi_isend(ab_s, nb+1, mpi_real8, my_pe-1, 1, mpi_comm, ireq_ab, mpierr)
#else
        call mpi_isend(ab_s, nb+1, mpi_real4, my_pe-1, 1, mpi_comm, ireq_ab, mpierr)
#endif

#endif /* WITH_MPI */
      endif


#ifndef WITH_MPI
          startAddr   = ubound(hh_trans_real,dim=2)
#endif

#ifdef WITH_OPENMP
      do istep=1,na-1-block_limits(my_pe)*nb
#else
      do istep=1,na-1
#endif

        if (my_pe==0) then
          n = MIN(na-na_s,nb) ! number of rows to be reduced
#ifdef DOUBLE_PRECISION_REAL
          hv(:) = 0._rk8
          tau = 0._rk8
#else
          hv(:) = 0._rk4
          tau = 0._rk4
#endif
          ! The last step (istep=na-1) is only needed for sending the last HH vectors.
          ! We don't want the sign of the last element flipped (analogous to the other sweeps)
          if (istep < na-1) then
            ! Transform first column of remaining matrix
            vnorm2 = sum(ab(3:n+1,na_s-n_off)**2)
#ifdef DOUBLE_PRECISION_REAL
            call hh_transform_real_double(ab(2,na_s-n_off),vnorm2,hf,tau)
	    hv(1) = 1._rk8
#else
            call hh_transform_real_single(ab(2,na_s-n_off),vnorm2,hf,tau)
	    hv(1) = 1._rk4
#endif
            hv(2:n) = ab(3:n+1,na_s-n_off)*hf
          endif
          d(istep) = ab(1,na_s-n_off)
          e(istep) = ab(2,na_s-n_off)
          if (istep == na-1) then
            d(na) = ab(1,na_s+1-n_off)
#ifdef DOUBLE_PRECISION_REAL
            e(na) = 0._rk8
#else
            e(na) = 0._rk4
#endif
          endif
        else
          if (na>na_s) then
            ! Receive Householder vector from previous task, from PE owning subdiagonal

#ifdef WITH_OPENMP

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
            call mpi_recv(hv, nb, mpi_real8, my_pe-1, 2, mpi_comm, MPI_STATUS, mpierr)
#else
            call mpi_recv(hv, nb, mpi_real4, my_pe-1, 2, mpi_comm, MPI_STATUS, mpierr)
#endif

#else /* WITH_MPI */

            hv(1:nb) = hv_s(1:nb)

#endif /* WITH_MPI */

#else /* WITH_OPENMP */

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
            call mpi_recv(hv, nb, mpi_real8, my_pe-1, 2, mpi_comm, MPI_STATUS_IGNORE, mpierr)
#else
            call mpi_recv(hv, nb, mpi_real4, my_pe-1, 2, mpi_comm, MPI_STATUS_IGNORE, mpierr)
#endif

#else /* WITH_MPI */
            hv(1:nb) = hv_s(1:nb)
#endif /* WITH_MPI */

#endif /* WITH_OPENMP */
            tau = hv(1)
#ifdef DOUBLE_PRECISION_REAL
            hv(1) = 1._rk8
#else
            hv(1) = 1._rk4
#endif
          endif
        endif

        na_s = na_s+1
        if (na_s-n_off > nb) then
          ab(:,1:nblocks*nb) = ab(:,nb+1:(nblocks+1)*nb)
#ifdef DOUBLE_PRECISION_REAL
          ab(:,nblocks*nb+1:(nblocks+1)*nb) = 0._rk8
#else
          ab(:,nblocks*nb+1:(nblocks+1)*nb) = 0._rk4
#endif
          n_off = n_off + nb
        endif

#ifdef WITH_OPENMP
        if (max_threads > 1) then

          ! Codepath for OpenMP

          ! Please note that in this case it is absolutely necessary to have at least 2 blocks per thread!
          ! Every thread is one reduction cycle behind its predecessor and thus starts one step later.
          ! This simulates the behaviour of the MPI tasks which also work after each other.
          ! The code would be considerably easier, if the MPI communication would be made within
          ! the parallel region - this is avoided here since this would require
          ! MPI_Init_thread(MPI_THREAD_MULTIPLE) at the start of the program.

          hv_t(:,1) = hv
          tau_t(1) = tau

          do iter = 1, 2

            ! iter=1 : work on first block
            ! iter=2 : work on remaining blocks
            ! This is done in 2 iterations so that we have a barrier in between:
            ! After the first iteration, it is guaranteed that the last row of the last block
            ! is completed by the next thread.
            ! After the first iteration it is also the place to exchange the last row
            ! with MPI calls
#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
            call timer%start("OpenMP parallel_double")
#else
            call timer%start("OpenMP parallel_single")
#endif
#endif

!$omp parallel do private(my_thread, my_block_s, my_block_e, iblk, ns, ne, hv, tau, &
!$omp&                    nc, nr, hs, hd, vnorm2, hf, x, h, i), schedule(static,1), num_threads(max_threads)
            do my_thread = 1, max_threads

              if (iter == 1) then
                my_block_s = omp_block_limits(my_thread-1) + 1
                my_block_e = my_block_s
              else
                my_block_s = omp_block_limits(my_thread-1) + 2
                my_block_e = omp_block_limits(my_thread)
              endif

              do iblk = my_block_s, my_block_e

                ns = na_s + (iblk-1)*nb - n_off - my_thread + 1 ! first column in block
                ne = ns+nb-1                    ! last column in block

                if (istep<my_thread .or. ns+n_off>na) exit

                hv = hv_t(:,my_thread)
                tau = tau_t(my_thread)

                ! Store Householder vector for back transformation

                hh_cnt(iblk) = hh_cnt(iblk) + 1

                hh_gath(1   ,hh_cnt(iblk),iblk) = tau
                hh_gath(2:nb,hh_cnt(iblk),iblk) = hv(2:nb)

                nc = MIN(na-ns-n_off+1,nb) ! number of columns in diagonal block
                nr = MIN(na-nb-ns-n_off+1,nb) ! rows in subdiagonal block (may be < 0!!!)
                                          ! Note that nr>=0 implies that diagonal block is full (nc==nb)!

                ! Transform diagonal block
#ifdef DOUBLE_PRECISION_REAL
                call DSYMV('L', nc, tau, ab(1,ns), 2*nb-1, hv, 1, 0.0_rk8, hd, 1)
#else
                call SSYMV('L', nc, tau, ab(1,ns), 2*nb-1, hv, 1, 0.0_rk4, hd, 1)
#endif
                x = dot_product(hv(1:nc),hd(1:nc))*tau
#ifdef DOUBLE_PRECISION_REAL
                hd(1:nc) = hd(1:nc) - 0.5_rk8*x*hv(1:nc)
#else
                hd(1:nc) = hd(1:nc) - 0.5_rk4*x*hv(1:nc)
#endif

#ifdef DOUBLE_PRECISION_REAL
                call DSYR2('L', nc, -1.0_rk8 ,hd, 1, hv, 1, ab(1,ns), 2*nb-1)
#else
                call SSYR2('L', nc, -1.0_rk4 ,hd, 1, hv, 1, ab(1,ns), 2*nb-1)
#endif

#ifdef DOUBLE_PRECISION_REAL
                hv_t(:,my_thread) = 0._rk8
                tau_t(my_thread)  = 0._rk8
#else
                hv_t(:,my_thread) = 0._rk4
                tau_t(my_thread)  = 0._rk4
#endif
                if (nr<=0) cycle ! No subdiagonal block present any more

                ! Transform subdiagonal block
#ifdef DOUBLE_PRECISION_REAL
                call DGEMV('N', nr, nb, tau, ab(nb+1,ns), 2*nb-1, hv, 1, 0.0_rk8, hs, 1)
#else
                call SGEMV('N', nr, nb, tau, ab(nb+1,ns), 2*nb-1, hv, 1, 0.0_rk4, hs, 1)
#endif
                if (nr>1) then

                  ! complete (old) Householder transformation for first column

                  ab(nb+1:nb+nr,ns) = ab(nb+1:nb+nr,ns) - hs(1:nr) ! Note: hv(1) == 1

                  ! calculate new Householder transformation for first column
                  ! (stored in hv_t(:,my_thread) and tau_t(my_thread))

                  vnorm2 = sum(ab(nb+2:nb+nr,ns)**2)
#ifdef DOUBLE_PRECISION_REAL
                  call hh_transform_real_double(ab(nb+1,ns),vnorm2,hf,tau_t(my_thread))
#else
                  call hh_transform_real_single(ab(nb+1,ns),vnorm2,hf,tau_t(my_thread))
#endif

#ifdef DOUBLE_PRECISION_REAL
                  hv_t(1   ,my_thread) = 1._rk8
                  hv_t(2:nr,my_thread) = ab(nb+2:nb+nr,ns)*hf
                  ab(nb+2:,ns) = 0.0_rk8
#else
                  hv_t(1   ,my_thread) = 1._rk4
                  hv_t(2:nr,my_thread) = ab(nb+2:nb+nr,ns)*hf
                  ab(nb+2:,ns) = 0.0_rk4
#endif

                  ! update subdiagonal block for old and new Householder transformation
                  ! This way we can use a nonsymmetric rank 2 update which is (hopefully) faster
#ifdef DOUBLE_PRECSION_REAL
                  call DGEMV('T',nr, nb-1, tau_t(my_thread), ab(nb,ns+1), 2*nb-1, hv_t(1,my_thread), 1, 0.0_rk8, h(2), 1)
#else
                  call SGEMV('T',nr, nb-1, tau_t(my_thread), ab(nb,ns+1), 2*nb-1, hv_t(1,my_thread), 1, 0.0_rk4, h(2), 1)
#endif
                  x = dot_product(hs(1:nr),hv_t(1:nr,my_thread))*tau_t(my_thread)
                  h(2:nb) = h(2:nb) - x*hv(2:nb)
                  ! Unfortunately there is no BLAS routine like DSYR2 for a nonsymmetric rank 2 update ("DGER2")
                  do i=2,nb
                    ab(2+nb-i:1+nb+nr-i,i+ns-1) = ab(2+nb-i:1+nb+nr-i,i+ns-1) - hv_t(1:nr,my_thread)*h(i) - hs(1:nr)*hv(i)
                  enddo

                else

                  ! No new Householder transformation for nr=1, just complete the old one
                  ab(nb+1,ns) = ab(nb+1,ns) - hs(1) ! Note: hv(1) == 1
                  do i=2,nb
                    ab(2+nb-i,i+ns-1) = ab(2+nb-i,i+ns-1) - hs(1)*hv(i)
                  enddo
                  ! For safety: there is one remaining dummy transformation (but tau is 0 anyways)
#ifdef DOUBLE_PRECISION_REAL
                  hv_t(1,my_thread) = 1._rk8
#else
                  hv_t(1,my_thread) = 1._rk4
#endif

                endif

              enddo

            enddo ! my_thread
!$omp end parallel do

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
            call timer%stop("OpenMP parallel_double")
#else
            call timer%stop("OpenMP parallel_single")
#endif

#endif

            if (iter==1) then
              ! We are at the end of the first block

              ! Send our first column to previous PE
              if (my_pe>0 .and. na_s <= na) then
#ifdef WITH_MPI
                call mpi_wait(ireq_ab, mpi_status, mpierr)
#endif
                ab_s(1:nb+1) = ab(1:nb+1,na_s-n_off)
#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
                call mpi_isend(ab_s, nb+1, mpi_real8, my_pe-1, 1, mpi_comm, ireq_ab, mpierr)
#else
                call mpi_isend(ab_s, nb+1, mpi_real4, my_pe-1, 1, mpi_comm, ireq_ab, mpierr)
#endif

#endif /* WITH_MPI */
              endif

              ! Request last column from next PE
              ne = na_s + nblocks*nb - (max_threads-1) - 1
#ifdef WITH_MPI
              if (istep>=max_threads .and. ne <= na) then
#ifdef DOUBLE_PRECISION_REAL
                call mpi_recv(ab(1,ne-n_off), nb+1, mpi_real8, my_pe+1, 1, mpi_comm, mpi_status, mpierr)
#else
                call mpi_recv(ab(1,ne-n_off), nb+1, mpi_real4, my_pe+1, 1, mpi_comm, mpi_status, mpierr)
#endif
              endif
#else /* WITH_MPI */
              if (istep>=max_threads .and. ne <= na) then
                ab(1:nb+1,ne-n_off) = ab_s(1:nb+1)
              endif
#endif /* WITH_MPI */
            else
              ! We are at the end of all blocks

              ! Send last HH vector and TAU to next PE if it has been calculated above
              ne = na_s + nblocks*nb - (max_threads-1) - 1
              if (istep>=max_threads .and. ne < na) then
#ifdef WITH_MPI
                call mpi_wait(ireq_hv, mpi_status, mpierr)
#endif
                hv_s(1) = tau_t(max_threads)
                hv_s(2:) = hv_t(2:,max_threads)

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
                call mpi_isend(hv_s, nb, mpi_real8, my_pe+1, 2, mpi_comm, ireq_hv, mpierr)
#else
                call mpi_isend(hv_s, nb, mpi_real4, my_pe+1, 2, mpi_comm, ireq_hv, mpierr)
#endif

#endif /* WITH_MPI */
              endif

              ! "Send" HH vector and TAU to next OpenMP thread
              do my_thread = max_threads, 2, -1
                hv_t(:,my_thread) = hv_t(:,my_thread-1)
                tau_t(my_thread)  = tau_t(my_thread-1)
              enddo

            endif
          enddo ! iter

        else

          ! Codepath for 1 thread without OpenMP

          ! The following code is structured in a way to keep waiting times for
          ! other PEs at a minimum, especially if there is only one block.
          ! For this reason, it requests the last column as late as possible
          ! and sends the Householder vector and the first column as early
          ! as possible.

#endif /* WITH_OPENMP */

          do iblk=1,nblocks
            ns = na_s + (iblk-1)*nb - n_off ! first column in block
            ne = ns+nb-1                    ! last column in block

            if (ns+n_off>na) exit

            ! Store Householder vector for back transformation

            hh_cnt(iblk) = hh_cnt(iblk) + 1

            hh_gath(1   ,hh_cnt(iblk),iblk) = tau
            hh_gath(2:nb,hh_cnt(iblk),iblk) = hv(2:nb)

#ifndef WITH_OPENMP
            if (hh_cnt(iblk) == snd_limits(hh_dst(iblk)+1,iblk)-snd_limits(hh_dst(iblk),iblk)) then
              ! Wait for last transfer to finish
#ifdef WITH_MPI
              call mpi_wait(ireq_hhs(iblk), MPI_STATUS_IGNORE, mpierr)
#endif
              ! Copy vectors into send buffer
              hh_send(:,1:hh_cnt(iblk),iblk) = hh_gath(:,1:hh_cnt(iblk),iblk)
              ! Send to destination

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
              call mpi_isend(hh_send(1,1,iblk), nb*hh_cnt(iblk), mpi_real8, &
                           global_id(hh_dst(iblk), mod(iblk+block_limits(my_pe)-1,np_cols)), &
                           10+iblk, mpi_comm, ireq_hhs(iblk), mpierr)
#else
              call mpi_isend(hh_send(1,1,iblk), nb*hh_cnt(iblk), mpi_real4, &
                           global_id(hh_dst(iblk), mod(iblk+block_limits(my_pe)-1,np_cols)), &
                           10+iblk, mpi_comm, ireq_hhs(iblk), mpierr)
#endif

#else /* WITH_MPI */
             ! do the post-poned irecv here
             startAddr = startAddr - hh_cnt(iblk)
             hh_trans_real(1:nb,startAddr+1:startAddr+hh_cnt(iblk)) = hh_send(1:nb,1:hh_cnt(iblk),iblk)
#endif /* WITH_MPI */

            ! Reset counter and increase destination row
#ifdef DOUBLE_PRECISION_REAL
              hh_cnt(iblk) = 0._rk8
#else
              hh_cnt(iblk) = 0._rk4
#endif
              hh_dst(iblk) = hh_dst(iblk)+1
            endif

            ! The following code is structured in a way to keep waiting times for
            ! other PEs at a minimum, especially if there is only one block.
            ! For this reason, it requests the last column as late as possible
            ! and sends the Householder vector and the first column as early
            ! as possible.
#endif /* WITH_OPENMP */
            nc = MIN(na-ns-n_off+1,nb) ! number of columns in diagonal block
            nr = MIN(na-nb-ns-n_off+1,nb) ! rows in subdiagonal block (may be < 0!!!)
                                          ! Note that nr>=0 implies that diagonal block is full (nc==nb)!

            ! Multiply diagonal block and subdiagonal block with Householder vector

            if (iblk==nblocks .and. nc==nb) then

              ! We need the last column from the next PE.
              ! First do the matrix multiplications without last column ...

              ! Diagonal block, the contribution of the last element is added below!
#ifdef DOUBLE_PRECISION_REAL
              ab(1,ne) = 0._rk8
#else
              ab(1,ne) = 0._rk4
#endif


#ifdef DOUBLE_PRECISION_REAL
              call DSYMV('L', nc, tau, ab(1,ns), 2*nb-1, hv, 1, 0.0_rk8, hd, 1)

              ! Subdiagonal block
              if (nr>0) call DGEMV('N', nr, nb-1, tau, ab(nb+1,ns), 2*nb-1, hv, 1, 0.0_rk8, hs, 1)

              ! ... then request last column ...
#ifdef WITH_MPI

#ifdef WITH_OPENMP
              call mpi_recv(ab(1,ne), nb+1, mpi_real8, my_pe+1, 1, mpi_comm, MPI_STATUS, mpierr)
#else
              call mpi_recv(ab(1,ne), nb+1, mpi_real8, my_pe+1, 1, mpi_comm, MPI_STATUS_IGNORE, mpierr)
#endif

#else /* WITH_MPI */

              ab(1:nb+1,ne) = ab_s(1:nb+1)

#endif /* WITH_MPI */

#else /* DOUBLE_PRECISION_REAL */
              call SSYMV('L', nc, tau, ab(1,ns), 2*nb-1, hv, 1, 0.0_rk4, hd, 1)

              ! Subdiagonal block
              if (nr>0) call SGEMV('N', nr, nb-1, tau, ab(nb+1,ns), 2*nb-1, hv, 1, 0.0_rk4, hs, 1)

              ! ... then request last column ...
#ifdef WITH_MPI

#ifdef WITH_OPENMP
              call mpi_recv(ab(1,ne), nb+1, mpi_real4, my_pe+1, 1, mpi_comm, MPI_STATUS, mpierr)
#else
              call mpi_recv(ab(1,ne), nb+1, mpi_real4, my_pe+1, 1, mpi_comm, MPI_STATUS_IGNORE, mpierr)
#endif

#else /* WITH_MPI */

              ab(1:nb+1,ne) = ab_s(1:nb+1)

#endif /* WITH_MPI */

#endif /* DOUBLE_PRECISION_REAL */

              ! ... and complete the result
              hs(1:nr) = hs(1:nr) + ab(2:nr+1,ne)*tau*hv(nb)
              hd(nb) = hd(nb) + ab(1,ne)*hv(nb)*tau

            else

              ! Normal matrix multiply
#ifdef DOUBLE_PRECISION_REAL
              call DSYMV('L', nc, tau, ab(1,ns), 2*nb-1, hv, 1, 0.0_rk8, hd, 1)
              if (nr>0) call DGEMV('N', nr, nb, tau, ab(nb+1,ns), 2*nb-1, hv, 1, 0.0_rk8, hs, 1)
#else
              call SSYMV('L', nc, tau, ab(1,ns), 2*nb-1, hv, 1, 0.0_rk4, hd, 1)
              if (nr>0) call SGEMV('N', nr, nb, tau, ab(nb+1,ns), 2*nb-1, hv, 1, 0.0_rk4, hs, 1)
#endif
            endif

            ! Calculate first column of subdiagonal block and calculate new
            ! Householder transformation for this column
#ifdef DOUBLE_PRECISION_REAL
            hv_new(:) = 0._rk8 ! Needed, last rows must be 0 for nr < nb
            tau_new = 0._rk8
#else
            hv_new(:) = 0._rk4 ! Needed, last rows must be 0 for nr < nb
            tau_new = 0._rk4
#endif
            if (nr>0) then

              ! complete (old) Householder transformation for first column

              ab(nb+1:nb+nr,ns) = ab(nb+1:nb+nr,ns) - hs(1:nr) ! Note: hv(1) == 1

              ! calculate new Householder transformation ...
              if (nr>1) then
                vnorm2 = sum(ab(nb+2:nb+nr,ns)**2)
#ifdef DOUBLE_PRECISION_REAL
                call hh_transform_real_double(ab(nb+1,ns),vnorm2,hf,tau_new)
                hv_new(1) = 1._rk8
                hv_new(2:nr) = ab(nb+2:nb+nr,ns)*hf
                ab(nb+2:,ns) = 0._rk8
#else
                call hh_transform_real_single(ab(nb+1,ns),vnorm2,hf,tau_new)
                hv_new(1) = 1._rk4
                hv_new(2:nr) = ab(nb+2:nb+nr,ns)*hf
                ab(nb+2:,ns) = 0._rk4
#endif
              endif

              ! ... and send it away immediatly if this is the last block

              if (iblk==nblocks) then
#ifdef WITH_MPI

#ifdef WITH_OPENMP
                call mpi_wait(ireq_hv,MPI_STATUS,mpierr)
#else
                call mpi_wait(ireq_hv,MPI_STATUS_IGNORE,mpierr)
#endif

#endif /* WITH_MPI */
                hv_s(1) = tau_new
                hv_s(2:) = hv_new(2:)

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL
                call mpi_isend(hv_s, nb, mpi_real8, my_pe+1, 2, mpi_comm, ireq_hv, mpierr)
#else
                call mpi_isend(hv_s, nb, mpi_real4, my_pe+1, 2, mpi_comm, ireq_hv, mpierr)
#endif

#endif /* WITH_MPI */
              endif

            endif

            ! Transform diagonal block
            x = dot_product(hv(1:nc),hd(1:nc))*tau
#ifdef DOUBLE_PRECISION_REAL
            hd(1:nc) = hd(1:nc) - 0.5_rk8*x*hv(1:nc)
#else
            hd(1:nc) = hd(1:nc) - 0.5_rk4*x*hv(1:nc)
#endif

            if (my_pe>0 .and. iblk==1) then

              ! The first column of the diagonal block has to be send to the previous PE
              ! Calculate first column only ...

              ab(1:nc,ns) = ab(1:nc,ns) - hd(1:nc)*hv(1) - hv(1:nc)*hd(1)

              ! ... send it away ...
#ifdef WITH_MPI

#ifdef WITH_OPENMP
              call mpi_wait(ireq_ab,MPI_STATUS,mpierr)
#else
              call mpi_wait(ireq_ab,MPI_STATUS_IGNORE,mpierr)
#endif

#endif /* WITH_MPI */
              ab_s(1:nb+1) = ab(1:nb+1,ns)

#ifdef DOUBLE_PRECISION_REAL

#ifdef WITH_MPI
              call mpi_isend(ab_s, nb+1, mpi_real8, my_pe-1, 1, mpi_comm, ireq_ab, mpierr)
#endif
              ! ... and calculate remaining columns with rank-2 update
              if (nc>1) call DSYR2('L', nc-1, -1.0_rk8, hd(2), 1, hv(2), 1, ab(1,ns+1), 2*nb-1)
            else
              ! No need to  send, just a rank-2 update
              call DSYR2('L', nc, -1.0_rk8, hd, 1, hv, 1, ab(1,ns), 2*nb-1)
            endif
#else /* DOUBLE_PRECISION_REAL */

#ifdef WITH_MPI
              call mpi_isend(ab_s, nb+1, mpi_real4, my_pe-1, 1, mpi_comm, ireq_ab, mpierr)
#endif
              ! ... and calculate remaining columns with rank-2 update
              if (nc>1) call SSYR2('L', nc-1, -1.0_rk4, hd(2), 1, hv(2), 1, ab(1,ns+1), 2*nb-1)
            else
              ! No need to  send, just a rank-2 update
              call SSYR2('L', nc, -1.0_rk4, hd, 1, hv, 1, ab(1,ns), 2*nb-1)
            endif
#endif /* DOUBLE_PRECISION_REAL */

            ! Do the remaining double Householder transformation on the subdiagonal block cols 2 ... nb

            if (nr>0) then
              if (nr>1) then
#ifdef DOUBLE_PRECISION_REAL
                call DGEMV('T', nr, nb-1, tau_new, ab(nb,ns+1), 2*nb-1, hv_new, 1, 0.0_rk8, h(2), 1)
#else
                call SGEMV('T', nr, nb-1, tau_new, ab(nb,ns+1), 2*nb-1, hv_new, 1, 0.0_rk4, h(2), 1)
#endif
                x = dot_product(hs(1:nr),hv_new(1:nr))*tau_new
                h(2:nb) = h(2:nb) - x*hv(2:nb)
                ! Unfortunately there is no BLAS routine like DSYR2 for a nonsymmetric rank 2 update
                do i=2,nb
                  ab(2+nb-i:1+nb+nr-i,i+ns-1) = ab(2+nb-i:1+nb+nr-i,i+ns-1) - hv_new(1:nr)*h(i) - hs(1:nr)*hv(i)
                enddo
              else
                ! No double Householder transformation for nr=1, just complete the row
                do i=2,nb
                  ab(2+nb-i,i+ns-1) = ab(2+nb-i,i+ns-1) - hs(1)*hv(i)
                enddo
              endif
            endif

            ! Use new HH vector for the next block
            hv(:) = hv_new(:)
            tau = tau_new

          enddo

#ifdef WITH_OPENMP
        endif

        do iblk = 1, nblocks

          if (hh_dst(iblk) >= np_rows) exit
          if (snd_limits(hh_dst(iblk)+1,iblk) == snd_limits(hh_dst(iblk),iblk)) exit

          if (hh_cnt(iblk) == snd_limits(hh_dst(iblk)+1,iblk)-snd_limits(hh_dst(iblk),iblk)) then
            ! Wait for last transfer to finish
#ifdef WITH_MPI
            call mpi_wait(ireq_hhs(iblk), mpi_status, mpierr)
#endif
            ! Copy vectors into send buffer
            hh_send(:,1:hh_cnt(iblk),iblk) = hh_gath(:,1:hh_cnt(iblk),iblk)
            ! Send to destination

#ifdef WITH_MPI

#ifdef DOUBLE_PRECISION_REAL

            call mpi_isend(hh_send(1,1,iblk), nb*hh_cnt(iblk), mpi_real8, &
                  global_id(hh_dst(iblk), mod(iblk+block_limits(my_pe)-1, np_cols)), &
                  10+iblk, mpi_comm, ireq_hhs(iblk), mpierr)
#else
            call mpi_isend(hh_send(1,1,iblk), nb*hh_cnt(iblk), mpi_real4, &
                  global_id(hh_dst(iblk), mod(iblk+block_limits(my_pe)-1, np_cols)), &
                  10+iblk, mpi_comm, ireq_hhs(iblk), mpierr)
#endif

#else /* WITH_MPI */
            ! do the post-poned irecv here
            startAddr = startAddr - hh_cnt(iblk)
            hh_trans_real(1:nb,startAddr+1:startAddr+hh_cnt(iblk)) = hh_send(1:nb,1:hh_cnt(iblk),iblk)
#endif /* WITH_MPI */

            ! Reset counter and increase destination row
#ifdef DOUBLE_PRECISION_REAL
            hh_cnt(iblk) = 0._rk8
#else
            hh_cnt(iblk) = 0._rk4
#endif
            hh_dst(iblk) = hh_dst(iblk)+1
          endif

        enddo
#endif /* WITH_OPENMP */
      enddo ! istep

      ! Finish the last outstanding requests

#ifdef WITH_OPENMP

#ifdef WITH_MPI
      call mpi_wait(ireq_ab,MPI_STATUS,mpierr)
      call mpi_wait(ireq_hv,MPI_STATUS,mpierr)

      allocate(mpi_statuses(MPI_STATUS_SIZE,max(nblocks,num_chunks)), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when allocating mpi_statuses"//errorMessage
        stop
      endif

      call mpi_waitall(nblocks, ireq_hhs, MPI_STATUSES, mpierr)
      call mpi_waitall(num_chunks, ireq_hhr, MPI_STATUSES, mpierr)
      deallocate(mpi_statuses, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when deallocating mpi_statuses"//errorMessage
        stop
      endif
#endif

#else /* WITH_OPENMP */

#ifdef WITH_MPI
      call mpi_wait(ireq_ab,MPI_STATUS_IGNORE,mpierr)
      call mpi_wait(ireq_hv,MPI_STATUS_IGNORE,mpierr)

      call mpi_waitall(nblocks, ireq_hhs, MPI_STATUSES_IGNORE, mpierr)
      call mpi_waitall(num_chunks, ireq_hhr, MPI_STATUSES_IGNORE, mpierr)
#endif

#endif /* WITH_OPENMP */

#ifdef  WITH_MPI
      call mpi_barrier(mpi_comm,mpierr)
#endif
      deallocate(ab, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when deallocating ab"//errorMessage
        stop
      endif

      deallocate(ireq_hhr, ireq_hhs, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"tridiag_band_real: error when deallocating ireq_hhr, ireq_hhs"//errorMessage
        stop
      endif

      deallocate(hh_cnt, hh_dst, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"tridiag_band_real: error when deallocating hh_cnt, hh_dst"//errorMessage
         stop
       endif

      deallocate(hh_gath, hh_send, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"tridiag_band_real: error when deallocating hh_gath, hh_send"//errorMessage
         stop
       endif

      deallocate(limits, snd_limits, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"tridiag_band_real: error when deallocating limits, send_limits"//errorMessage
         stop
       endif

      deallocate(block_limits, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"tridiag_band_real: error when deallocating block_limits"//errorMessage
         stop
       endif

      deallocate(global_id, stat=istat, errmsg=errorMessage)
       if (istat .ne. 0) then
         print *,"tridiag_band_real: error when allocating global_id"//errorMessage
         stop
       endif

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
      call timer%stop("tridiag_band_real_double")
#else
      call timer%stop("tridiag_band_real_single")
#endif
#endif

#ifdef DOUBLE_PRECISION_REAL
    end subroutine tridiag_band_real_double
#else
    end subroutine tridiag_band_real_single
#endif

#ifdef DOUBLE_PRECISION_REAL
    subroutine trans_ev_tridi_to_band_real_double(na, nev, nblk, nbw, q, ldq, matrixCols, hh_trans_real, &
                                           mpi_comm_rows, mpi_comm_cols, wantDebug, useGPU, success, &
                                           THIS_REAL_ELPA_KERNEL)
#else
    subroutine trans_ev_tridi_to_band_real_single(na, nev, nblk, nbw, q, ldq, matrixCols, hh_trans_real, &
                                           mpi_comm_rows, mpi_comm_cols, wantDebug, useGPU, success, &
                                           THIS_REAL_ELPA_KERNEL)
#endif
    !-------------------------------------------------------------------------------
    !  trans_ev_tridi_to_band_real:
    !  Transforms the eigenvectors of a tridiagonal matrix back to the eigenvectors of the band matrix
    !
    !  Parameters
    !
    !  na          Order of matrix a, number of rows of matrix q
    !
    !  nev         Number eigenvectors to compute (= columns of matrix q)
    !
    !  nblk        blocksize of cyclic distribution, must be the same in both directions!
    !
    !  nb          semi bandwith
    !
    !  q           On input: Eigenvectors of tridiagonal matrix
    !              On output: Transformed eigenvectors
    !              Distribution is like in Scalapack.
    !
    !  ldq         Leading dimension of q
    !  matrixCols  local columns of matrix q
    !
    !  mpi_comm_rows
    !  mpi_comm_cols
    !              MPI-Communicators for rows/columns/both
    !
    !-------------------------------------------------------------------------------
#ifdef HAVE_DETAILED_TIMINGS
      use timings
#endif
      use cuda_functions
      use precision
      use pack_unpack_real
      use pack_unpack_real_gpu
      use compute_hh_trafo_real
      use iso_c_binding
      implicit none
      logical, intent(in) :: useGPU

      integer(kind=ik), intent(in)  :: THIS_REAL_ELPA_KERNEL
      integer(kind=ik), intent(in)  :: na, nev, nblk, nbw, ldq, matrixCols, mpi_comm_rows, mpi_comm_cols
#ifdef DESPERATELY_WANT_ASSUMED_SIZE
      real(kind=REAL_DATATYPE)                 :: q(ldq,*)
#else
      real(kind=REAL_DATATYPE)                 :: q(ldq,matrixCols)
#endif
      real(kind=REAL_DATATYPE), intent(in)     :: hh_trans_real(:,:)
      integer(kind=ik)              :: np_rows, my_prow, np_cols, my_pcol

      integer(kind=ik)              :: i, j, ip, sweep, nbuf, l_nev, a_dim2
      integer(kind=ik)              :: current_n, current_local_n, current_n_start, current_n_end
      integer(kind=ik)              :: next_n, next_local_n, next_n_start, next_n_end
      integer(kind=ik)              :: bottom_msg_length, top_msg_length, next_top_msg_length
      integer(kind=ik)              :: stripe_width, last_stripe_width, stripe_count
#ifdef WITH_OPENMP
      integer(kind=ik)              :: thread_width, csw, b_off, b_len
#endif
      integer(kind=ik)              :: num_result_blocks, num_result_buffers, num_bufs_recvd
      integer(kind=ik)              :: a_off, current_tv_off, max_blk_size
      integer(kind=ik)              :: mpierr, src, src_offset, dst, offset, nfact, num_blk
#ifdef WITH_OPENMP
#ifdef WITH_MPI
      integer(kind=ik)              :: mpi_status(MPI_STATUS_SIZE)
#endif
#endif
      logical                       :: flag

#ifdef WITH_OPENMP
3413
      real(kind=REAL_DATATYPE), pointer        :: a(:,:,:,:)
3414
#else
3415
      real(kind=REAL_DATATYPE), pointer        :: a(:,:,:)
3416
#endif
3417
      real(kind=REAL_DATATYPE)                 :: a_real
3418
3419
      type(c_ptr)                              :: a_ptr
      real(kind=REAL_DATATYPE)   , allocatable :: row(:)
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
      real(kind=REAL_DATATYPE)   , allocatable :: row_group(:,:)

#ifdef WITH_OPENMP
      real(kind=REAL_DATATYPE), allocatable    :: top_border_send_buffer(:,:), top_border_recv_buffer(:,:)
      real(kind=REAL_DATATYPE), allocatable    :: bottom_border_send_buffer(:,:), bottom_border_recv_buffer(:,:)
#else
      real(kind=REAL_DATATYPE), allocatable    :: top_border_send_buffer(:,:,:), top_border_recv_buffer(:,:,:)
      real(kind=REAL_DATATYPE), allocatable    :: bottom_border_send_buffer(:,:,:), bottom_border_recv_buffer(:,:,:)
#endif
      real(kind=REAL_DATATYPE), allocatable    :: result_buffer(:,:,:)
      real(kind=REAL_DATATYPE), allocatable    :: bcast_buffer(:,:)
      integer(kind=ik)              :: tmp

!      real*8, allocatable, device :: a_dev(:,:,:)
!      real*8, allocatable, device :: bcast_buffer_dev(:,:)
!      real*8, allocatable, device :: row_dev(:)
!      real*8, allocatable, device :: row_group_dev(:,:)
!      real*8, allocatable, device :: hh_dot_dev(:)
!      real*8, allocatable, device :: hh_tau_dev(:)

      integer(kind=c_intptr_t)      :: a_dev
      integer(kind=c_intptr_t)      :: bcast_buffer_dev
      integer(kind=c_size_t)        :: num
      integer(kind=c_size_t)        :: dev_offset, dev_offset_1


      integer(kind=c_intptr_t)      :: row_dev
      integer(kind=c_intptr_t)      :: row_group_dev
      integer(kind=c_intptr_t)      :: hh_dot_dev
      integer(kind=c_intptr_t)      :: hh_tau_dev
      Integer(kind=ik)              :: top, chunk, this_chunk
      integer(kind=ik)              :: row_group_size, unpack_idx

      integer(kind=ik)              :: n_off
      integer(kind=ik), allocatable :: result_send_request(:), result_recv_request(:), limits(:)
      integer(kind=ik), allocatable :: top_send_request(:), bottom_send_request(:)
      integer(kind=ik), allocatable :: top_recv_request(:), bottom_recv_request(:)
#ifdef WITH_OPENMP
      integer(kind=ik), allocatable :: mpi_statuses(:,:)
#endif
      ! MPI send/recv tags, arbitrary

      integer(kind=ik), parameter  :: bottom_recv_tag = 111
      integer(kind=ik), parameter  :: top_recv_tag    = 222
      integer(kind=ik), parameter  :: result_recv_tag = 333

      ! Just for measuring the kernel performance
      real(kind=c_double)          :: kernel_time ! MPI_WTIME always needs double
      ! long integer
      integer(kind=lik)            :: kernel_flops

#ifdef WITH_OPENMP
      integer(kind=ik)             :: max_threads, my_thread
      integer(kind=ik)             :: omp_get_max_threads
#endif

      logical, intent(in)          :: wantDebug
      logical                      :: success
      integer(kind=ik)             :: istat
      character(200)               :: errorMessage
      logical                      :: successCUDA
#ifndef WITH_MPI
      integer(kind=ik)             :: j1
#endif

#ifdef HAVE_DETAILED_TIMINGS
#ifdef DOUBLE_PRECISION_REAL
      call timer%start("trans_ev_tridi_to_band_real_double")
#else
      call timer%start("trans_ev_tridi_to_band_real_single")
#endif

#endif

#ifdef WITH_GPU_VERSION
      unpack_idx = 0
      row_group_size = 0
#endif
      success = .true.
      kernel_time = 0.0
      kernel_flops = 0

#ifdef WITH_OPENMP
      max_threads = 1
      max_threads = omp_get_max_threads()
#endif
      call MPI_Comm_rank(mpi_comm_rows, my_prow, mpierr)
      call MPI_Comm_size(mpi_comm_rows, np_rows, mpierr)
      call MPI_Comm_rank(mpi_comm_cols, my_pcol, mpierr)
      call MPI_Comm_size(mpi_comm_cols, np_cols, mpierr)
      if (mod(nbw,nblk)/=0) then
        if (my_prow==0 .and. my_pcol==0) then
          if (wantDebug) then
            write(error_unit,*) 'ELPA2_trans_ev_tridi_to_band_real: ERROR: nbw=',nbw,', nblk=',nblk
            write(error_unit,*) 'ELPA2_trans_ev_tridi_to_band_real: band backtransform works only for nbw==n*nblk'
          endif
          success = .false.
          return
        endif
      endif

      nfact = nbw / nblk


      ! local number of eigenvectors
      l_nev = local_index(nev, my_pcol, np_cols, nblk, -1)

      if (l_nev==0) then
#ifdef WITH_OPENMP
        thread_width = 0
#endif
        stripe_width = 0
        stripe_count = 0
        last_stripe_width = 0
      else

        ! Suggested stripe width is 48 since 48*64 real*8 numbers should fit into
        ! every primary cache
        if (.not.(useGPU)) then

#ifdef WITH_OPENMP
          thread_width = (l_nev-1)/max_threads + 1 ! number of eigenvectors per OMP thread
#endif
3543
#ifdef DOUBLE_PRECISION_REAL
3544
          stripe_width = 48 ! Must be a multiple of 4
3545
3546
3547
#else
          stripe_width = 96 ! Must be a multiple of 8
#endif
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
#ifdef WITH_OPENMP
          stripe_count = (thread_width-1)/stripe_width + 1
#else
          stripe_count = (l_nev-1)/stripe_width + 1
#endif
          ! Adapt stripe width so that last one doesn't get too small
#ifdef WITH_OPENMP
          stripe_width = (thread_width-1)/stripe_count + 1
#else
          stripe_width = (l_nev-1)/stripe_count + 1
#endif
3559
3560
3561
3562
3563
3564
3565
#ifdef DOUBLE_PRECISION_REAL
          stripe_width = ((stripe_width+3)/4)*4 ! Must be a multiple of 4 because of AVX/SSE memory alignment of 32 bytes
	  					! (4 * sizeof(double) == 32)
#else
          stripe_width = ((stripe_width+7)/8)*8 ! Must be a multiple of 8 because of AVX/SSE memory alignment of 32 bytes
	  					! (8 * sizeof(float) == 32)
#endif
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
        else ! GPUs are used
          stripe_width = 256 ! Must be a multiple of 4
          stripe_count = (l_nev - 1) / stripe_width + 1
        endif

        last_stripe_width = l_nev - (stripe_count-1)*stripe_width
      endif

      ! Determine the matrix distribution at the beginning

      allocate(limits(0:np_rows), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"trans_ev_tridi_to_band_real: error when allocating limits"//errorMessage
        stop
      endif
      call determine_workload(na, nbw, np_rows, limits)

      max_blk_size = maxval(limits(1:np_rows) - limits(0:np_rows-1))

      a_dim2 = max_blk_size + nbw

      if (useGPU) then
#ifdef DOUBLE_PRECISION_REAL
        num =  (stripe_width*a_dim2*stripe_count)*size_of_double_real_datatype
        successCUDA = cuda_malloc(a_dev, stripe_width*a_dim2*stripe_count*size_of_double_real_datatype)
#else
        num =  (stripe_width*a_dim2*stripe_count)*size_of_single_real_datatype
        successCUDA = cuda_malloc(a_dev, stripe_width*a_dim2*stripe_count*size_of_single_real_datatype)
#endif
        if (.not.(successCUDA)) then
          print *,"trans_ev_tridi_to_band_real: error in cudaMalloc"//errorMessage
          stop
        endif

        successCUDA = cuda_memset(a_dev , 0, num)
        if (.not.(successCUDA)) then
          print *,"trans_ev_tridi_to_band_real: error in cudaMemset"//errorMessage
          stop
        endif

      else ! GPUs are not used
3607
#if 0
3608
!DEC$ ATTRIBUTES ALIGN: 64:: a
3609
3610
#endif

3611
#ifdef WITH_OPENMP
3612
        if (posix_memalign(a_ptr, 64_C_SIZE_T, stripe_width*a_dim2*stripe_count*max_threads*C_SIZEOF(a_real)) /= 0) then
3613
3614
3615
3616
          print *,"trans_ev_tridi_to_band_real: error when allocating a"//errorMessage
          stop
        endif

3617
3618
3619
        call c_f_pointer(a_ptr, a, [stripe_width,a_dim2,stripe_count,max_threads])
        ! allocate(a(stripe_width,a_dim2,stripe_count,max_threads), stat=istat, errmsg=errorMessage)

3620
3621
        ! a(:,:,:,:) should be set to 0 in a parallel region, not here!
#else
3622
        if (posix_memalign(a_ptr, 64_C_SIZE_T, stripe_width*a_dim2*stripe_count*C_SIZEOF(a_real)) /= 0) then
3623
3624
3625
          print *,"trans_ev_tridi_to_band_real: error when allocating a"//errorMessage
          stop
        endif
3626
3627
3628
3629

        call c_f_pointer(a_ptr, a,[stripe_width,a_dim2,stripe_count] )
        !allocate(a(stripe_width,a_dim2,stripe_count), stat=istat, errmsg=errorMessage)

3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755