Source

IRATE-format / irate / gadget.py

Full commit
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
from __future__ import division
from .validate import Validator,add_validator_type

def gbin_to_irate(inname,outname,snapnum,potential=False,accel=False,entropy=False,timestep=False,
    t0_name="Gas",t1_name="Dark_Halo",t2_name="Dark_Disk",t3_name="Dark_Bulge",
    t4_name="Star",t5_name="Dark_Boundary",
    ics=False,s8=None,ns=None,omegaB=None,
    lname="comoving Mpc/h",lunits=[3.08568025e24,-1,1],
    vname="(km/s)*sqrt(a)",vunits=[1e5,0,0.5],
    mname="1e10 M_sun/h",munits=[1.98892e43,-1,0]):
    """
    Reads a GADGET format file block by block (e.g. coordinate block for gas
    particles), writes the block to an IRATE formate HDF5 file, and then 
    deletes that block from memory. 

    :param inname: 
        The name of the gadget binary file to be read
    :param  outname: 
        The name of the IRATE file to be written
    :param int snapnum:  
        The number to add to 'Snapshot' that becomes the name of
        the group that particle data is added to. 
    :param bool potential: 
        True to read the Makefile enabled potential block
    :param bool accel: 
        True to read the Makefile enabled acceleration block
    :param bool entropy: 
        True to read the Makefile enabled dA/dt block
    :param bool timestep: 
        True to read the Makefile enabled timestep block 
    :param t#_name: 
        Determines the name of the group that contains the data from #
    :param bool ics:  
        True if the file being converted is an initial conditions
        file, in which case the gas density and smoothing length blocks won't
        be looked for.
    :param float s8: 
        sigma_8, for the purposes of adding it to the Cosmology group
    :param float ns: 
        n_s, for the purposes of adding it to the Cosmology group
    :param ___name: 
        A human readable string that defines the units for either
        length (l), velocity (v), or mass (m)
    :param ___units: 
        A three-element array.  The first entry defines the
        conversion factor to convert either length (l), velocity (v),
        or mass (m) to CGS units.  The second element is the exponent on the
        reduced Hubble Parameter that appears in that unit, and the third
        is the exponent on the scale factor that appears in that unit. 
        
    # refers to the same names as Gadget2:
    
    * 0 = gas particles
    * 1 = halo particles
    * 2 = disk particles
    * 3 = bulge particles
    * 4 = star particles
    * 5 = bndry particles
    
    """
    import h5py,struct,os
    from numpy import fromstring,empty
    from .core import add_cosmology,check_version
    try:
        snapnum = int(snapnum)
    except ValueError:
        raise ValueError("The number used for the snapshot is not an integer--please check and provide it by hand.")
    print "\nOpening "+inname    
    f = open(inname,'rb')
    
    #Grab the cosmology to check that it's the same
    f.seek(140)
    omegaM = struct.unpack('<d',f.read(8))[0]
    omegaL = struct.unpack('<d',f.read(8))[0]
    hubble = struct.unpack('<d',f.read(8))[0]
    f.seek(0)
    
    if os.path.isfile(outname):
        new = False
        print "Opening {0} to add data to it.".format(outname)
        irate = h5py.File(outname,'a')
        
        try:
            check_version(irate,update=False)
        except ValueError,e:
            print "\nWARNING:  ",e,"\n" 
        
        if 'Cosmology' not in irate.keys():
            add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=True)
        else:
            try:
                add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=False)
            except KeyError:    #Then ns, s8, or omegaB was passed, but wasn't in the file before (in which case I want to add it)
                add_cosmology(outname,s8=s8,ns=ns,omegaB=omegaB,update=True)
    else:
        new = True
        print "Creating new IRATE file {0}".format(outname)
        irate = h5py.File(outname,'w')
        check_version(irate,update=True)
        add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=True)


    #Create the file structure
    try:
        snap = irate.create_group("Snapshot{0:05}".format(snapnum))
        print "Created new group for Snapshot{0:05}".format(snapnum)
    except ValueError:
        snap = irate["Snapshot{0:05}".format(snapnum)]
        print "Adding data to exist group Snapshot{0:05}".format(snapnum)
        
    #Now I want to know what particles I have, so I can only create groups for those that have particles
    #First read the header so I know how many particles of each type I have
    header_size = struct.unpack('<I',f.read(4))[0]

    #number of particles of each type in this file
    nfile = struct.unpack('<6I',f.read(24)) #Number of particles in this file

    masstable = struct.unpack('<6d',f.read(48))  #masses of the particle groups
        
    a = struct.unpack('<d',f.read(8))[0]        #expansion factor
    z = struct.unpack('<d',f.read(8))[0]        #redshift
    
    if "Redshift" in snap.attrs.keys():
        if snap.attrs['Redshift'] != z:
            msg = "The existing redshift for group /Snapshot{0:05} doesn't match that in the Gadget file.  Please specify the snapshot group manually.".format(snapnum)
            raise ValueError(msg)
    else:
        snap.attrs['Redshift'] = z
    
    if "ScaleFactor" in snap.attrs.keys():
        if snap.attrs['ScaleFactor'] != a:
            msg = "The existing scale factor for group /Snapshot{0:05} doesn't match that in the Gadget file.  Please specify the snapshot group manually".format(snapnum)
            raise ValueError(msg)
    else:
        snap.attrs['ScaleFactor'] = a

    flag_sfr = struct.unpack('<i',f.read(4))[0] #star formation included?
    flag_feed = struct.unpack('<i',f.read(4))[0] #feedback included?

    ntot = struct.unpack('<6i',f.read(24))      #total number of particles in the simulation (= nfile if numfiles == 1)
        
    flag_cool = struct.unpack('<i',f.read(4))[0]  #cooling included?
    numfiles = struct.unpack('<i',f.read(4))[0]   #number of files in each snapshot
    boxsize = struct.unpack('<d',f.read(8))[0] #Size of the box, if periodic
    omega0 = struct.unpack('<d',f.read(8))[0]  #matter density at z = 0
    omegaL = struct.unpack('<d',f.read(8))[0]  #vacuum energy density at z = 0
    h = struct.unpack('<d',f.read(8))[0] #hubble parameter in units of 100 km/s/Mpc
    flag_age = struct.unpack('<i',f.read(4))[0]  #stellar age included?
    flag_metals = struct.unpack('<i',f.read(4))[0]  #use metals?
    nhighword = struct.unpack('<6i',f.read(24))   #contains the most significant word of 64-bit particle numbers (if npart > 2^32)

    flag_entropy = struct.unpack('<i',f.read(4))[0] #entropy instead of thermal energy in initial conditions?

    f.seek(264,0)   #Moves to the end of the header (and block that tells you size of header)

    #Now I want to create the simulation group and the cosmology group (if they don't exist)
    try:
        simprops = irate.create_group("SimulationProperties")
        addprops = True
    except ValueError:
        #Then it already exists, so let's check that what I was going to put there matches
        simprops = irate['SimulationProperties']
        addprops = False
        try:
            msg = "\n"
            exitflag = False
            if boxsize != simprops.attrs['Boxsize']:
                msg = msg + "Box size from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_sfr != simprops.attrs['FlagSFR']:
                msg = msg + "Flag SFR from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_feed != simprops.attrs['FlagFeedback']:
                msg = msg + "Flag Feedback from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_cool != simprops.attrs['FlagCooling']:
                msg = msg + "Flag Cooling from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_age != simprops.attrs['FlagAge']:
                msg = msg + "Flag Age from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_metals != simprops.attrs['FlagMetals']:
                msg = msg + "Flag Metals from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_entropy != simprops.attrs['FlagEntropyICs']:
                msg = msg + "Flag Entropy ICs from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if exitflag:
                raise ValueError(msg)
        except KeyError:
            raise KeyError("There is a group for simulation properties, but it's not filled with all the relevant values.  This is considered odd.")
    
    if addprops:
        simprops.attrs['Boxsize'] = boxsize
        simprops.attrs['FlagSFR'] = flag_sfr
        simprops.attrs['FlagFeedback'] = flag_feed
        simprops.attrs['FlagCooling'] = flag_cool
        simprops.attrs['FlagAge'] = flag_age
        simprops.attrs['FlagMetals'] = flag_metals
        simprops.attrs['FlagEntropyICs'] = flag_entropy
        
    #Now I'm done with the IRATE file, and instead I need to create groups inside the Snapshot group
    ngas = nfile[0]
    nhalo = nfile[1]
    ndisk = nfile[2]
    nbulge = nfile[3]
    nstar = nfile[4]
    nbndry = nfile[5]

    capbet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    try:
        pdata = snap.create_group('ParticleData')
        #Add units to pdata
        pdata.attrs['Positionunitname'] = lname
        pdata.attrs['Positionunitcgs'] = lunits
        pdata.attrs['Velocityunitname'] = vname
        pdata.attrs['Velocityunitcgs'] = vunits
        pdata.attrs['Massunitname'] = mname
        pdata.attrs['Massunitcgs'] = munits
    except ValueError:
        pdata = snap['ParticleData']
        #If 'ParticleData' already exists, check that the units that I'm adding match up (if it has units)
        try:
            msg = "\n"
            #Check that the units that are there match what I have
            exitflag = False
            if pdata.attrs['Positionunitname'] != lname or (pdata.attrs['Positionunitcgs'] != lunits).all():
                msg = msg + "Length units in existing file are different than those provided.\n"
                exitflag = True
            if pdata.attrs['Velocityunitname'] != vname or (pdata.attrs['Velocityunitcgs'] != vunits).all():
                msg = msg + "Velocity units in existing file are different than those provided.\n"
                exitflag = True
            if pdata.attrs['Massunitname'] != mname or (pdata.attrs['Massunitcgs'] != munits).all():
                msg = msg + "Mass units in existing file are different than those provided.\n"
                exitflag = True
            if exitflag:
                raise ValueError(msg)
        except KeyError:
            #add the units, since they're not there 
            pdata.attrs['Positionunitname'] = lname
            pdata.attrs['Positionunitcgs'] = lunits
            pdata.attrs['Velocityunitname'] = vname
            pdata.attrs['Velocityunitcgs'] = vunits
            pdata.attrs['Massunitname'] = mname
            pdata.attrs['Massunitcgs'] = munits

    exitflag = False
    msg = "\n"
    if ngas > 0:
        if t0_name[0] not in capbet:  t0_name = t0_name.capitalize()
        try:
            gas = pdata.create_group(t0_name)
            print "Saving gas data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t0_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save gas data.\n".format(snapnum,t0_name)
            exitflag = True
        
    if nhalo > 0:
        if t1_name[0] not in capbet:  t1_name = t1_name.capitalize()
        try:
            halo = pdata.create_group(t1_name)
            print "Saving halo data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t1_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save halo data.\n".format(snapnum,t1_name)
            exitflag = True
        
    if ndisk > 0:
        if t2_name[0] not in capbet:  t2_name = t2_name.capitalize()
        try:
            disk = pdata.create_group(t2_name)
            print "Saving disk data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t2_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save disk data.\n".format(snapnum,t2_name)
            exitflag = True
        
    if nbulge > 0:
        if t3_name[0] not in capbet:  t3_name = t3_name.capitalize()
        try:
            bulge = pdata.create_group(t3_name)
            print "Saving bulge data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t3_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save bulge data.\n".format(snapnum,t3_name)
            exitflag = True
        
    if nstar > 0:
        if t4_name[0] not in capbet:  t4_name = t4_name.capitalize()
        try:
            star = pdata.create_group(t4_name)
            print "Saving star data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t4_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save star data.\n".format(snapnum,t4_name)
            exitflag = True
        
    if nbndry > 0:
        if t5_name[0] not in capbet:  t5_name = t5_name.capitalize()
        try:
            bndry = pdata.create_group(t5_name)
            print "Saving boundary data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t5_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save boundary data.\n".format(snapnum,t5_name)
            exitflag = True
        
    if exitflag:
        raise ValueError(msg)

    #Ok, now to read in the blocks and immediately save them in the file
    #Read in the coordinates, starting with the size of the block    
    print "Reading coordinates"
    coord_size = struct.unpack('<I',f.read(4))[0]

    if ngas > 0:    #Only try to do something for a group of particles if they exist
        #Read in the binary data and convert to the appropriate type and save in the appropriate place
        gas.create_dataset("Position",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
    if nhalo > 0:
        halo.create_dataset("Position",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    if ndisk > 0:
        disk.create_dataset("Position",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
    print "Read coordinates for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
    if nbulge > 0:
        bulge.create_dataset("Position",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    if nstar > 0:
        star.create_dataset("Position",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    if nbndry > 0:
        bndry.create_dataset("Position",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
        
    #And read the size of the coordinate block again.
    if struct.unpack('<I',f.read(4))[0] != coord_size:
        raise IOError("The block size at the end of the coordinate block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")

    #next up is velocities.  pretty identical to the coordinates.
    vel_size = struct.unpack('<I',f.read(4))[0]
    print "Reading velocities"
    
    if ngas > 0:    #Only try to do something for a group of particles if they exist
        gas.create_dataset("Velocity",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
    if nhalo > 0:
        halo.create_dataset("Velocity",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    if ndisk > 0:
        disk.create_dataset("Velocity",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
    print "Read velocities for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
    if nbulge > 0:
        bulge.create_dataset("Velocity",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    if nstar > 0:
        star.create_dataset("Velocity",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    if nbndry > 0:
        bndry.create_dataset("Velocity",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))

    if struct.unpack('<I',f.read(4))[0] != vel_size:   #And read the size of the block again.
        raise IOError("The block size at the end of the velocity block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")

    #Next up are the particle IDs, which are unsigned integers.
    id_size = struct.unpack('<I',f.read(4))[0]
    print "Reading particle IDs"

    if ngas > 0:
        gas.create_dataset("ID",data=fromstring(f.read(4*ngas),dtype='I'))
    if nhalo > 0:
        halo.create_dataset("ID",data=fromstring(f.read(4*nhalo),dtype='I'))
    if ndisk > 0:
        disk.create_dataset("ID",data=fromstring(f.read(4*ndisk),dtype='I'))
    print "Read IDs for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
    if nbulge > 0:
        bulge.create_dataset("ID",data=fromstring(f.read(4*nbulge),dtype='I'))
    if nstar > 0:
        star.create_dataset("ID",data=fromstring(f.read(4*nstar),dtype='I'))
    if nbndry > 0:
        bndry.create_dataset("ID",data=fromstring(f.read(4*nbndry),dtype='I'))

    if struct.unpack('<I',f.read(4))[0] != id_size:   #And read the size of the block again.
        raise IOError("The block size at the end of the IDs block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")

    #Now I have to do the mass block.  Do this by checking if there are particles in a block that have a zero in the mass table.    
    if (ngas > 0 and masstable[0] == 0) or (nhalo > 0 and masstable[1] == 0) or (ndisk > 0 and masstable[2] == 0) or (nbulge > 0 and masstable[3] == 0) or (nstar > 0 and masstable[4] == 0) or (nbndry > 0 and masstable[5] == 0):
    #In other words, only read the size of the mass block if there is a mass block (for any of the groups)
        mass_size = struct.unpack('<I',f.read(4))[0]
    
        if ngas > 0 and masstable[0] == 0:    #There are particles in the group, but their masses aren't in the header (so they must be in the file)
            print "Reading variable masses for gas group"
            gas.create_dataset("Mass",data=fromstring(f.read(4*ngas),dtype='f'))
        elif ngas > 0 and masstable[0] > 0:    #There are particles in the group, and their masses are in the header (so I have to fill in a variable block)
            marray = empty(ngas,dtype='f')
            marray[:] = masstable[0]
            gas.create_dataset("Mass",data=marray)
        
        if nhalo > 0 and masstable[1] == 0:
            print "Reading variable masses for halo group"
            halo.create_dataset("Mass",data=fromstring(f.read(4*nhalo),dtype='f'))
        elif nhalo > 0 and masstable[1] > 0:
            marray = empty(nhalo,dtype='f')
            marray[:] = masstable[1]
            halo.create_dataset("Mass",data=marray)
            
        if ndisk > 0 and masstable[2] == 0:
            print "Reading variable masses for disk group"
            disk.create_dataset("Mass",data=fromstring(f.read(4*ndisk),dtype='f'))
        elif ndisk > 0 and masstable[2] > 0:
            marray = empty(ndisk,dtype='f')
            marray[:] = masstable[2]
            disk.create_dataset("Mass",data=marray)
            
        if nbulge > 0 and masstable[3] == 0:
            print "Reading variable masses for bulge group"
            bulge.create_dataset("Mass",data=fromstring(f.read(4*nbulge),dtype='f'))
        elif nbulge > 0 and masstable[3] > 0:
            marray = empty(nbulge,dtype='f')
            marray[:] = masstable[3]
            bulge.create_dataset("Mass",data=marray)
            
        if nstar > 0 and masstable[4] == 0:
            print "Reading variable masses for star group"
            star.create_dataset("Mass",data=fromstring(f.read(4*nstar),dtype='f'))
        elif nstar > 0 and masstable[4] > 0:
            marray = empty(nstar,dtype='f')
            marray[:] = masstable[4]
            star.create_dataset("Mass",data=marray)
            
        if nbndry > 0 and masstable[5] == 0:
            print "Reading variable masses for boundary group"
            bndry.create_dataset("Mass",data=fromstring(f.read(4*nbndry),dtype='f'))
        elif nbndry > 0 and masstable[5] > 0:
            marray = empty(nbndry,dtype='f')
            marray[:] = masstable[5]
            bndry.create_dataset("Mass",data=marray)
        
        try:    
            del marray      #If there are no masses in the mass table, marray will have never been defined
        except NameError:
            pass
            
        if struct.unpack('<I',f.read(4))[0] != mass_size:   #And read the size of the block again.
            raise IOError("The block size at the end of the mass block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    
    else:       #Then all the particles in the file have their mass defined in the header, so I need to fill arrays
        if ngas > 0:
            marray = empty(ngas)
            marray.fill(masstable[0])
            gas.create_dataset("Mass",data=marray)
        if nhalo > 0:
            marray = empty(nhalo)
            marray.fill(masstable[1])
            halo.create_dataset("Mass",data=marray)
        if ndisk > 0:
            marray = empty(ndisk)
            marray.fill(masstable[2])
            disk.create_dataset("Mass",data=marray)
        if nbulge > 0:
            marray = empty(nbulge)
            marray.fill(masstable[3])
            bulge.create_dataset("Mass",data=marray)
        if nstar > 0:
            marray = empty(nstar)
            marray.fill(masstable[4])
            star.create_dataset("Mass",data=marray)
        if nbndry > 0:
            marray = empty(nbndry)
            marray.fill(masstable[5])
            bndry.create_dataset("Mass",data=marray)
            
        del marray      #marray had to have been defined if there are any particles in the file
            
    #Next up is gas specific stuff:
    if ngas > 0:
        print "Reading gas specific data."
        
        #Put all this inside the if statement because I don't want it reading block sizes for gas blocks if there is no gas data (cause then there will be no block size and I will accidentally read into other data or past the end of the file.)
        
        #Internal energy:
        u_size = struct.unpack('<I',f.read(4))[0]
        gas.create_dataset("InternalEnergy",data=fromstring(f.read(4*ngas),dtype='f'))
        if struct.unpack('<I',f.read(4))[0] != u_size:
            raise IOError("The block size at the end of the internal energy block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
        print "Read gas internal energy."
        
        if not ics:     #These two blocks aren't required in IC files.
            #Density:
            rho_size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset("Density",data=fromstring(f.read(4*ngas),dtype='f'))  
            if struct.unpack('<I',f.read(4))[0] != rho_size:
                raise IOError("The block size at the end of the density block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
            
            #Smoothing length:
            hsml_size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset("SmoothingLength",data=fromstring(f.read(4*ngas),dtype='f'))       
            if struct.unpack('<I',f.read(4))[0] != hsml_size:
                raise IOError("The block size at the end of the HSML block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.") 
            
            print "Read gas density and smoothing lengths."
            
        else:
            print "Skipping blocks for gas density and smoothing lengths because this is an initial conditions file."
        
    #Now for the things that have to be specifically enabled in the makefile
    if potential:
        print "Reading gravitational potentials."
        phi_size = struct.unpack('<I',f.read(4))[0]
        
        if ngas > 0:
            gas.create_dataset("Potential",data=fromstring(f.read(4*ngas),dtype='f'))     
        if nhalo > 0:
            halo.create_dataset("Potential",data=fromstring(f.read(4*nhalo),dtype='f'))
        if ndisk > 0:
            disk.create_dataset("Potential",data=fromstring(f.read(4*ndisk),dtype='f'))
        print "Read gravitational potentials for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
        if nbulge > 0:
            bulge.create_dataset("Potential",data=fromstring(f.read(4*nbulge),dtype='f'))
        if nstar > 0:
            star.create_dataset("Potential",data=fromstring(f.read(4*nstar),dtype='f'))
        if nbndry > 0:
            bndry.create_dataset("Potential",data=fromstring(f.read(4*nbndry),dtype='f'))
        
        if struct.unpack('<I',f.read(4))[0] != phi_size:
            raise IOError("The block size at the end of the gravitational potential block doesn't match that at the beginning.  This may be because the file contains extra unexpected blocks.  It is suggested that you rerun, ignoring the extra optional blocks, in the hopes that the standard blocks haven't been modified.")

    
    #Next, acceleration, which is the same as velocity:
    if accel:
        print "Reading accelerations."
        accel_size = struct.unpack('<I',f.read(4))[0]
        
        if ngas > 0:
            gas.create_dataset("Acceleration",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
        if nhalo > 0:
            halo.create_dataset("Acceleration",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
        if ndisk > 0:
            disk.create_dataset("Acceleration",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
        print "Read accelerations for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
        if nbulge > 0:
            bulge.create_dataset("Acceleration",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
        if nstar > 0:
            star.create_dataset("Acceleration",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
        if nbndry > 0:
            bndry.create_dataset("Acceleration",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
        
        if struct.unpack('<I',f.read(4))[0] != accel_size:
            raise IOError("The block size at the end of the acceleration block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    
    if entropy and ngas > 0:    #i.e. neglect their call for entropy data if there are no gas particles
        print "Reading rate of change of entropy for gas data"
        dsdt_size = struct.unpack('<I',f.read(4))[0]
        gas.create_dataset("RateofChangeofEntropy",data=fromstring(f.read(4*ngas),dtype='f'))
        if struct.unpack('<I',f.read(4))[0] != dsdt_size:
            raise IOError("The block size at the end of the entropy block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")    
    else:
        if entropy:  print "Warning:  You specified that entropy is included, but there are no gas particles."
        
    if timestep:
        print "Reading timesteps"
        timestep_size = struct.unpack('<I',f.read(4))[0]
        
        if ngas > 0:
            gas.create_dataset("TimeStep",data=fromstring(f.read(4*ngas),dtype='f'))
        if nhalo > 0:
            halo.create_dataset("TimeStep",data=fromstring(f.read(4*nhalo),dtype='f'))
        if ndisk > 0:
            disk.create_dataset("TimeStep",data=fromstring(f.read(4*ndisk),dtype='f'))     
        print "Read timesteps for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))    
        if nbulge > 0:
            bulge.create_dataset("TimeStep",data=fromstring(f.read(4*nbulge),dtype='f')) 
        if nstar > 0:
            star.create_dataset("TimeStep",data=fromstring(f.read(4*nstar),dtype='f'))
        if nbndry > 0:
            bndry.create_dataset("TimeStep",data=fromstring(f.read(4*nbndry),dtype='f'))
        
                
        if struct.unpack('<I',f.read(4))[0] != timestep_size:
            raise IOError("The block size at the end of the timestep block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    
    current_pos = f.tell()
    f.seek(0,2) #Jump to the end of the file
    if current_pos == f.tell():
        print "Read "+inname
    else:
        print "Completed reading "+inname+" but there remain {0} bytes at the end of the file unread.".format(f.tell()-current_pos)
    f.close()
    if new:  print "Created IRATE format file "+outname
    else:  print "Added data to IRATE format file "+outname
    irate.close()        

def gbin2_to_irate(inname,outname,snapnum,t0_name="Gas",t1_name="Dark_Halo",t2_name="Dark_Disk",
    t3_name="Dark_Bulge",t4_name="Star",t5_name="Dark_Boundary",
    s8=None,ns=None,omegaB=None,
    fprec=4,zfields=3,
    lname="comoving Mpc/h",lunits=[3.08568025e24,-1,1],
    vname="(km/s)*sqrt(a)",vunits=[1e5,0,0.5],
    mname="1e10 M_sun/h",munits=[1.98892e43,-1,0]):
    """
    Reads a GADGET type 2 snapshot file block by block (e.g. coordinate 
    block for gas particles), writes the block to an IRATE formate HDF5 file,
    and then deletes that block from memory. If a given block identifier isn't
    recognized, one of two things will happen:  either the script will figure
    out which particles that data belongs to and add it automatically with
    the dataset named according to the label used, or if it's not obvious
    what particles the data belongs to, the user will be given the option to
    skip it or to exit entirely.

    :param inname: 
        The name of the gadget binary file to be read
    :param  outname: 
        The name of the IRATE file to be written, 
    :param int snapnum:  
        The number to add to 'Snapshot' that becomes the name of
        the group that particle data is added to.
    :param t#_name: 
        Determines the name of the group that contains the data 
        from #
    :param float s8: 
        sigma_8, for the purposes of adding it to the Cosmology group
    :param float ns: 
        n_s, for the purposes of adding it to the Cosmology group
    :param float omegaB:
        omegaB, for the purposes of adding it to the Cosmology group
    :param fprec:
        Precision of the file. Single (4) or double (8). Assumed
        single precision. Warning! Right now changing this parameter
        to double prec (8) will probably not work but I hope it is a
        good start point.
    :param zfields:
        Fields in the Z block for each particle.
    :param ___name: 
        A human readable string that defines the units for either
        length (l), velocity (v), or mass (m)
    :param ___units: 
        A three-element array.  The first entry defines the
        conversion factor to convert either length (l), velocity (v),
        or mass (m) to CGS units.  The second element is the exponent on the
        reduced Hubble Parameter that appears in that unit, and the third
        is the exponent on the scale factor that appears in that unit.
        
    # refers to the same names as Gadget2:
    
    * 0 = gas particles
    * 1 = halo particles
    * 2 = disk particles
    * 3 = bulge particles
    * 4 = star particles
    * 5 = bndry particles
    
    """
    import h5py,struct,os,sys
    from numpy import fromstring,empty
    from .core import add_cosmology,check_version
    try:
        snapnum = int(snapnum)
    except ValueError:
        raise ValueError("The number used for the snapshot is not an integer--please check and provide it by hand.")
    print "\nOpening "+inname    
    f = open(inname,'rb')
    #First let's find out the total length of the file
    f.seek(0,2)
    flen = f.tell()
    f.seek(0,0)
    
    #Grab the cosmology to check that it's the same
    f.seek(156)
    omegaM = struct.unpack('<d',f.read(8))[0]
    omegaL = struct.unpack('<d',f.read(8))[0]
    hubble = struct.unpack('<d',f.read(8))[0]
    f.seek(0)
    
    if os.path.isfile(outname):
        new = False
        print "Opening {0} to add data to it.".format(outname)
        irate = h5py.File(outname,'a')
        
        try:
            check_version(irate,update=False)
        except ValueError,e:
            print "\nWARNING:  ",e,"\n" 
            
        if 'Cosmology' not in irate.keys():
            add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=True)
        else:
            try:
                add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=False)
            except KeyError:    #Then ns, s8, or omegaB was passed, but wasn't in the file before (in which case I want to add it)
                add_cosmology(outname,s8=s8,ns=ns,omegaB=omegaB,update=True)
    else:
        new = True
        print "Creating new IRATE file {0}".format(outname)
        irate = h5py.File(outname,'w')
        check_version(irate,update=True)
        add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=True)
        
    #Create the file structure
    try:
        snap = irate.create_group("Snapshot{0:05}".format(snapnum))
        print "Created new group for Snapshot{0:05}".format(snapnum)
    except ValueError:
        snap = irate["Snapshot{0:05}".format(snapnum)]
        print "Adding data to existing group Snapshot{0:05}".format(snapnum)
        
    #First read the header so I know how many particles of each type I have
    #Since this is a type 2 binary, first I have to read the size of a block that tells me that the header block is next, etc.
    bsize = struct.unpack('<I',f.read(4))[0]   #This should be an 8
    if f.read(4) != 'HEAD':      #Most of the time I'm going to be using the labels to tell me what something is, but here I know that I have to read the header
        print "You're reading the wrong file type or HEAD isn't the first block.  Exiting..."
        sys.exit(1337)
    hblocksize = struct.unpack('<I',f.read(4))[0]      #So this is the size of the header block, including the numbers before and after that tell you how big it is
    assert struct.unpack('<I',f.read(4))[0] == bsize   #So this is the close of the block that includes nothing but the information about what block is next
    
    #Now I can actually read the header:
    header_size = struct.unpack('<I',f.read(4))[0]

    #number of particles of each type in this file
    nfile = struct.unpack('<6I',f.read(24)) #Number of particles in this file

    masstable = struct.unpack('<6d',f.read(48))  #masses of the particle groups
        
    a = struct.unpack('<d',f.read(8))[0]        #expansion factor
    z = struct.unpack('<d',f.read(8))[0]        #redshift
    
    if "Redshift" in snap.attrs.keys():
        if snap.attrs['Redshift'] != z:
            msg = "The existing redshift for group /Snapshot{0:05} doesn't match that in the Gadget file.  Please specify the snapshot group manually.".format(snapnum)
            raise ValueError(msg)
    else:
        snap.attrs['Redshift'] = z
    
    if "ScaleFactor" in snap.attrs.keys():
        if snap.attrs['ScaleFactor'] != a:
            msg = "The existing scale factor for group /Snapshot{0:05} doesn't match that in the Gadget file.  Please specify the snapshot group manually".format(snapnum)
            raise ValueError(msg)
    else:
        snap.attrs['ScaleFactor'] = a

    flag_sfr = struct.unpack('<i',f.read(4))[0] #star formation included?
    flag_feed = struct.unpack('<i',f.read(4))[0] #feedback included?

    ntot = struct.unpack('<6i',f.read(24))      #total number of particles in the simulation (= nfile if numfiles == 1)
        
    flag_cool = struct.unpack('<i',f.read(4))[0]  #cooling included?
    numfiles = struct.unpack('<i',f.read(4))[0]   #number of files in each snapshot
    boxsize = struct.unpack('<d',f.read(8))[0] #Size of the box, if periodic
    omega0 = struct.unpack('<d',f.read(8))[0]  #matter density at z = 0
    omegaL = struct.unpack('<d',f.read(8))[0]  #vacuum energy density at z = 0
    h = struct.unpack('<d',f.read(8))[0] #hubble parameter in units of 100 km/s/Mpc
    flag_age = struct.unpack('<i',f.read(4))[0]  #stellar age included?
    flag_metals = struct.unpack('<i',f.read(4))[0]  #use metals?
    nhighword = struct.unpack('<6i',f.read(24))   #contains the most significant word of 64-bit particle numbers (if npart > 2^32)

    flag_entropy = struct.unpack('<i',f.read(4))[0] #entropy instead of thermal energy in initial conditions?

    f.seek(280,0)   #Moves to the end of the header (and block that tells you size of header)

    #Now I want to create the simulation group and the cosmology group (if they don't exist)
    try:
        simprops = irate.create_group("SimulationProperties")
        addprops = True
    except ValueError:
        #Then it already exists, so let's check that what I was going to put there matches
        simprops = irate['SimulationProperties']
        addprops = False
        try:
            msg = "\n"
            exitflag = False
            if boxsize != simprops.attrs['Boxsize']:
                msg = msg + "Box size from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_sfr != simprops.attrs['FlagSFR']:
                msg = msg + "Flag SFR from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_feed != simprops.attrs['FlagFeedback']:
                msg = msg + "Flag Feedback from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_cool != simprops.attrs['FlagCooling']:
                msg = msg + "Flag Cooling from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_age != simprops.attrs['FlagAge']:
                msg = msg + "Flag Age from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_metals != simprops.attrs['FlagMetals']:
                msg = msg + "Flag Metals from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if flag_entropy != simprops.attrs['FlagEntropyICs']:
                msg = msg + "Flag Entropy ICs from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if exitflag:
                raise ValueError(msg)
        except KeyError:
            raise KeyError("There is a group for simulation properties, but it's not filled with all the relevant values.  This is considered odd.")
    
    if addprops:
        simprops.attrs['Boxsize'] = boxsize
        simprops.attrs['FlagSFR'] = flag_sfr
        simprops.attrs['FlagFeedback'] = flag_feed
        simprops.attrs['FlagCooling'] = flag_cool
        simprops.attrs['FlagAge'] = flag_age
        simprops.attrs['FlagMetals'] = flag_metals
        simprops.attrs['FlagEntropyICs'] = flag_entropy
                
    #Now I'm done with the IRATE file, and instead I need to create groups inside the Snapshot group
    ngas = nfile[0]
    nhalo = nfile[1]
    ndisk = nfile[2]
    nbulge = nfile[3]
    nstar = nfile[4]
    nbndry = nfile[5]

    capbet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    try:
        pdata = snap.create_group('ParticleData')
        #Add units to pdata
        pdata.attrs['Positionunitname'] = lname
        pdata.attrs['Positionunitcgs'] = lunits
        pdata.attrs['Velocityunitname'] = vname
        pdata.attrs['Velocityunitcgs'] = vunits
        pdata.attrs['Massunitname'] = mname
        pdata.attrs['Massunitcgs'] = munits
    except ValueError:
        pdata = snap['ParticleData']
        #If 'ParticleData' already exists, check that the units that I'm adding match up (if it has units)
        try:
            msg = "\n"
            #Check that the units that are there match what I have
            exitflag = False
            if pdata.attrs['Positionunitname'] != lname or (pdata.attrs['Positionunitcgs'] != lunits).all():
                msg = msg + "Length units in existing file are different than those provided.\n"
                exitflag = True
            if pdata.attrs['Velocityunitname'] != vname or (pdata.attrs['Velocityunitcgs'] != vunits).all():
                msg = msg + "Velocity units in existing file are different than those provided.\n"
                exitflag = True
            if pdata.attrs['Massunitname'] != mname or (pdata.attrs['Massunitcgs'] != munits).all():
                msg = msg + "Mass units in existing file are different than those provided.\n"
                exitflag = True
            if exitflag:
                raise ValueError(msg)
        except KeyError:
            #add the units, since they're not there 
            pdata.attrs['Positionunitname'] = lname
            pdata.attrs['Positionunitcgs'] = lunits
            pdata.attrs['Velocityunitname'] = vname
            pdata.attrs['Velocityunitcgs'] = vunits
            pdata.attrs['Massunitname'] = mname
            pdata.attrs['Massunitcgs'] = munits

    exitflag = False
    msg = "\n"
    if ngas > 0:
        if t0_name[0] not in capbet:  t0_name = t0_name.capitalize()
        try:
            gas = pdata.create_group(t0_name)
            print "Saving gas data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t0_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save gas data.\n".format(snapnum,t0_name)
            exitflag = True
        
    if nhalo > 0:
        if t1_name[0] not in capbet:  t1_name = t1_name.capitalize()
        try:
            halo = pdata.create_group(t1_name)
            print "Saving halo data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t1_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save halo data.\n".format(snapnum,t1_name)
            exitflag = True
        
    if ndisk > 0:
        if t2_name[0] not in capbet:  t2_name = t2_name.capitalize()
        try:
            disk = pdata.create_group(t2_name)
            print "Saving disk data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t2_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save disk data.\n".format(snapnum,t2_name)
            exitflag = True
        
    if nbulge > 0:
        if t3_name[0] not in capbet:  t3_name = t3_name.capitalize()
        try:
            bulge = pdata.create_group(t3_name)
            print "Saving bulge data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t3_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save bulge data.\n".format(snapnum,t3_name)
            exitflag = True
        
    if nstar > 0:
        if t4_name[0] not in capbet:  t4_name = t4_name.capitalize()
        try:
            star = pdata.create_group(t4_name)
            print "Saving star data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t4_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save star data.\n".format(snapnum,t4_name)
            exitflag = True
        
    if nbndry > 0:
        if t5_name[0] not in capbet:  t5_name = t5_name.capitalize()
        try:
            bndry = pdata.create_group(t5_name)
            print "Saving boundary data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t5_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save boundary data.\n".format(snapnum,t5_name)
            exitflag = True
        
    if exitflag:
        raise ValueError(msg)
            
    posflag = False
    velflag = False
    idflag = False
    massflag = False
    
    while f.tell() < flen:
        #If I have this loop right, it'll check whether it's at the end of the file
        #If it's not, it'll read in an 8 byte block that includes a label and the size of the next block
        #Then, it'll go through and compare the labels to everything that's known, find where it goes, then read that block and save it to the appropriate tree
        bsize = struct.unpack('<I',f.read(4))
        label = f.read(4)
        btot = struct.unpack('<I',f.read(4))[0]
        assert struct.unpack('<I',f.read(4)) == bsize
        
        if label == 'POS ':
            posflag = True
            print "Reading coordinates for "+str(ngas+nhalo+ndisk+nbulge+nstar+nbndry)+" particles with "+str(fprec)+" bytes per float"
            coord_size = struct.unpack('<I',f.read(4))[0]

            if ngas > 0:    #Only try to do something for a group of particles if they exist
                #Read in the binary data and convert to the appropriate type and save in the appropriate place
                gas.create_dataset("Position",data=fromstring(f.read(3*fprec*ngas),dtype='f').reshape((-1,3)))
            if nhalo > 0:
                halo.create_dataset("Position",data=fromstring(f.read(3*fprec*nhalo),dtype='f').reshape((-1,3)))
            if ndisk > 0:
                disk.create_dataset("Position",data=fromstring(f.read(3*fprec*ndisk),dtype='f').reshape((-1,3)))
            #print "Read coordinates for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge.create_dataset("Position",data=fromstring(f.read(3*fprec*nbulge),dtype='f').reshape((-1,3)))
            if nstar > 0:
                star.create_dataset("Position",data=fromstring(f.read(3*fprec*nstar),dtype='f').reshape((-1,3)))
            if nbndry > 0:
                bndry.create_dataset("Position",data=fromstring(f.read(3*fprec*nbndry),dtype='f').reshape((-1,3)))
        
            #And read the size of the coordinate block again.
            if struct.unpack('<I',f.read(4))[0] != coord_size:
                raise IOError("The block size at the end of the coordinate block doesn't match that at the beginning: "+str(coord_size)+". There is something wrong with the file, or my reading of it.")
            continue
                
        elif label == 'VEL ':
            velflag = True
            vel_size = struct.unpack('<I',f.read(4))[0]
            print "Reading velocities for "+str(ngas+nhalo+ndisk+nbulge+nstar+nbndry)+" particles with  "+str(fprec)+" bytes per float"
            
            if ngas > 0:    #Only try to do something for a group of particles if they exist
                gas.create_dataset("Velocity",data=fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
            if nhalo > 0:
                halo.create_dataset("Velocity",data=fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
            if ndisk > 0:
                disk.create_dataset("Velocity",data=fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
            #print "Read velocities for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge.create_dataset("Velocity",data=fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
            if nstar > 0:
                star.create_dataset("Velocity",data=fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
            if nbndry > 0:
                bndry.create_dataset("Velocity",data=fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))

            if struct.unpack('<I',f.read(4))[0] != vel_size:   #And read the size of the block again.
                raise IOError("The block size at the end of the velocity block doesn't match that at the beginning: "+str(vel_size)+". There is something wrong with the file, or my reading of it.")
            continue
                
        elif label == 'ID  ':
            idflag = True
            id_size = struct.unpack('<I',f.read(4))[0]
            print "Reading IDs for "+str(ngas+nhalo+ndisk+nbulge+nstar+nbndry)+" particles with "+str(fprec)+" bytes per integer"

            if ngas > 0:
                gas.create_dataset("ID",data=fromstring(f.read(4*ngas),dtype='I'))
            if nhalo > 0:
                halo.create_dataset("ID",data=fromstring(f.read(4*nhalo),dtype='I'))
            if ndisk > 0:
                disk.create_dataset("ID",data=fromstring(f.read(4*ndisk),dtype='I'))
            #print "Read IDs for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge.create_dataset("ID",data=fromstring(f.read(4*nbulge),dtype='I'))
            if nstar > 0:
                star.create_dataset("ID",data=fromstring(f.read(4*nstar),dtype='I'))
            if nbndry > 0:
                bndry.create_dataset("ID",data=fromstring(f.read(4*nbndry),dtype='I'))

            if struct.unpack('<I',f.read(4))[0] != id_size:   #And read the size of the block again.
                raise IOError("The block size at the end of the IDs block doesn't match that at the beginning: "+str(id_size)+".  There is something wrong with the file, or my reading of it.")
            continue
                
        elif label == 'MASS':
            massflag = True
            mass_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0 and masstable[0] == 0:    #There are particles in the group, but their masses aren't in the header (so they must be in the file)
                print "Reading variable masses for gas group: "+str(ngas)+" particles with "+str(fprec)+" bytes per float"
                gas.create_dataset("Mass",data=fromstring(f.read(fprec*ngas),dtype='f'))
            #Otherwise, there are either no particles in the group (in which case I don't have to worry about it) or the mass is in the header
            elif ngas > 0 and masstable[0] != 0:    #Then the mass is in the header
                marray = empty(ngas)
                marray.fill(masstable[0])
                gas.create_dataset("Mass",data=marray)
                
            if nhalo > 0 and masstable[1] == 0:
                print "Reading variable masses for halo group: "+str(nhalo)+" particles with "+str(fprec)+" bytes per float"
                halo.create_dataset("Mass",data=fromstring(f.read(fprec*nhalo),dtype='f'))
            elif nhalo > 0 and masstable[1] > 0:
                    marray = empty(nhalo)
                    marray.fill(masstable[1])
                    halo.create_dataset("Mass",data=marray)
                    
            if ndisk > 0 and masstable[2] == 0:
                print "Reading variable masses for disk group: "+str(ndisk)+" particles with "+str(fprec)+" bytes per float"
                disk.create_dataset("Mass",data=fromstring(f.read(fprec*ndisk),dtype='f'))
            elif ndisk > 0 and masstable[2] > 0:
                    marray = empty(ndisk)
                    marray.fill(masstable[2])
                    disk.create_dataset("Mass",data=marray)
                
            if nbulge > 0 and masstable[3] == 0:
                print "Reading variable masses for bulge group: "+str(nbulge)+" particles with "+str(fprec)+" bytes  per float"
                bulge.create_dataset("Mass",data=fromstring(f.read(fprec*nbulge),dtype='f'))
            elif nbulge > 0 and masstable[3] > 0:
                    marray = empty(nbulge)
                    marray.fill(masstable[3])
                    bulge.create_dataset("Mass",data=marray)
                
            if nstar > 0 and masstable[4] == 0:
                print "Reading variable masses for star group: "+str(nstar)+" particles with "+str(fprec)+" bytes per float"
                star.create_dataset("Mass",data=fromstring(f.read(fprec*nstar),dtype='f'))
            elif nstar > 0 and masstable[4] > 0:
                    marray = empty(nstar)
                    marray.fill(masstable[4])
                    star.create_dataset("Mass",data=marray)                
                
            if nbndry > 0 and masstable[5] == 0:
                print "Reading variable masses for boundary group: "+str(nbndry)+" particles with "+str(fprec)+" bytes per float"
                bndry.create_dataset("Mass",data=fromstring(f.read(fprec*nbndry),dtype='f'))
            elif nbndry > 0 and masstable[5] > 0:
                    marray = empty(nbndry)
                    marray.fill(masstable[5])
                    bndry.create_dataset("Mass",data=marray)                
                    
            try:    
                del marray      #If there are no masses in the mass table, marray will have never been defined
            except NameError:
                pass
                
            if struct.unpack('<I',f.read(4))[0] != mass_size:   #And read the size of the block again.
                raise IOError("The block size at the end of the mass block doesn't match that at the beginning: "+str(mass_size)+". There is something wrong with the file, or my reading of it.")
            continue
                
        elif label == 'U   ':     #Then it's internal energy, and I should do that
            u_size = struct.unpack('<I',f.read(4))[0]
            print "Reading gas internal energy for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            gas.create_dataset("InternalEnergy",data=fromstring(f.read(fprec*ngas),dtype='f'))
            if struct.unpack('<I',f.read(4))[0] != u_size:
                raise IOError("The block size at the end of the internal energy block doesn't match that at the beginning: "+str(u_size)+". There is something wrong with the file, or my reading of it.")
            continue
        
        elif label == "RHO ":
            print "Reading density for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            rho_size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset("Density",data=fromstring(f.read(fprec*ngas),dtype='f'))  
            if struct.unpack('<I',f.read(4))[0] != rho_size:
                raise IOError("The block size at the end of the density block doesn't match that at the beginning: "+str(rho_size)+". There is something wrong with the file, or my reading of it.")
            continue        #These continues are probably unnecessary, but better safe (and faster) then sorry
            
        elif label == "HSML":
            print "Reading smoothings lengths for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            hsml_size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset("SmoothingLength",data=fromstring(f.read(fprec*ngas),dtype='f'))       
            if struct.unpack('<I',f.read(4))[0] != hsml_size:
                raise IOError("The block size at the end of the HSML block doesn't match that at the beginning: "+str(hsml_size)+". There is something wrong with the file, or my reading of it.")
            continue
            
        #Now check if it's a standard Makefile enabled block:
        elif label == "POT ":
            print "Reading gravitational potentials for "+str(ngas+nhalo+ndisk+nbulge+nstar+nbndry)+" particles with "+str(fprec)+" bytes per float"
            phi_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0:
                gas.create_dataset("Potential",data=fromstring(f.read(fprec*ngas),dtype='f'))     
            if nhalo > 0:
                halo.create_dataset("Potential",data=fromstring(f.read(fprec*nhalo),dtype='f'))
            if ndisk > 0:
                disk.create_dataset("Potential",data=fromstring(f.read(fprec*ndisk),dtype='f'))
            #print "Read gravitational potentials for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge.create_dataset("Potential",data=fromstring(f.read(fprec*nbulge),dtype='f'))
            if nstar > 0:
                star.create_dataset("Potential",data=fromstring(f.read(fprec*nstar),dtype='f'))
            if nbndry > 0:
                bndry.create_dataset("Potential",data=fromstring(f.read(fprec*nbndry),dtype='f'))
            
            if struct.unpack('<I',f.read(4))[0] != phi_size:
                raise IOError("The block size at the end of the gravitational potential block doesn't match that at the beginning: "+str(phi_size)+".  There is something wrong with the file, or my reading of it.")
            continue
            
        elif label == "ACCE":
            print "Reading accelerations for "+str(ngas+nhalo+ndisk+nbulge+nstar+nbndry)+" particles with "+str(fprec)+" bytes per integer"
            accel_size = struct.unpack('<I',f.read(4))[0]
            
            if ngas > 0:
                gas.create_dataset("Acceleration",data=fromstring(f.read(3*fprec*ngas),dtype='f').reshape((-1,3)))
            if nhalo > 0:
                halo.create_dataset("Acceleration",data=fromstring(f.read(3*fprec*nhalo),dtype='f').reshape((-1,3)))
            if ndisk > 0:
                disk.create_dataset("Acceleration",data=fromstring(f.read(3*fprec*ndisk),dtype='f').reshape((-1,3)))
            #print "Read accelerations for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))
            if nbulge > 0:
                bulge.create_dataset("Acceleration",data=fromstring(f.read(3*fprec*nbulge),dtype='f').reshape((-1,3)))
            if nstar > 0:
                star.create_dataset("Acceleration",data=fromstring(f.read(3*fprec*nstar),dtype='f').reshape((-1,3)))
            if nbndry > 0:
                bndry.create_dataset("Acceleration",data=fromstring(f.read(3*frec*nbndry),dtype='f').reshape((-1,3)))
            
            if struct.unpack('<I',f.read(4))[0] != accel_size:
                raise IOError("The block size at the end of the acceleration block doesn't match that at the beginning: "+str(accel_size)+". There is something wrong with the file, or my reading of it.")
            continue
            
        elif label == "ENDT":
            print "Reading rate of change of entropy for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            dsdt_size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset("RateofChangeofEntropy",data=fromstring(f.read(fprec*ngas),dtype='f'))
            if struct.unpack('<I',f.read(4))[0] != dsdt_size:
                raise IOError("The block size at the end of the entropy block doesn't match that at the beginning: "+str(dsdt_size)+". There is something wrong with the file, or my reading of it.")
            continue
            
        elif label == "TSTP":
            print "Reading timesteps for "+str(ngas+nhalo+ndisk+nbulge+nstar+nbndry)+" particles with "+str(fprec)+" bytes per integer"
            timestep_size = struct.unpack('<I',f.read(4))[0]
        
            if ngas > 0:
                gas.create_dataset("TimeStep",data=fromstring(f.read(fprec*ngas),dtype='f'))
            if nhalo > 0:
                halo.create_dataset("TimeStep",data=fromstring(f.read(fprec*nhalo),dtype='f'))
            if ndisk > 0:
                disk.create_dataset("TimeStep",data=fromstring(f.read(fprec*ndisk),dtype='f'))     
            #print "Read timesteps for {0} of {1} particles".format(ngas+nhalo+ndisk,sum(nfile))    
            if nbulge > 0:
                bulge.create_dataset("TimeStep",data=fromstring(f.read(fprec*nbulge),dtype='f')) 
            if nstar > 0:
                star.create_dataset("TimeStep",data=fromstring(f.read(fprec*nstar),dtype='f'))
            if nbndry > 0:
                bndry.create_dataset("TimeStep",data=fromstring(f.read(fprec*nbndry),dtype='f'))
                                
            if struct.unpack('<I',f.read(4))[0] != timestep_size:
                raise IOError("The block size at the end of the timestep block doesn't match that at the beginning: "+str(timesteps_size)+". There is something wrong with the file, or my reading of it.")
            continue
        
        #Ok, so if I'm here, it's a nonstandard block.  How to handle those....hmm
        #Well, I'm not going to bother renaming things; rather, I'll just use the strings as names
        #The primary difficulty lies in determining what type of particle the various blocks belong to...
        #Certain blocks I know belong to gas and/or stars, others it's not obvious
        #If a block is unrecognized, I'm going to give the option to skip or exit.
        elif label == "NE  ":   #A gas only thing
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
        
        elif label == "NH  ":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
                        
        elif label == "SFR ":   #A gas only block
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
                
        elif label == "AGE ":   #Stars only block
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            star.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*nstar),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
                        
        elif label == "Z   ":   #Gas and stars
            print "Reading "+label+" for "+str(ngas+nstar)+" (gas+stars) particles with "+str(fprec)+" bytes per float ("+str(zfields)+" fields per particle)"
            size = struct.unpack('<I',f.read(4))[0]
            if ngas > 0:  gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(zfields*fprec*ngas),dtype='f').reshape((-1,3)))
            if nstar > 0:  star.create_dataset(label.rstrip(' '),data=fromstring(f.read(zfields*fprec*nstar),dtype='f').reshape((-1,3)))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")    
            continue
        
        elif label == "BFLD":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
        
        elif label == "DBDT":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
        
        elif label == "DIVB":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")  
            continue
                
        elif label == "ABVC":  
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*gas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
                
        elif label == "COOR":    
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
        
        elif label == "CONR":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue
            
        elif label == "BFSM":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue

        elif label == "DENN":
            print "Reading "+label+" for "+str(ngas)+" (gas) particles with "+str(fprec)+" bytes per float"
            size = struct.unpack('<I',f.read(4))[0]
            gas.create_dataset(label.rstrip(' '),data=fromstring(f.read(fprec*ngas),dtype='f'))    
            if struct.unpack('<I',f.read(4))[0] != size:
                raise IOError("The block size at the end of the "+label.rstrip(' ')+" block doesn't match that at the beginning: "+str(size)+". There is something wrong with the file, or my reading of it.")
            continue

        else:
            cont = raw_input("Block labeled '"+label+"' isn't recognized by this script.  Press enter to skip it or type 'exit' to exit. ")
            if len(cont) > 0:
                if massflag == False:
                    #Then I need to fill in mass blocks for those particles that have their masses defined in the header before exiting because the mass block hasn't come up yet or doesn't exist.
                    if ngas > 0 and masstable[0] > 0:    #There are particles in the group, and their masses are in the header (so I have to fill in a variable block)
                            marray = empty(ngas)
                            marray.fill(masstable[0])
                            gas.create_dataset("Mass",data=marray)
                    if nhalo > 0 and masstable[1] > 0:
                            marray = empty(nhalo)
                            marray.fill(masstable[1])
                            halo.create_dataset("Mass",data=marray)
                    if ndisk > 0 and masstable[2] > 0:
                            marray = empty(ndisk)
                            marray.fill(masstable[2])
                            disk.create_dataset("Mass",data=marray)
                    if nbulge > 0 and masstable[3] > 0:
                            marray = empty(nbulge)
                            marray.fill(masstable[3])
                            bulge.create_dataset("Mass",data=marray)
                    if nstar > 0 and masstable[4] > 0:
                            marray = empty(nstar)
                            marray.fill(masstable[4])
                            star.create_dataset("Mass",data=marray)
                    if nbndry > 0 and masstable[5] > 0:
                            marray = empty(nbndry)
                            marray.fill(masstable[5])
                            bndry.create_dataset("Mass",data=marray)
                    try:    
                        del marray      #If there are no masses in the mass table, marray will have never been defined
                    except NameError:
                        pass
                f.close()
                irate.close()
                print "All blocks up to "+label+" from "+inname+" have been saved to "+outname+"."
                sys.exit(1)
            else:
                f.seek(btot,1)
                continue
    
    #Now I need to fill in mass blocks for those particles that have their masses defined in the header
    if massflag == False:   #Then mass wasn't anywhere in the file, so I need to create them for all the groups
        if ngas > 0 and masstable[0] > 0:    #There are particles in the group, and their masses are in the header (so I have to fill in a variable block)
                marray = empty(ngas)
                marray.fill(masstable[0])
                gas.create_dataset("Mass",data=marray)
        if nhalo > 0 and masstable[1] > 0:
                marray = empty(nhalo)
                marray.fill(masstable[1])
                halo.create_dataset("Mass",data=marray)
        if ndisk > 0 and masstable[2] > 0:
                marray = empty(ndisk)
                marray.fill(masstable[2])
                disk.create_dataset("Mass",data=marray)
        if nbulge > 0 and masstable[3] > 0:
                marray = empty(nbulge)
                marray.fill(masstable[3])
                bulge.create_dataset("Mass",data=marray)
        if nstar > 0 and masstable[4] > 0:
                marray = empty(nstar)
                marray.fill(masstable[4])
                star.create_dataset("Mass",data=marray)
        if nbndry > 0 and masstable[5] > 0:
                marray = empty(nbndry)
                marray.fill(masstable[5])
                bndry.create_dataset("Mass",data=marray)
        try:    
            del marray      #If there are no masses in the mass table, marray will have never been defined
        except NameError:
            pass

    f.close()
    irate.close()
    msg = ""
    if posflag == False:
        msg = msg + "There was no position block identified in the file; therefore, "+outname+" doesn't conform to the IRATE format specifications.\n"
    elif velflag == False:
        msg = msg +  "There was no velocity block identified in the file; therefore, "+outname+" doesn't conform to the IRATE format specifications.\n"
    elif idflag == False:
        msg = msg +  "There was no particle ID block identified in the file; therefore, "+outname+" doesn't conform to the IRATE format specifications.\n"
    else:
        msg = msg + "Finished reading type 2 file "+inname+" and saved it to "+outname
    print msg


def irate_to_gbin(inname,outname,snapnum):
    """
    Converts a single snapshot in an IRATE format file into a SnapFormat = 1
    Gadget binary file.  If there are groups with "Star" in the name, they're
    assumed to contain star particles and will be placed in Gadget group 4;
    likewise, if there are groups with "Gas" in the name, their particles will
    be placed in Gadget group 0.  All other particles will be placed in Gadget
    group 5.
    
    :param inname:  
        The input IRATE format file.
    :param outname:  
        The name of the output Gadget file
    :param int snapnum:  
        The integer identifying where the data is stored; that is,
        particle data is expected to be under '/Snapshot{snapnum}/ParticleData.
    """
    import h5py,sys,os
    from numpy import empty,append
    from struct import pack
    from .core import check_version
    
    try:
        snapnum = int(snapnum)
    except ValueError:
        raise ValueError("The number used for the snapshot is not an integer.")
    
    irate = h5py.File(inname,'r')
    
    try:
        check_version(irate,update=False)
    except ValueError,e:
        print "\nWARNING:  ",e,"\n" 
    
    #Find all the data
    try:
        snap = irate['Snapshot{0:05}'.format(snapnum)]
        pdata = snap['ParticleData']
    except KeyError:
        print "There is no group /Snapshot/{0:05}/ParticleData.  Please check your file format and the snapshot number you provided and try again.".format(snapnum)
        sys.exit(1337)
        
    dpos = empty(0,dtype="float32").reshape((-1,3))
    dvel = empty(0,dtype="float32").reshape((-1,3))
    dID = empty(0,dtype="I")
    dmass = empty(0,dtype="float32")
    
    gpos = empty(0,dtype="float32").reshape((-1,3))
    gvel = empty(0,dtype="float32").reshape((-1,3))
    gID = empty(0,dtype="I")
    gmass = empty(0,dtype="float32")
    u = empty(0,dtype="float32")
    rho = empty(0,dtype="float32")
    hsml = empty(0,dtype="float32")    
        
    spos = empty(0,dtype="float32").reshape((-1,3))
    svel = empty(0,dtype="float32").reshape((-1,3))
    sID = empty(0,dtype="I")
    smass = empty(0,dtype="float32")
    
    for key in pdata.keys():
        if "Gas" in key:
            print "Saving data under /Snapshot{0:05}/ParticleData/{1} in the gas group".format(snapnum,key)
            gpos = append(gpos,pdata[key]['Position'][:],axis=0)
            gvel = append(gvel,pdata[key]['Velocity'][:],axis=0)
            gID = append(gID,pdata[key]['ID'][:])
            gmass = append(gmass,pdata[key]['Mass'][:])
            u = append(u,pdata[key]['InternalEnergy'][:])
            rho = append(rho,pdata[key]['Density'][:])
            hsml = append(hsml,pdata[key]['SmoothingLength'][:])
        elif "Star" in key:
            print "Saving data under /Snapshot{0:05}/ParticleData/{1} in the star group".format(snapnum,key)
            spos = append(spos,pdata[key]['Position'][:],axis=0)
            svel = append(svel,pdata[key]['Velocity'][:],axis=0)
            sID = append(sID,pdata[key]['ID'][:])
            smass = append(smass,pdata[key]['Mass'][:])
        else:
            print "Saving data under /Snapshot{0:05}/ParticleData/{1} in the boundary group".format(snapnum,key)
            dpos = append(dpos,pdata['Dark'][key]['Position'][:],axis=0)
            dvel = append(dvel,pdata['Dark'][key]['Velocity'][:],axis=0)
            dID = append(dID,pdata['Dark'][key]['ID'][:])
            dmass = append(dmass,pdata['Dark'][key]['Mass'][:])

    ndark = dpos.shape[0]
    dpos = dpos.astype("f")
    dvel = dvel.astype("f")
    dID = dID.astype("I")
    dmass = dmass.astype("f")

    ngas = gpos.shape[0]
    gpos = gpos.astype("f")
    gvel = gvel.astype("f")
    gID = gID.astype('I')
    gmass = gmass.astype("f")
    u = u.astype("f")
    rho = rho.astype("f")
    hsml = hsml.astype("f")
       
    nstar = spos.shape[0]
    spos = spos.astype("f")
    svel = svel.astype("f")
    sID = sID.astype("I")
    smass = smass.astype("f")
                
    #Ok, now I have all the data--just need to write it out appropriately, starting with the header
    if os.path.isfile(outname):
        print "The file you've chosen to output to exists already.  Please choose a different outname."
        sys.exit(1337)
        
    simprops = irate['SimulationProperties'].attrs
    cosmo = irate['Cosmology'].attrs
        
    out = open(outname,'w')
    out.write(pack('<I',256))
    
    out.write(pack('<6I',ngas,0,0,0,nstar,ndark))
    out.write(pack('<6d',0,0,0,0,0,0))  #just going to include the mass for each particle individually
    out.write(pack('<d',snap.attrs['ScaleFactor']))
    out.write(pack('<d',snap.attrs['Redshift']))
    out.write(pack('<i',simprops['FlagSFR']))
    out.write(pack('<i',simprops['FlagFeedback']))
    out.write(pack('<6i',ngas,0,0,0,nstar,ndark))
    out.write(pack('<i',simprops['FlagCooling']))
    out.write(pack('<i',1))
    out.write(pack('<d',simprops['Boxsize']))
    out.write(pack('<d',cosmo['OmegaMatter']))
    out.write(pack('<d',cosmo['OmegaLambda']))
    out.write(pack('<d',cosmo['HubbleParam']))
    out.write(pack('<i',simprops['FlagAge']))
    out.write(pack('<i',simprops['FlagMetals']))
    out.write(pack('<6i',0,0,0,0,0,0))
    out.write(pack('<i',simprops['FlagEntropyICs']))
    
    left = 260 - out.tell()
    assert left > 0
    for i in range(left):
        out.write(pack('<x'))
    out.write(pack('<I',256))
    assert out.tell() == 264
    
    irate.close()
    
    #Now to do the rest of the file
    ntot = sum([ngas,nstar,ndark])
    vec_size = pack('<I',12*ntot)
    scal_size = pack('<I',4*ntot)
    gas_size = pack('<I',4*ngas)
    
    out.write(vec_size)
    if gas: out.write(gpos.tostring())
    if star: out.write(spos.tostring())
    if dark: out.write(dpos.tostring())
    out.write(vec_size)
    
    out.write(vec_size)
    if gas: out.write(gvel.tostring())
    if star: out.write(svel.tostring())
    if dark: out.write(dvel.tostring())
    out.write(vec_size)
    
    out.write(scal_size)
    if gas: out.write(gID.tostring())
    if star: out.write(sID.tostring())
    if dark: out.write(dID.tostring())
    out.write(scal_size)
    
    out.write(scal_size)
    if gas: out.write(gmass.tostring())
    if star: out.write(smass.tostring())
    if dark: out.write(dmass.tostring())
    out.write(scal_size)
    
    if gas:
        out.write(gas_size)
        out.write(u.tostring())
        out.write(gas_size)
        
        out.write(gas_size)
        out.write(rho.tostring())
        out.write(gas_size)
        
        out.write(gas_size)
        out.write(hsml.tostring())
        out.write(gas_size)
        
    out.close()
    
    print "Finished writing {0} gas particles, {1} star particles, and {2} dark particles to {3}".format(ngas,nstar,ndark,outname)
    

def gadget_hdf5_to_irate(inname,outname,snapnum,t0_name="Gas",t1_name="Dark_Halo",
                         t2_name="Dark_Disk",t3_name="Dark_Bulge",t4_name="Star",
                         t5_name="Dark_Boundary",s8=None,ns=None,omegaB=None,
                         lname="comoving Mpc/h",lunits=[3.08568025e24,-1,1],
                         vname="(km/s)*sqrt(a)",vunits=[1e5,0,0.5],
                         mname="1e10 M_sun/h",munits=[1.98892e43,-1,0]):
    """
    Transforms Gadget type 3 (HDF5) snapshots into a format that meets the
    IRATE specifications.  This will automatically check for Makefile
    enabled blocks.
        
    :param inname:  
        Gadget type 3 snapshot to convert to IRATE
    :param outname:  
        IRATE file to output
    :param int snapnum:  
        The number to add to 'Snapshot' that becomes the name of
        the group that particle data is added to.
    :param #name:  
        Name of group that particles of type # are given
    :param float s8: 
        sigma_8, for the purposes of adding it to the Cosmology group
    :param float ns: 
        n_s, for the purposes of adding it to the Cosmology group
    :param float omegaB:
        omegaB, for the purposes of adding it to the Cosmology group
    :param ___name: 
        A human readable string that defines the units for either
        length (l), velocity (v), or mass (m)
    :param ___units: 
        A three-element array.  The first entry defines the
        conversion factor to convert either length (l), velocity (v),
        or mass (m) to CGS units.  The second element is the exponent on the
        reduced Hubble Parameter that appears in that unit, and the third
        is the exponent on the scale factor that appears in that unit. 
        
    # refers to the same names as Gadget2:
    
    * 0 = gas particles
    * 1 = halo particles
    * 2 = disk particles
    * 3 = bulge particles
    * 4 = star particles
    * 5 = bndry particles
    """
    import h5py,os,sys
    from numpy import empty
    from .core import add_cosmology,check_version
    print "Opening GADGET format HDF5 file"+inname
    
    fin = h5py.File(inname,'r')
    inhead = fin['Header']
    #Grab the cosmology to check that it's the same
    omegaM = inhead.attrs['Omega0']
    omegaL = inhead.attrs['OmegaLambda']
    hubble = inhead.attrs['HubbleParam']

    
    if os.path.isfile(outname):
        irate = h5py.File(outname,'a')
        print "Opening {0} to add data to it.".format(outname)
        
        try:
            check_version(irate,update=False)
        except ValueError,e:
            print "\nWARNING:  ",e,"\n" 
        
        if "Cosmology" not in irate.keys():
            add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=True)
        else:
            try:
                add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=False)
            except KeyError:    #Then ns, s8, or omegaB was passed, but wasn't in the file before (in which case I want to add it)
                add_cosmology(outname,s8=s8,ns=ns,omegaB=omegaB,update=True)
    else:
        print "Creating new IRATE file {0}".format(outname)
        irate = h5py.File(outname,'w')
        check_version(irate,update=True)
        add_cosmology(outname,omegaM=omegaM,omegaL=omegaL,h=hubble,s8=s8,ns=ns,omegaB=omegaB,update=True)


    #Create the simulation properties group in the output file
    try:
        simprops = irate.create_group("SimulationProperties")
        addprops = True
    except ValueError:
        #Then it already exists, so let's check that what I was going to put there matches
        simprops = irate['SimulationProperties']
        addprops = False
        try:
            msg = "\n"
            exitflag = False
            if inhead.attrs['BoxSize'] != simprops.attrs['Boxsize']:
                msg = msg + "Box size from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if inhead.attrs['Flag_Sfr'] != simprops.attrs['FlagSFR']:
                msg = msg + "Flag SFR from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if inhead.attrs['Flag_Feedback'] != simprops.attrs['FlagFeedback']:
                msg = msg + "Flag Feedback from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if inhead.attrs['Flag_Cooling'] != simprops.attrs['FlagCooling']:
                msg = msg + "Flag Cooling from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if inhead.attrs['Flag_StellarAge'] != simprops.attrs['FlagAge']:
                msg = msg + "Flag Age from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if inhead.attrs['Flag_Metals'] != simprops.attrs['FlagMetals']:
                msg = msg + "Flag Metals from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if (inhead.attrs['Flag_Entropy_ICs'] != simprops.attrs['FlagEntropyICs']).all():
                msg = msg + "Flag Entropy ICs from {0} doesn't match that in {1}.\n".format(inname,outname)
                exitflag = True
            if exitflag:
                raise ValueError(msg)
        except KeyError:
            raise KeyError("There is a group for simulation properties, but it's not filled with all the relevant values.  This is considered odd.")
            
    if addprops:
        simprops.attrs['Boxsize'] = inhead.attrs['BoxSize']
        simprops.attrs['FlagSFR'] = inhead.attrs['Flag_Sfr']
        simprops.attrs['FlagFeedback'] = inhead.attrs['Flag_Feedback']
        simprops.attrs['FlagCooling'] = inhead.attrs['Flag_Cooling']
        simprops.attrs['FlagAge'] = inhead.attrs['Flag_StellarAge']
        simprops.attrs['FlagMetals'] = inhead.attrs['Flag_Metals']
        simprops.attrs['FlagEntropyICs'] = inhead.attrs['Flag_Entropy_ICs']

    masses = inhead.attrs['MassTable']
    
    #Create the tree structure of the output file
    nfile = inhead.attrs['NumPart_ThisFile']
    ngas = nfile[0]
    nhalo = nfile[1]
    ndisk = nfile[2]
    nbulge = nfile[3]
    nstar = nfile[4]
    nbndry = nfile[5]
        
    try:
        snap = irate.create_group("Snapshot"+str(snapnum))
        print "Created new group for Snapshot "+str(snapnum)
    except ValueError:
        snap = irate['Snapshot'+str(snapnum)]
        print "Adding data to existing group Snapshot"+str(snapnum)

    capbet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    try:
        pdata = snap.create_group('ParticleData')
        #Add units to pdata
        pdata.attrs['Positionunitname'] = lname
        pdata.attrs['Positionunitcgs'] = lunits
        pdata.attrs['Velocityunitname'] = vname
        pdata.attrs['Velocityunitcgs'] = vunits
        pdata.attrs['Massunitname'] = mname
        pdata.attrs['Massunitcgs'] = munits
    except ValueError:
        pdata = snap['ParticleData']
        #If 'ParticleData' already exists, check that the units that I'm adding match up (if it has units)
        try:
            #Check that the units that are there match what I have
            msg = "\n"
            exitflag = False
            if pdata.attrs['Positionunitname'] != lname or (pdata.attrs['Positionunitcgs'] != lunits).all():
                msg = msg + "Length units in existing file are different than those provided.\n"
                exitflag = True
            if pdata.attrs['Velocityunitname'] != vname or (pdata.attrs['Velocityunitcgs'] != vunits).all():
                msg = msg + "Velocity units in existing file are different than those provided.\n"
                exitflag = True
            if pdata.attrs['Massunitname'] != mname or (pdata.attrs['Massunitcgs'] != munits).all():
                msg = msg + "Mass units in existing file are different than those provided.\n"
                exitflag = True
            if exitflag:
                raise ValueError(msg)
        except KeyError:
            #add the units, since they're not there 
            pdata.attrs['Positionunitname'] = lname
            pdata.attrs['Positionunitcgs'] = lunits
            pdata.attrs['Velocityunitname'] = vname
            pdata.attrs['Velocityunitcgs'] = vunits
            pdata.attrs['Massunitname'] = mname
            pdata.attrs['Massunitcgs'] = munits
    
    exitflag = False
    if ngas > 0:
        if t0_name[0] not in capbet:  t0_name = t0_name.capitalize()
        try:
            gas = pdata.create_group(t0_name)
            print "Saving gas data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t0_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save gas data.\n".format(snapnum,t0_name)
            exitflag = True
        
    if nhalo > 0:
        if t1_name[0] not in capbet:  t1_name = t1_name.capitalize()
        try:
            halo = pdata.create_group(t1_name)
            print "Saving halo data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t1_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save halo data.\n".format(snapnum,t1_name)
            exitflag = True
        
    if ndisk > 0:
        if t2_name[0] not in capbet:  t2_name = t2_name.capitalize()
        try:
            disk = pdata.create_group(t2_name)
            print "Saving disk data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t2_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save disk data.\n".format(snapnum,t2_name)
            exitflag = True
        
    if nbulge > 0:
        if t3_name[0] not in capbet:  t3_name = t3_name.capitalize()
        try:
            bulge = pdata.create_group(t3_name)
            print "Saving bulge data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t3_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save bulge data.\n".format(snapnum,t3_name)
            exitflag = True
        
    if nstar > 0:
        if t4_name[0] not in capbet:  t4_name = t4_name.capitalize()
        try:
            star = pdata.create_group(t4_name)
            print "Saving star data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t4_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save star data.\n".format(snapnum,t4_name)
            exitflag = True
        
    if nbndry > 0:
        if t5_name[0] not in capbet:  t5_name = t5_name.capitalize()
        try:
            bndry = pdata.create_group(t5_name)
            print "Saving boundary data under /Snapshot{0:05}/ParticleData/{1}".format(snapnum,t5_name)
        except ValueError:
            msg = msg + "The group /Snapshot{0:05}/ParticleData/{1} already exists. Please specify a different location to save boundary data.\n".format(snapnum,t5_name)
            exitflag = True
        
    if exitflag:
        raise ValueError(msg)   
            
    if ngas > 0:
        path = fin['PartType0']
        for block in path.keys():
            if block == 'Coordinates':
                gas.create_dataset('Position',data=path[block])
            elif block == 'Velocities':
                gas.create_dataset('Velocity',data=path[block])
            elif block == 'ParticleIDs':
                gas.create_dataset('ID',data=path[block])
            else:            
                gas.create_dataset(block,data=path[block])
        #If there's not currently an array for the mass, I need to make one
        if 'Mass' not in path.keys():
            marray = empty(nfile[0])
            marray.fill(masses[0])
            gas.create_dataset('Mass',data=marray)
            del marray
    
    if nhalo > 0:
        path = fin['PartType1']
        for block in path.keys():
            if block == 'Coordinates':
                halo.create_dataset('Position',data=path[block])
            elif block == 'Velocities':
                halo.create_dataset('Velocity',data=path[block])
            elif block == 'ParticleIDs':
                halo.create_dataset('ID',data=path[block])
            else:            
                halo.create_dataset(block,data=path[block])
        #If there's not currently an array for the mass, I need to make one
        if 'Mass' not in path.keys():
            marray = empty(nfile[1])
            marray.fill(masses[1])
            halo.create_dataset('Mass',data=marray)
            del marray
            
    if ndisk > 0:
        path = fin['PartType2']
        for block in path.keys():
            if block == 'Coordinates':
                disk.create_dataset('Position',data=path[block])
            elif block == 'Velocities':
                disk.create_dataset('Velocity',data=path[block])
            elif block == 'ParticleIDs':
                disk.create_dataset('ID',data=path[block])
            else:            
                disk.create_dataset(block,data=path[block])
        #If there's not currently an array for the mass, I need to make one
        if 'Mass' not in path.keys():
            marray = empty(nfile[2])
            marray.fill(masses[2])
            disk.create_dataset('Mass',data=marray)
            del marray
            
    if nbulge > 0:
        path = fin['PartType3']
        for block in path.keys():
            if block == 'Coordinates':
                bulge.create_dataset('Position',data=path[block])
            elif block == 'Velocities':
                bulge.create_dataset('Velocity',data=path[block])
            elif block == 'ParticleIDs':
                bulge.create_dataset('ID',data=path[block])
            else:            
                bulge.create_dataset(block,data=path[block])
        #If there's not currently an array for the mass, I need to make one
        if 'Mass' not in path.keys():
            marray = empty(nfile[3])
            marray.fill(masses[3])
            bulge.create_dataset('Mass',data=marray)
            del marray
            
    if nstar > 0:
        path = fin['PartType4']
        for block in path.keys():
            if block == 'Coordinates':
                star.create_dataset('Position',data=path[block])
            elif block == 'Velocities':
                star.create_dataset('Velocity',data=path[block])
            elif block == 'ParticleIDs':
                star.create_dataset('ID',data=path[block])
            else:            
                star.create_dataset(block,data=path[block])
        #If there's not currently an array for the mass, I need to make one
        if 'Mass' not in path.keys():
            marray = empty(nfile[4])
            marray.fill(masses[4])
            star.create_dataset('Mass',data=marray)
            del marray
            
    if nbndry > 0:
        path = fin['PartType5']
        for block in path.keys():
            if block == 'Coordinates':
                bndry.create_dataset('Position',data=path[block])
            elif block == 'Velocities':
                bndry.create_dataset('Velocity',data=path[block])
            elif block == 'ParticleIDs':
                bndry.create_dataset('ID',data=path[block])
            else:            
                bndry.create_dataset(block,data=path[block])
        #If there's not currently an array for the mass, I need to make one
        if 'Mass' not in path.keys():
            marray = empty(nfile[5])
            marray.fill(masses[5])
            bndry.create_dataset('Mass',data=marray)
            del marray
            
    fin.close()
    irate.close()

    
def read_gbin(fname,potential,accel,entropy,timestep):
    """Reads a GADGET format file and returns the data in lists, one for
    each type of particle that contains arrays for each bit of data about
    each particle.  
        
    .. warning::
        Currently unused in the IRATE suite, and definitely not
        maintained either.  Use at your own risk.

    :param fname: 
        The name of the gadget binary file to be read
    :param bool potential: 
        True to read the Makefile enabled potential block
    :param bool accel: 
        True to read the Makefile enabled acceleration block
    :param bool entropy: 
        True to read the Makefile enabled dA/dt block
    :param bool timestep: 
        True to read the Makefile enabled timestep block 
    """       
    #The header and each data group gets its own list.
    
    #For non-gas groups, eg halodata = [halocoords,halovels,haloids,halomasses,halophi (if exists),haloaccel (if exists), halotimestep (if exists).  The (if exists) blocks must be enabled in the makefile; code will ask if they are or not.  The mass block may also be empty if all particles in that group have the same mass.
    
    #For gas, gasdata = [gascoords,gasvels,gasids,gasmass (if exists),gasU,gasdensity,gasHSML,gasphi (if exists),gasaccel (if exists), gas dS/dt (if exists), gastimestep (if exists), with the same conditions as non-gas groups.
    from numpy import fromstring
    print "\nOpening "+fname
    f = open(fname,'rb')

    #First read the header.
    header_size = struct.unpack('<I',f.read(4))[0]

    #number of particles of each type in this file
    nfile = struct.unpack('<6I',f.read(24)) #Number of particles in this file

    masstable = struct.unpack('<6d',f.read(48))  #masses of the particle groups
        
    a = struct.unpack('<d',f.read(8))[0]        #expansion factor
    z = struct.unpack('<d',f.read(8))[0]        #redshift

    flag_sfr = struct.unpack('<i',f.read(4))[0] #star formation included?
    flag_feed = struct.unpack('<i',f.read(4))[0] #feedback included?

    ntot = struct.unpack('<6i',f.read(24))      #total number of particles in the simulation (= nfile if numfiles == 1)
        
    flag_cool = struct.unpack('<i',f.read(4))[0]  #cooling included?
    numfiles = struct.unpack('<i',f.read(4))[0]   #number of files in each snapshot
    boxsize = struct.unpack('<d',f.read(8))[0] #Size of the box, if periodic
    omega0 = struct.unpack('<d',f.read(8))[0]  #matter density at z = 0
    omegaL = struct.unpack('<d',f.read(8))[0]  #vacuum energy density at z = 0
    h = struct.unpack('<d',f.read(8))[0] #hubble parameter in units of 100 km/s/Mpc
    flag_age = struct.unpack('<i',f.read(4))[0]  #stellar age included?
    flag_metals = struct.unpack('<i',f.read(4))[0]  #use metals?
    nhighword = struct.unpack('<6i',f.read(24))   #contains the most significant word of 64-bit particle numbers (if npart > 2^32)

    flag_entropy = struct.unpack('<i',f.read(4))[0] #entropy instead of thermal energy in initial conditions?

    #That's it for the header, so let's assemble it into a list then skip to the end:
    header = [nfile,masstable,a,z,flag_sfr,flag_feed,ntot,flag_cool,numfiles,boxsize,omega0,omegaL,h,flag_age,flag_metals,nhighword,flag_entropy]


    f.seek(264,0)   #Moves to the end of the header (and block that tells you size of header)
    """
    print "According to the header:"
    print "Ntotal = "+str(ntot[0]+ntot[1]+ntot[2]+ntot[3]+ntot[4]+ntot[5])
    print "There are "+str(ntot[0])+" gas particles.  According to the mass table, their mass is "+str(masstable[0])
    print "There are "+str(ntot[1])+" halo particles.  According to the mass table, their mass is "+str(masstable[1])
    print "There are "+str(ntot[2])+" disk particles.  According to the mass table, their mass is "+str(masstable[2])
    print "There are "+str(ntot[3])+" bulge particles.  According to the mass table, their mass is "+str(masstable[3])
    print "There are "+str(ntot[4])+" star particles.  According to the mass table, their mass is "+str(masstable[4])
    print "There are "+str(ntot[5])+" boundary particles.  According to the mass table, their mass is "+str(masstable[5])+"\n"
    """
    
    ngas = nfile[0]
    nhalo = nfile[1]
    ndisk = nfile[2]
    nbulge = nfile[3]
    nstar = nfile[4]
    nbndry = nfile[5]
    
    gasdata = []        #Use lists to keep the data for a specific particle species together, but it's a list of arrays
    halodata = []
    diskdata = []
    bulgedata = []
    stardata = []
    bndrydata = []
    
    #Rread in the coordinates, separate list for each particle type    
    coord_size = struct.unpack('<I',f.read(4))[0]   
    print "Reading coordinates..."
    #Read in all the coordinate data for the gas particles, Convert the string to an array, reshape it, and append it to the list of data for that particle type
    gasdata.append(fromstring(f.read(12*ngas) ,dtype='f').reshape((-1,3)))
    halodata.append(fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    diskdata.append(fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
    print "Read gas, halo, disk coordinates..."
    bulgedata.append(fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    stardata.append(fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    bndrydata.append(fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
    #And read the size of the coordinate block again.
    if struct.unpack('<I',f.read(4))[0] != coord_size:
        raise IOError("The block size at the end of the coordinate block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    
    #next up is velocities.  pretty identical to the coordinates.
    vel_size = struct.unpack('<I',f.read(4))[0]
    print "Reading velocities..."
    gasdata.append(fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
    halodata.append(fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
    diskdata.append(fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))   
    print "Read gas, halo, disk velocities..."            
    bulgedata.append(fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
    stardata.append(fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
    bndrydata.append(fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
    if struct.unpack('<I',f.read(4))[0] != vel_size:   #And read the size of the block again.
        raise IOError("The block size at the end of the velocity block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
        
    #Next up are the particle IDs, which are unsigned integers.
    id_size = struct.unpack('<I',f.read(4))[0]
    print "Reading particle IDs..."
    gasdata.append(fromstring(f.read(4*ngas),dtype='I'))
    halodata.append(fromstring(f.read(4*nhalo),dtype='I'))
    diskdata.append(fromstring(f.read(4*ndisk),dtype='I'))
    print "Read gas, halo, disk IDs..."            
    bulgedata.append(fromstring(f.read(4*nbulge),dtype='I'))
    stardata.append(fromstring(f.read(4*nstar),dtype='I'))
    bndrydata.append(fromstring(f.read(4*nbndry),dtype='I'))
    if struct.unpack('<I',f.read(4))[0] != id_size:   #And read the size of the block again.
        raise IOError("The block size at the end of the IDs block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    
    #Now I have to do the mass block.  Do this by checking if there are particles in a block that have a zero in the mass table.    
    if (ngas > 0 and masstable[0] == 0) or (nhalo > 0 and masstable[1] == 0) or (ndisk > 0 and masstable[2] == 0) or (nbulge > 0 and masstable[3] == 0) or (nstar > 0 and masstable[4] == 0) or (nbndry > 0 and masstable[5] == 0):
    #In other words, only read the size of the mass block if there is a mass block (for any of the groups); otherwise I'm just going to assign an empty list.
        mass_size = struct.unpack('<I',f.read(4))[0]
        
        if ngas > 0 and masstable[0] == 0:   #Then there are gas masses (ngas != 0 but the masstable has m = 0)
            print "Reading variable masses for gas group."
            gasmass = fromstring(f.read(4*ngas),dtype='f')
        else:
            gasmass = 0     #Just a placeholder so that my indices stay the same
            
        if nhalo > 0 and masstable[1] == 0:   #Then masses for particle group 1 are included
            print "Reading variable masses for group 1 (halo)."
            halomass = fromstring(f.read(4*nhalo),dtype='f')
        else:
            halomass = 0
            
        if ndisk > 0 and masstable[2] == 0:
            print "Reading variable masses for group 2 (disk)."
            diskmass = fromstring(f.read(4*ndisk),dtype='f')
        else:
            diskmass = 0
                        
        if nbulge > 0 and masstable[3] == 0:
            print "Reading variable masses for group 3 (bulge)."
            bulgemass = fromstring(f.read(4*nbulge),dtype='f')
        else:
            bulgemass = 0
            
        if nstar > 0 and masstable[4] == 0:
            print "Reading variable masses for group 4 (star)."
            starmass = fromstring(f.read(4*nstar),dtype='f')
        else:
            starmass = 0
            
        if nbndry > 0 and masstable[5] == 0:
            print "Reading variable masses for group 5 (boundary)."
            bndrymass = fromstring(f.read(4*nbndry),dtype='f')
        else:
            bndrymass = 0

        if struct.unpack('<I',f.read(4))[0] != mass_size:   #And read the size of the block again.
            raise IOError("The block size at the end of the mass block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")

    else:
        gasmass = 0
        halomass = 0
        diskmass = 0
        bulgemass = 0
        starmass = 0
        bndrymass = 0

    gasdata.append(gasmass)
    halodata.append(halomass)
    diskdata.append(diskmass)
    bulgedata.append(bulgemass)
    stardata.append(starmass)
    bndrydata.append(bndrymass)
    del gasmass,halomass,diskmass,bulgemass,starmass,bndrymass
    
    #Next up is some gas specific stuff.
    if ngas > 0:
        print "Reading gas specific data."
        
        #Put all this inside the if statement because I don't want it reading block sizes for gas blocks if there is no gas data (cause then there will be no block size and I will accidentally read into other data or past the end of the file.)
        
        #Internal energy:
        u_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        if struct.unpack('<I',f.read(4))[0] != u_size:
            raise IOError("The block size at the end of the internal energy block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
        
        #Density:
        rho_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        if struct.unpack('<I',f.read(4))[0] != rho_size:
            raise IOError("The block size at the end of the density block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
        
        #Smoothing length:
        hsml_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        if struct.unpack('<I',f.read(4))[0] != hsml_size:
            raise IOError("The block size at the end of the HSML block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.") 
        
        print "Read gas internal energy, gas density, and gas smoothing lengths."
    
    #That's it for the gas stuff; now I have to read stuff that's only there if enabled in the Makefile.
    #First, potential:
    #Create and append the lists regardless of whether or not they'll be empty
    if potential:
        print "Reading gravitational potentials."
        phi_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        halodata.append(fromstring(f.read(4*nhalo),dtype='f'))
        diskdata.append(fromstring(f.read(4*ndisk),dtype='f'))
        print "Read potentials for gas, halo, and disk groups..."
        bulgedata.append(fromstring(f.read(4*nbulge),dtype='f'))
        stardata.append(fromstring(f.read(4*nstar),dtype='f'))
        bndrydata.append(fromstring(f.read(4*nbndry),dtype='f'))
        
        if struct.unpack('<I',f.read(4))[0] != phi_size:
            raise IOError("The block size at the end of the phi block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    else:
    #append a placeholder to keep the indices the same either way
        gasdata.append(0)
        halodata.append(0)
        diskdata.append(0)
        bulgedata.append(0)
        stardata.append(0)
        bndrydata.append(0)
    
    #Next, acceleration, which is the same as velocity:
    if accel:
        print "Reading accelerations."
        accel_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(12*ngas),dtype='f').reshape((-1,3)))
        halodata.append(fromstring(f.read(12*nhalo),dtype='f').reshape((-1,3)))
        diskdata.append(fromstring(f.read(12*ndisk),dtype='f').reshape((-1,3)))
        print "Read gas, halo, disk velocities..."            
        bulgedata.append(fromstring(f.read(12*nbulge),dtype='f').reshape((-1,3)))
        stardata.append(fromstring(f.read(12*nstar),dtype='f').reshape((-1,3)))
        bndrydata.append(fromstring(f.read(12*nbndry),dtype='f').reshape((-1,3)))
        
        if struct.unpack('<I',f.read(4))[0] != accel_size:
            raise IOError("The block size at the end of the acceleration block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    else:
        gasdata.append(0)
        halodata.append(0)
        diskdata.append(0)
        bulgedata.append(0)
        stardata.append(0)
        bndrydata.append(0) 
    
    if entropy and ngas > 0:    #i.e. neglect their call for entropy data if there are no gas particles
        print "Reading rate of change of entropy for gas data"
        dsdt_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        if struct.unpack('<I',f.read(4))[0] != dsdt_size:
            raise IOError("The block size at the end of the entropy block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")    
    else:
        if entropy:  print "Warning:  You specified that entropy is included, but there are no gas particles."
        gasdata.append(0)
        
    if timestep:
        print "Reading timesteps"
        timestep_size = struct.unpack('<I',f.read(4))[0]
        gasdata.append(fromstring(f.read(4*ngas),dtype='f'))
        halodata.append(fromstring(f.read(4*nhalo),dtype='f'))
        diskdata.append(fromstring(f.read(4*ndisk),dtype='f'))
        print "Read potentials for gas, halo, and disk groups..."
        bulgedata.append(fromstring(f.read(4*nbulge),dtype='f'))
        stardata.append(fromstring(f.read(4*nstar),dtype='f'))
        bndrydata.append(fromstring(f.read(4*nbndry),dtype='f'))               
        if struct.unpack('<I',f.read(4))[0] != timestep_size:
            raise IOError("The block size at the end of the timestep block doesn't match that at the beginning.  There is something wrong with the file, or my reading of it.")
    
    else:
        gasdata.append(0)
        halodata.append(0)
        diskdata.append(0)
        bulgedata.append(0)
        stardata.append(0)
        bndrydata.append(0)

    current_pos = f.tell()
    f.seek(0,2) #Jump to the end of the file
    if current_pos == f.tell():
        print "Read "+fname
    else:
        print "Completed reading "+fname+" but there remain {0} bytes at the end of the file unread.".format(f.tell()-current_pos)
    f.close()

    return [header,gasdata,halodata,diskdata,bulgedata,stardata,bndrydata]
    
    
class GadgetSimulationPropertiesValidator(Validator):
    groupname = 'SimulationProperties'
    def validate(self,grp):
        """
        Validates that the SimulationProperties group in an IRATE file has the
        necessary properties that are typically contained in a Gadget file
        header:  Boxsize, FlagSFR, FlagFeedback, FlagCooling, FlagAge,
        FlagMetals, and FlagEntropyICs.
        
        :param grp:
            The 'SimulationProperties' :class:`~h5py.Group` to be validated
        """ 
        #Ok, so the simulation properties need the boxsize and some flags
        required = ['Boxsize','FlagSFR','FlagFeedback','FlagCooling','FlagAge','FlagMetals','FlagEntropyICs']
        for prop in required:
            if prop not in grp.attrs:
                self.invalid("Simulation properties is missing required attribute {0}".format(prop))
        
class GadgetGasValidator(Validator):
    groupname = 'Gas'
    def validate(self,grp):
        """
        Validates that a Gas group contains the required datasets for gas and
        that they're all the proper length and dimensions.  Since the standard
        Position, Velocity, Mass, and ID are checked for by the default
        validator, this checks only for InternalEnergy, Density, and
        SmoothingLength.
        
        :param grp:
            The :class:`~h5py.Group` that will be validated
        """
        #Gas group needs to have the usual datasets, plus SmoothingLength, InternalEnergy, and Density
        if 'Position' not in grp:
            self.invalid('Position is missing')
            length = 0
        else:
            length = grp['Position'].shape[0]
            self.check_units(grp['Position'])
        if 'InternalEnergy' not in grp:
            self.invalid("InternalEnergy is missing")
        else:
            self.check_units(grp['InternalEnergy'])
            #The internal energy group needs to be 1D and the same length as position
            if len(grp['InternalEnergy'].shape) != 1:
                self.invalid('InternalEnergy dataset is not 1d')
            if length != 0:     #Then it found position fine, and I want to make sure that this is as long as that
                if grp['InternalEnergy'].shape[0] != length:
                    self.invalid("InternalEnergy dataset is not the same length as Position dataset")
            else:
                #Then position wasn't found, but I want to keep going, so set this as the new length
                length = grp['InternalEnergy'].shape[0]
        generallyrequired = ['SmoothingLength','Density']
        for key in generallyrequired:
            if key not in grp:
                self.invalid('{0} is missing (this is acceptable for initial conditions only).'.format(key))
            else:
                self.check_units(grp[key])
                #They need to be 1D and the same length as those above
                if len(grp[key].shape) != 1:
                    self.invalid('{0} dataset is not 1d'.format(key))
                if length != 0:
                    #Then the length of these needs to match that length
                    if grp[key].shape[0] != length:
                        self.invalid("{0} dataset is not the same length as other datasets in that group".format(key))
                else:
                    #Then I want to set this as the new length, because apparently neither of the ones before it had a length
                    length = grp[key].shape[0]
        
def _add_validators():
    add_validator_type('gadget',[GadgetSimulationPropertiesValidator,GadgetGasValidator])