File: misc.pd

package info (click to toggle)
pdl 1%3A2.017-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 12,396 kB
  • ctags: 7,752
  • sloc: perl: 47,595; fortran: 13,113; ansic: 9,359; sh: 41; makefile: 38; sed: 6
file content (1592 lines) | stat: -rw-r--r-- 47,434 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592

# check for bad value support
use PDL::Config;
my $bvalflag = $PDL::Config{WITH_BADVAL} || 0;

# and endian-ness of machine
require PDL::Core::Dev;
my $isbigendian = PDL::Core::Dev::isbigendian();

pp_addpm({At=>'Top'},<<'EOD');

=head1 NAME

PDL::IO::Misc - misc IO routines for PDL

=head1 DESCRIPTION

Some basic I/O functionality: FITS, tables, byte-swapping

=head1 SYNOPSIS

 use PDL::IO::Misc;

=cut

EOD

pp_addpm({At=>'Bot'},<<'EOD');

=head1 AUTHOR

Copyright (C) Karl Glazebrook 1997, Craig DeForest 2001,
2003, and Chris Marshall 2010. All rights reserved. There is
no warranty. You are allowed to redistribute this software
/ documentation under certain conditions. For details, see
the file COPYING in the PDL distribution. If this file is
separated from the PDL distribution, the copyright notice
should be included in the file.

=cut

EOD

pp_add_exported('',"rcols wcols swcols rgrep rdsa");

############################## PM CODE ########################################

pp_addpm(<<'!NO!SUBS!');

use PDL::Primitive;
use PDL::Types;
use PDL::Options;
use PDL::Bad;
use Carp;
use Symbol qw/ gensym /;
use List::Util;
use strict;

!NO!SUBS!

defpdl(
        'bswap2',
        'x(); ',
        '',
        '
      int i;
      PDL_Short *aa; PDL_Short bb;
      PDL_Byte *a,*b;

      int n = sizeof($x()) / sizeof(PDL_Short);
      aa = (PDL_Short*) &$x();

      for(i=0;i<n; i++) {
         bb = aa[i]; a = (PDL_Byte*) (void*) (aa+i);
         b = (PDL_Byte*) &bb;
         *a = *(b+1);  *(a+1) = *b;
     }',
     "Swaps pairs of bytes in argument x()"
);


defpdl(
        'bswap4',
        'x(); ',
        '',
        '
      int i;
      PDL_Long *aa; PDL_Long bb;
      PDL_Byte *a,*b;

      int n = sizeof($x()) / sizeof(PDL_Long);
      aa = (PDL_Long*) &$x();

      for(i=0;i<n; i++) {
         bb = aa[i]; a = (PDL_Byte*) (void*) (aa+i);
         b = (PDL_Byte*) &bb;
         *a = *(b+3);  *(a+1) = *(b+2);  *(a+2) = *(b+1); *(a+3) = *b;
     }',
     "Swaps quads of bytes in argument x()"
);


defpdl(
        'bswap8',
        'x(); ',
        '',
        '
      int i;
      PDL_Double *aa; PDL_Double bb;
      PDL_Byte *a,*b;

      int n = sizeof($x()) / sizeof(PDL_Double);
      aa = (PDL_Double*) &$x();

      for(i=0;i<n; i++) {
         bb = aa[i]; a = (PDL_Byte*) (void*) (aa+i);
         b = (PDL_Byte*) &bb;
         *a     = *(b+7);  *(a+1) = *(b+6);  *(a+2) = *(b+5); *(a+3) = *(b+4);
         *(a+4) = *(b+3);  *(a+5) = *(b+2);  *(a+6) = *(b+1); *(a+7) = *b;
     }',
     "Swaps octets of bytes in argument x()"
);


pp_addpm(<<'!NO!SUBS!');



# Internal routine to extend PDL array by size $n along last dimension
# - Would be nice to have a proper extend function rather than hack
# - Is a NO-OP when handed a perl ARRAY ref rather than a piddle arg
sub _ext_lastD {                           # Called by rcols and rgrep
   my ($a,$n) = @_;
   if (ref($_[0]) ne 'ARRAY') {
      my @nold   = $a->dims;
      my @nnew   = @nold;
      $nnew[-1] += $n;                      # add $n to the last dimension
      my $b      = zeroes($a->type,@nnew);  # New pdl
      my $bb     = $b->mv(-1,0)->slice("0:".($nold[-1]-1))->mv(0,-1);
      $bb       .= $a;
      $_[0]      = $b;
   }
   1;
}

# Implements PDL->at() for either 1D PDL or ARRAY arguments
# TODO: Need to add support for multidim piddles parallel to rcols
sub _at_1D ($$) {                           # Called by wcols and swcols
    my $data = $_[0];
    my $index = $_[1];
    
    if (ref $data eq 'ARRAY') {
       return $data->[$index];
    } else {
       return $data->at($index);
    }
}

# squeezes "fluffy" perl list values into column data type
sub _burp_1D {
   my $data = $_[0]->[0]; 
   my $databox = $_[0]->[1];
   my $index = $_[1];

   my $start = $index - @{$databox} + 1;

   my $tmp; # work around for perl -d "feature"
   if (ref $data eq 'ARRAY') {
      push @{$data}, @{$databox};
   } elsif ( ref($databox->[0]) eq "ARRAY" ) {
      # could add POSIX::strtol for hex and octal support but
      # can't break float conversions (how?)
      ($tmp = $data->slice(":,$start:$index")) .= pdl($databox);
   } else {
      # could add POSIX::strtol for hex and octal support but
      # can't break float conversions (how?)
      ($tmp = $data->slice("$start:$index")) .= pdl($databox);
   }
   $_[0] = [ $data, [] ];
}

# taken outside of rcols() to avoid clutter
sub _handle_types ($$$) {
    my $ncols = shift;
    my $deftype = shift;
    my $types = shift;

    barf "Unknown PDL type given for DEFTYPE.\n"
        unless ref($deftype) eq "PDL::Type";

    my @cols = ref($types) eq "ARRAY" ? @$types : ();
        
    if ( $#cols > -1 ) {
        # truncate if required
        $#cols = $ncols if $#cols > $ncols;
        
        # check input values are sensible
        for ( 0 .. $#cols ) {
            barf "Unknown value '$cols[$_]' in TYPES array.\n" 
                unless ref($cols[$_]) eq "PDL::Type";
        }
    }

    # fill in any missing columns
    for ( ($#cols+1) .. $ncols ) { push @cols, $deftype; }

    return @cols;
} # sub: _handle_types


# Whether an object is an IO handle
use Scalar::Util;
sub _is_io_handle {
    my $h = shift;
    # reftype catches almost every handle, except: *MYHANDLE
    # fileno catches *MYHANDLE, but doesn't catch handles that aren't files
    my $reftype = Scalar::Util::reftype($h);
    return defined(fileno($h)) || (defined($reftype) && $reftype eq 'GLOB');
}


=head2 rcols

=for ref

Read specified ASCII cols from a file into piddles and perl
arrays (also see L</rgrep>).

=for usage

  Usage:
    ($x,$y,...) = rcols( *HANDLE|"filename", { EXCLUDE => '/^!/' }, $col1, $col2, ... )
             $x = rcols( *HANDLE|"filename", { EXCLUDE => '/^!/' }, [] )
    ($x,$y,...) = rcols( *HANDLE|"filename", $col1, $col2, ..., { EXCLUDE => '/^!/' } )
    ($x,$y,...) = rcols( *HANDLE|"filename", "/foo/", $col1, $col2, ... )

For each column number specified, a 1D output PDL will be
generated.  Anonymous arrays of column numbers generate
2D output piddles with dim0 for the column data and dim1
equal to the number of colums in the anonymous array(s).

An empty anonymous array as column specification will
produce a single output data piddle with dim(1) equal
to the number of columns available.

There are two calling conventions - the old version, where a
pattern can be specified after the filename/handle, and the
new version where options are given as as hash reference.
This reference can be given as either the second or last
argument.

The default behaviour is to ignore lines beginning with
a # character and lines that only consist of whitespace.
Options exist to only read from lines that match, or do
not match, supplied patterns, and to set the types of the
created piddles.

Can take file name or *HANDLE, and if no explicit column
numbers are specified, all are assumed. For the allowed types,
see L<PDL::Core/Datatype_conversions>.

Options (case insensitive):

  EXCLUDE or IGNORE
  - ignore lines matching this pattern (default B<'/^#/'>).
  
  INCLUDE or KEEP
  - only use lines which match this pattern (default B<''>).
  
  LINES   
  - a string pattern specifying which line numbers to use.
  Line numbers start at 0 and the syntax is 'a:b:c' to use
  every c'th matching line between a and b (default B<''>).
  
  DEFTYPE
  - default data type for stored data (if not specified, use the type 
  stored in C<$PDL::IO::Misc::deftype>, which starts off as B<double>).
  
  TYPES
  - reference to an array of data types, one element for each column 
  to be read in.  Any missing columns use the DEFTYPE value (default B<[]>).
  
  COLSEP
  - splits on this string/pattern/qr{} between colums of data. Defaults to
  $PDL::IO::Misc::defcolsep.
  
  PERLCOLS
  - an array of column numbers which are to be read into perl arrays
  rather than piddles.  Any columns not specified in the explicit list
  of columns to read will be returned after the explicit columns.
  (default B<undef>).

  COLIDS
  - if defined to an array reference, it will be assigned the column
  ID values obtained by splitting the first line of the file in the
  identical fashion to the column data.

  CHUNKSIZE
  - the number of input data elements to batch together before appending
  to each output data piddle (Default value is 100).  If CHUNKSIZE is
  greater than the number of lines of data to read, the entire file is
  slurped in, lines split, and perl lists of column data are generated.
  At the end, effectively pdl(@column_data) produces any result piddles.

  VERBOSE
  - be verbose about IO processing (default C<$PDL::vebose>)

=for example

For example:

  $x      = PDL->rcols 'file1';	        # file1 has only one column of data
  $x      = PDL->rcols 'file2', [];	# file2 can have multiple columns, still 1 piddle output
                                        # (empty array ref spec means all possible data fields)

  ($x,$y) = rcols 'table.csv', { COLSEP => ',' };  # read CSV data file
  ($x,$y) = rcols *STDOUT;  # default separator for lines like '32 24'

  # read in lines containing the string foo, where the first
  # example also ignores lines that begin with a # character.
  ($x,$y,$z) = rcols 'file2', 0,4,5, { INCLUDE => '/foo/' };
  ($x,$y,$z) = rcols 'file2', 0,4,5, { INCLUDE => '/foo/', EXCLUDE => '' };

  # ignore the first 27 lines of the file, reading in as ushort's
  ($x,$y) = rcols 'file3', { LINES => '27:-1', DEFTYPE => ushort };
  ($x,$y) = rcols 'file3', { LINES => '27:', TYPES => [ ushort, ushort ] };

  # read in the first column as a perl array and the next two as piddles
  # with the perl column returned after the piddle outputs
  ($x,$y,$name) = rcols 'file4', 1, 2   , { PERLCOLS => [ 0 ] };
  printf "Number of names read in = %d\n", 1 + $#$name;

  # read in the first column as a perl array and the next two as piddles
  # with PERLCOLS changing the type of the first returned value to perl list ref
  ($name,$x,$y) = rcols 'file4', 0, 1, 2, { PERLCOLS => [ 0 ] };

  # read in the first column as a perl array returned first followed by the
  # the next two data columns in the file as a single Nx2 piddle 
  ($name,$xy) = rcols 'file4', 0, [1, 2], { PERLCOLS => [ 0 ] };


  NOTES:

  1. Quotes are required on patterns or use the qr{} quote regexp syntax.
  
  2. Columns are separated by whitespace by default, use the COLSEP option
     separator to specify an alternate split pattern or string or specify an
     alternate default separator by setting C<$PDL::IO::Misc::defcolsep> .
  
  3. Legacy support is present to use C<$PDL::IO::Misc::colsep> to set the
     column separator but C<$PDL::IO::Misc::colsep> is not defined by default.
     If you set the variable to a defined value it will get picked up.
  
  4. LINES => '-1:0:3' may not work as you expect, since lines are skipped
     when read in, then the whole array reversed.

  5. For consistency with wcols and rcols 1D usage, column data is loaded
     into the rows of the pdls (i.e., dim(0) is the elements read per column
     in the file and dim(1) is the number of columns of data read.

=cut

use vars qw/ $colsep $defcolsep $deftype /;

$defcolsep = ' ';       # Default column separator
$deftype = double;      # Default type for piddles

my $defchunksize = 100; # Number of perl list items to append to piddle
my $usecolsep;          # This is the colsep value that is actually used

# NOTE: XXX
#  need to look at the line-selection code. For instance, if want
#   lines => '-1:0:3', 
#  read in all lines, reverse, then apply the step
#  -> fix point 4 above
# 
# perhaps should just simplify the LINES option - ie remove
# support for reversed arrays?

sub rcols{ PDL->rcols(@_) }

sub PDL::rcols {
   my $class = shift;
   barf 'Usage ($x,$y,...) = rcols( *HANDLE|"filename", ["/pattern/" or \%options], $col1, $col2, ..., [ \%options] )' 
   if $#_<0;

   my $is_handle = _is_io_handle $_[0];
   my $fh = $is_handle ? $_[0] : gensym;
   open $fh, $_[0] or die "File $_[0] not found\n" unless $is_handle;
   shift;

   # set up default options
   my $opt = new PDL::Options( {
       CHUNKSIZE => undef,
       COLIDS => undef,
       COLSEP => undef,
       DEFTYPE => $deftype,
       EXCLUDE => '/^#/',
       INCLUDE => undef,
       LINES => '',
       PERLCOLS => undef,
       TYPES   => [],
       VERBOSE=> $PDL::verbose,
       } );
   $opt->synonyms( { IGNORE => 'EXCLUDE', KEEP => 'INCLUDE' } );

   # has the user supplied any options
   if ( defined($_[0]) ) {
      # ensure the old-style behaviour by setting the exclude pattern to undef 
      if ( $_[0] =~ m|^/.*/$| )        { $opt->options( { EXCLUDE => undef, INCLUDE => shift } ); }
      elsif ( ref($_[0]) eq "Regexp" ) { $opt->options( { EXCLUDE => undef, INCLUDE => shift } ); }
      elsif ( ref($_[0]) eq "HASH" )   { $opt->options( shift ); }
   }

   # maybe the last element is a hash array as well
   $opt->options( pop ) if defined($_[-1]) and ref($_[-1]) eq "HASH";

   # a reference to a hash array
   my $options = $opt->current();   

   # handle legacy colsep variable
   $usecolsep = (defined $colsep) ? qr{$colsep} : undef;
   $usecolsep = qr{$options->{COLSEP}} if $options->{COLSEP};

   # what are the patterns?
   foreach my $pattern ( qw( INCLUDE EXCLUDE ) ) {
      if ( $options->{$pattern} and ref($options->{$pattern}) ne "Regexp" ) {
         if ( $options->{$pattern} =~ m|^/.*/$| ) {
            $options->{$pattern} =~ s|^/(.*)/$|$1|;
            $options->{$pattern} = qr($options->{$pattern});
         } else {
            barf "rcols() - unable to process $pattern value.\n";
         }
      }
   }

   # CHUNKSIZE controls memory/time tradeoff of piddle IO
   my $chunksize = $options->{CHUNKSIZE} || $defchunksize;
   my $nextburpindex = -1;

# which columns are to be read into piddles and which into perl arrays?
my @end_perl_cols = ();       # unique perl cols to return at end

my @perl_cols = ();           # perl cols index list from PERLCOLS option
@perl_cols = @{ $$options{PERLCOLS} } if $$options{PERLCOLS};

my @is_perl_col;              # true if index corresponds to a perl column
for (@perl_cols) { $is_perl_col[$_] = 1; };
# print STDERR "rcols: \@is_perl_col is @is_perl_col\n";

my ( @explicit_cols )  = @_;  # call specified columns to read
# print STDERR "rcols: \@explicit_cols is @explicit_cols\n";

# work out which line numbers are required
# - the regexp's are a bit over the top
my ( $a, $b, $c );
if ( $$options{LINES} ne '' ) {
   if ( $$options{LINES} =~ /^\s*([+-]?\d*)\s*:\s*([+-]?\d*)\s*$/ ) {
      $a = $1; $b = $2;
   } elsif ( $$options{LINES} =~ /^\s*([+-]?\d*)\s*:\s*([+-]?\d*)\s*:\s*([+]?\d*)\s*$/ ) {
      $a = $1; $b = $2; $c = $3;
   } else {
      barf "rcols() - unable to parse LINES option.\n";
   }
}

# Since we do not know how many lines there are in advance, things get a bit messy
my ( $index_start, $index_end ) = ( 0, -1 );
$index_start  = $a if defined($a) and $a ne '';
$index_end    = $b if defined($b) and $b ne '';
my $line_step = $c || 1;

# $line_rev = 0/1 for normal order/reversed
# $line_start/_end refer to the first and last line numbers that we want
# (the values of which we may not know until we've read in all the file)
my ( $line_start, $line_end, $line_rev );
if ( ($index_start >= 0 and $index_end < 0) ) {
   # eg 0:-1
   $line_rev = 0; $line_start = $index_start;
} elsif ( $index_end >= 0 and $index_start < 0 ) {
   # eg -1:0
   $line_rev = 1; $line_start = $index_end; 
} elsif ( $index_end >= $index_start and $index_start >= 0 ) {
   # eg 0:10
   $line_rev = 0; $line_start = $index_start; $line_end = $index_end;
} elsif ( $index_start > $index_end and $index_end >= 0 ) {
   # eg 10:0
   $line_rev = 1; $line_start = $index_end; $line_end = $index_start;
} elsif ( $index_start <= $index_end ) {
   # eg -5:-1
   $line_rev = 0;
} else {
   # eg -1:-5
   $line_rev = 1;
}

my @ret;

my ($k,$fhline); 

my $line_num = -1;
my $line_ctr = $line_step - 1;  # ensure first line is always included
my $index    = -1;
my $pdlsize  =  0;
my $extend   = 10000;

my $line_store;  # line numbers of saved data

RCOLS_IO: {

   if ($options->{COLIDS}) {
      print STDERR "rcols: processing COLIDS option\n" if $options->{VERBOSE};
      undef $!;
      if (defined($fhline = <$fh>) ) {        # grab first line's fields for column IDs
         $fhline =~ s/\r?\n$//;               # handle DOS on unix files better
         my @v = defined($usecolsep) ? split($usecolsep,$fhline) : split(' ',$fhline);
         @{$options->{COLIDS}} = @v;
      } else {
         die "rcols: reading COLIDS info, $!" if $!;
         last RCOLS_IO;
      }
   }

   while( defined($fhline = <$fh>) ) {

      # chomp $fhline;
      $fhline =~ s/\r?\n$//;  # handle DOS on unix files better

      $line_num++;

      # the order of these checks is important, particularly whether we
      # check for line_ctr before or after the pattern matching
      # Prior to PDL 2.003 the line checks were done BEFORE the
      # pattern matching
      #
      # need this first check, even with it almost repeated at end of loop,
      # incase the pattern matching excludes $line_num == $line_end, say
      last if     defined($line_end)   and $line_num > $line_end;
      next if     defined($line_start) and $line_num < $line_start;
      next if     $options->{EXCLUDE} and     $fhline =~ /$options->{EXCLUDE}/;
      next if     $options->{INCLUDE} and not $fhline =~ /$options->{INCLUDE}/;
      next unless ++$line_ctr == $line_step;
      $line_ctr = 0;

      $index++;
      my @v = defined($usecolsep) ? split($usecolsep,$fhline) : split(' ',$fhline);

      # map empty fields '' to undef value
      @v = map { $_ eq '' ? undef : $_ } @v;

      # if the first line, set up the output piddles using all the columns
      # if the user doesn't specify anything
      if ( $index == 0 ) {

         # Handle implicit multicolumns in command line
         if ($#explicit_cols < 0) {                 # implicit single col data
            @explicit_cols = ( 0 .. $#v );
         }
         if (scalar(@explicit_cols)==1 and ref($explicit_cols[0]) eq "ARRAY") {
            if ( !scalar(@{$explicit_cols[0]}) ) {  # implicit multi-col data
               @explicit_cols = ( [ 0 .. $#v ] );
            }
         }
         my $implicit_pdls = 0;
         my $is_explicit = {};
         foreach my $col (@explicit_cols) {
            if (ref($col) eq "ARRAY") {
               $implicit_pdls++ if !scalar(@$col);
            } else {
               $is_explicit->{$col} = 1;
            }
         }
         if ($implicit_pdls > 1) {
            die "rcols: only one implicit multicolumn piddle spec allowed, found $implicit_pdls!\n";
         }
         foreach my $col (@explicit_cols) {
            if (ref($col) eq "ARRAY" and !scalar(@$col)) {
               @$col = grep { !$is_explicit->{$_} } ( 0 .. $#v );
            }
         }
            
         # remove declared perl columns from pdl data list
         $k = 0;
         my @pdl_cols = ();
         foreach my $col (@explicit_cols) {
            # strip out declared perl cols so they won't be read into piddles
            if ( ref($col) eq "ARRAY" ) {
               @$col = grep { !$is_perl_col[$_] } @{$col};
               push @pdl_cols, [ @{$col} ];
            } elsif (!$is_perl_col[$col]) {
               push @pdl_cols, $col;
            }
         }
         # strip out perl cols in explicit col list for return at end
         @end_perl_cols = @perl_cols;
         foreach my $col (@explicit_cols) {
            if ( ref($col) ne "ARRAY" and defined($is_perl_col[$col]) ) {
               @end_perl_cols = grep { $_ != $col } @end_perl_cols;
            }
         };

         # sort out the types of the piddles
         my @types = _handle_types( $#pdl_cols, $$options{DEFTYPE}, $$options{TYPES} );
         if ( $options->{VERBOSE} ) { # dbg aid
            print "Reading data into piddles of type: [ ";
            foreach my $t ( @types ) {
               print $t->shortctype() . " ";
            }
            print "]\n";
         }

         $k = 0;
         for (@explicit_cols) {
            # Using mixed list+piddle data structure for performance tradeoff
            # between memory usage (perl list) and speed of IO (PDL operations)
            if (ref($_) eq "ARRAY") {
               # use multicolumn piddle here
               push @ret, [ $class->zeroes($types[$k++],scalar(@{$_}),1), [] ];
            } else {
               push @ret, ($is_perl_col[$_] ? [ [], [] ] : [ $class->zeroes($types[$k],1), [] ]);
               $k++ unless $is_perl_col[$_];
            }
         }
         for (@end_perl_cols) { push @ret, [ [], [] ]; }

         $line_store = [ $class->zeroes(long,1), [] ]; # only need to store integers
      }

      # if necessary, extend PDL in buffered manner
      $k = 0;
      if ( $pdlsize < $index ) {
         for (@ret, $line_store) { _ext_lastD( $_->[0], $extend ); }
         $pdlsize += $extend;
      }

      # - stick perl arrays onto end of $ret
      $k = 0;
      for (@explicit_cols, @end_perl_cols)  {
         if (ref($_) eq "ARRAY") {
            push @{ $ret[$k++]->[1] }, [ @v[ @$_ ] ];
         } else {
            push @{ $ret[$k++]->[1] }, $v[$_];
         }
      }

      # store the line number
      push @{$line_store->[1]}, $line_num;

      # need to burp out list if needed
      if ( $index >= $nextburpindex ) {
         for (@ret, $line_store) { _burp_1D($_,$index); }
         $nextburpindex = $index + $chunksize;
      }

      # Thanks to Frank Samuelson for this
      last if defined($line_end) and $line_num == $line_end;
   }

}

close($fh) unless $is_handle;

# burp one final time if needed and 
# clean out additional ARRAY ref level for @ret
for (@ret, $line_store) {
   _burp_1D($_,$index) if defined $_ and scalar @{$_->[1]};
   $_ = $_->[0];
}

# have we read anything in? if not, return empty piddles
if ( $index == -1 ) {
   print "Warning: rcols() did not read in any data.\n" if $options->{VERBOSE};
   if ( wantarray ) {
      foreach ( 0 .. $#explicit_cols ) {
         if ( $is_perl_col[$_] ) {
            $ret[$_] = PDL->null;
         } else {
            $ret[$_] = [];
         }
      }
      for ( @end_perl_cols ) { push @ret, []; }
      return ( @ret );
   } else { 
      return PDL->null;
   }
}

# if the user has asked for lines => 0:-1 or 0:10 or 1:10 or 1:-1,
# - ie not reversed and the last line number is known -
# then we can skip the following nastiness
if ( $line_rev == 0 and $index_start >= 0 and $index_end >= -1 ) {
   for (@ret) {
      ## $_ = $_->mv(-1,0)->slice("0:${index}")->mv(0,-1) unless ref($_) eq 'ARRAY';
      $_ = $_->mv(-1,0)->slice("0:${index}") unless ref($_) eq 'ARRAY';  # cols are dim(0)
   };
   if ( $options->{VERBOSE} ) {
      if ( ref($ret[0]) eq 'ARRAY' ) {
         print "Read in ", scalar( @{ $ret[0] } ), " elements.\n";
      } else {
         print "Read in ", $ret[0]->nelem, " elements.\n";
      }
   }
   wantarray ? return(@ret) : return $ret[0];
}

# Work out which line numbers we want. First we clean up the piddle
# containing the line numbers that have been read in
$line_store = $line_store->slice("0:${index}");

# work out the min/max line numbers required
if ( $line_rev ) {
   if ( defined($line_start) and defined($line_end) ) {
      my $dummy = $line_start;
      $line_start = $line_end;
      $line_end = $dummy;
   } elsif ( defined($line_start) ) {
      $line_end = $line_start;
   } else {
      $line_start = $line_end; 
   }
}
$line_start = $line_num + 1 + $index_start if $index_start < 0;
$line_end   = $line_num + 1 + $index_end   if $index_end   < 0;

my $indices;

{ no warnings 'precedence';	
   if ( $line_rev ) {
      $indices = which( $line_store >= $line_end & $line_store <= $line_start )->slice('-1:0');
   } else {
      $indices = which( $line_store >= $line_start & $line_store <= $line_end );
   }
}

# truncate the piddles
for my $col ( @explicit_cols ) {
   if ( ref($col) eq "ARRAY" ) {
      for ( @$col ) {
         $ret[$_] = $ret[$_]->index($indices);
      }
   } else {
      $ret[$col] = $ret[$col]->index($indices) unless $is_perl_col[$col] };
}

# truncate/reverse/etc the perl arrays
my @indices_array = list $indices;
foreach ( @explicit_cols, @end_perl_cols ) {
   if ( $is_perl_col[$_] ) {
      my @temp = @{ $ret[$_] };
      $ret[$_] = [];
      foreach my $i ( @indices_array ) { push @{ $ret[$_] }, $temp[$i] };
   }
}

# print some diagnostics
if ( $options->{VERBOSE} ) {
   my $done = 0;
   foreach my $col (@explicit_cols) {
      last if $done;
      next if $is_perl_col[$col];
      print "Read in ", $ret[$col]->nelem, " elements.\n";
      $done = 1;
   }
   foreach my $col (@explicit_cols, @end_perl_cols) {
      last if $done;
      print "Read in ", $ret[$col]->nelem, " elements.\n";
      $done = 1;
   }
}

# fix 2D pdls to match what wcols generates
foreach my $col (@ret) {
   next if ref($col) eq "ARRAY";
   $col = $col->mv(0,1) if $col->ndims == 2;
}

wantarray ? return(@ret) : return $ret[0];
}


=head2 wcols

=for ref

  Write ASCII columns into file from 1D or 2D piddles and/or 1D listrefs efficiently.

Can take file name or *HANDLE, and if no file/filehandle is given defaults to STDOUT.

  Options (case insensitive):

    HEADER - prints this string before the data. If the string
             is not terminated by a newline, one is added. (default B<''>).

    COLSEP - prints this string between colums of data. Defaults to
             $PDL::IO::Misc::defcolsep.

    FORMAT - A printf-style format string that is cycled through
             column output for user controlled formatting.

=for usage

 Usage: wcols $data1, $data2, $data3,..., *HANDLE|"outfile", [\%options];  # or
        wcols $format_string, $data1, $data2, $data3,..., *HANDLE|"outfile", [\%options];

   where the $dataN args are either 1D piddles, 1D perl array refs,
   or 2D piddles (as might be returned from rcols() with the [] column
   syntax and/or using the PERLCOLS option).  dim(0) of all piddles
   written must be the same size.  The printf-style $format_string,
   if given, overrides any FORMAT key settings in the option hash.

e.g.,

=for example

  $x = random(4); $y = ones(4);
  wcols $x, $y+2, 'foo.dat';
  wcols $x, $y+2, *STDERR;
  wcols $x, $y+2, '|wc';

  $a = sequence(3); $b = zeros(3); $c = random(3);
  wcols $a,$b,$c; # Orthogonal version of 'print $a,$b,$c' :-)

  wcols "%10.3f", $a,$b; # Formatted
  wcols "%10.3f %10.5g", $a,$b; # Individual column formatting

  $a = sequence(3); $b = zeros(3); $units = [ 'm/sec', 'kg', 'MPH' ];
  wcols $a,$b, { HEADER => "#   a   b" };
  wcols $a,$b, { Header => "#   a   b", Colsep => ', ' };  # case insensitive option names!
  wcols " %4.1f  %4.1f  %s",$a,$b,$units, { header => "# Day  Time  Units" };

  $a52 = sequence(5,2); $b = ones(5); $c = [ 1, 2, 4 ];
  wcols $a52;         # now can write out 2D pdls (2 columns data in output)
  wcols $b, $a52, $c  # ...and mix and match with 1D listrefs as well

  NOTES:

  1. Columns are separated by whitespace by default, use
     C<$PDL::IO::Misc::defcolsep> to modify the default value or
     the COLSEP option

  2. Support for the C<$PDL::IO::Misc::colsep> global value
     of PDL-2.4.6 and earlier is maintained but the initial value
     of the global is undef until you set it.  The value will be
     then be picked up and used as if defcolsep were specified.

  3. Dim 0 corresponds to the column data dimension for both
     rcols and wcols.  This makes wcols the reverse operation
     of rcols.

=cut

*wcols = \&PDL::wcols;

sub PDL::wcols {
   barf 'Usage: wcols($optional_format_string, 1_or_2D_pdls, *HANDLE|"filename", [\%options])' if @_<1;

   # handle legacy colsep variable
   $usecolsep = (defined $colsep) ? $colsep : $defcolsep;

   # if last argument is a reference to a hash, parse the options
   my ($format_string, $step, $fh);
   my $header;
   if ( ref( $_[-1] ) eq "HASH" ) {
       my $opt = pop;
       foreach my $key ( keys %$opt ) {
           if ( $key =~ /^H/i ) { $header = $opt->{$key}; }             # option: HEADER
	   elsif ( $key =~ /^COLSEP/i ) { $usecolsep = $opt->{$key}; }  # option: COLSEP
	   elsif ( $key =~ /^FORMAT/i ) { $format_string = $opt->{$key}; }  # option: FORMAT
           else {
               print "Warning: wcols does not understand option <$key>.\n";
           }
       }
   }
   if (ref(\$_[0]) eq "SCALAR" || $format_string) {
       $format_string = shift if (ref(\$_[0]) eq "SCALAR");
       # 1st arg not piddle, explicit format string overrides option hash FORMAT
       $step = $format_string;
       $step =~ s/(%%|[^%])//g;  # use step to count number of format items
       $step = length ($step);
   }
   my $file = $_[-1];
   my $file_opened;
   my $is_handle = !UNIVERSAL::isa($file,'PDL') &&
                   !UNIVERSAL::isa($file,'ARRAY') &&
                   _is_io_handle $file;
   if ($is_handle) {  # file handle passed directly
       $fh = $file; pop;
   }
   else{
       if (ref(\$file) eq "SCALAR") {  # Must be a file name
          $fh = gensym;
         if (!$is_handle) {
            $file = ">$file" unless $file =~ /^\|/ or $file =~ /^\>/;
             open $fh, $file or barf "File $file can not be opened for writing\n";
         }
          pop;
          $file_opened = 1;
       }
       else{  # Not a filehandle or filename, assume something else
              # (probably piddle) and send to STDOUT
          $fh = *STDOUT;
       }
   }

   my @p = @_;
   my $n = (ref $p[0] eq 'ARRAY') ? $#{$p[0]}+1 : $p[0]->dim(0);
   my @dogp = ();  # need to break 2D pdls into a their 1D pdl components
   for (@p) {
      if ( ref $_ eq 'ARRAY' ) {
         barf "wcols: 1D args must have same number of elements\n" if scalar(@{$_}) != $n;
         push @dogp, $_;
      } else {
         barf "wcols: 1D args must have same number of elements\n" if $_->dim(0) != $n or $_->getndims > 2;
         if ( $_->getndims == 2 ) {
            push @dogp, $_->dog;
         } else {
            push @dogp, $_;
         }
      }
   }
   if ( defined $header ) {
       $header .= "\n" unless $header =~ m/\n$/;
       print $fh $header;
   }
   my $i;
   my $pcnt = scalar @dogp;
   for ($i=0; $i<$n; $i++) {
       if ($format_string) {
           my @d;
	   my $pdone = 0;
           for (@dogp) {
               push @d,_at_1D($_,$i); $pdone++;
               if (@d == $step) {
                   printf $fh $format_string,@d;
                   printf $fh $usecolsep unless $pdone==$pcnt;
                   $#d = -1;
               }
           }
           if (@d && !$i) {
               my $str;
               if ($#dogp>0) {
                   $str = ($#dogp+1).' columns don\'t';
               } else {
                   $str = '1 column doesn\'t';
               }
               $str .= " fit in $step column format ".
               '(even repeated) -- discarding surplus';
               carp $str;
               # printf $fh $format_string,@d;
               # printf $fh $usecolsep;
           }
       } else {
	   my $pdone = 0;
           for (@dogp) {
	       $pdone++;
               print $fh _at_1D($_,$i) . ( ($pdone==$pcnt) ? '' : $usecolsep );
           }
       }
       print $fh "\n";
   }
   close($fh) if $file_opened;
   return 1;
}

=head2 swcols

=for ref

generate string list from C<sprintf> format specifier and a list of piddles

C<swcols> takes an (optional) format specifier of the printf
sort and a list of 1D piddles as input. It returns a perl
array (or array reference if called in scalar context)
where each element of the array is the string generated by
printing the corresponding element of the piddle(s) using
the format specified. If no format is specified it uses the
default print format.

=for usage

 Usage: @str = swcols format, pdl1,pdl2,pdl3,...;
    or  $str = swcols format, pdl1,pdl2,pdl3,...;

=cut

*swcols = \&PDL::swcols;

sub PDL::swcols{
  my ($format_string,$step);

  my @outlist;

  if (ref(\$_[0]) eq "SCALAR") {
         $step = $format_string = shift; # 1st arg not piddle
         $step =~ s/(%%|[^%])//g;  # use step to count number of format items
         $step = length ($step);
  }
  
  my @p = @_;
  my $n = (ref $p[0] eq 'ARRAY') ? $#{$p[0]}+1 : $p[0]->nelem;
  for (@p) {
     if ( ref $_ eq 'ARRAY' ) {
        barf "swcols: 1D args must have same number of elements\n" if scalar(@{$_}) != $n;
     } else {
        barf "swcols: 1D args must have same number of elements\n" if $_->nelem != $n or $_->getndims!=1;
     }
  }

  my $i;
  for ($i=0; $i<$n; $i++) {
         if ($format_string) {
           my @d;
           for (@p) {
                  push @d,_at_1D($_,$i);
                  if (@d == $step) {
                         push @outlist,sprintf $format_string,@d;
                         $#d = -1;
                  }
           }
           if (@d && !$i) {
                  my $str;
                  if ($#p>0) {
                         $str = ($#p+1).' columns don\'t';
                  } else {
                         $str = '1 column doesn\'t';
                  }
                  $str .= " fit in $step column format ".
               '(even repeated) -- discarding surplus';
                  carp $str;
                  # printf $fh $format_string,@d;
                  # printf $fh $usecolsep;
           }
         } else {
           for (@p) {
                  push @outlist,sprintf _at_1D($_,$i),$usecolsep;
           }
         }
  }
  wantarray ? return @outlist: return \@outlist;
}


=head2 rgrep

=for ref

  Read columns into piddles using full regexp pattern matching.
  

  Options:
  
  UNDEFINED: This option determines what will be done for undefined 
  values. For instance when reading a comma-separated file of the type 
  C<1,2,,4> where the C<,,> indicates a missing value. 
  
  The default value is to assign C<$PDL::undefval> to undefined values,
  but if C<UNDEFINED> is set this is used instead. This would normally 
  be set to a number, but if it is set to C<Bad> and PDL is compiled
  with Badvalue support (see L<PDL::Bad/>) then undefined values are set to
  the appropriate badvalue and the column is marked as bad.
  
  DEFTYPE: Sets the default type of the columns - see the documentation for
   L</rcols()>
  
  TYPES:   A reference to a Perl array with types for each column - see 
  the documentation for L</rcols()>
  
  BUFFERSIZE: The number of lines to extend the piddle by. It might speed
  up the reading a little bit by setting this to the number of lines in the
  file, but in general L</rasc()> is a better choice

Usage

=for usage

 ($x,$y,...) = rgrep(sub, *HANDLE|"filename")

e.g.

=for example

 ($a,$b) = rgrep {/Foo (.*) Bar (.*) Mumble/} $file;

i.e. the vectors C<$a> and C<$b> get the progressive values
of C<$1>, C<$2> etc.

=cut

  sub rgrep (&@) {
     barf 'Usage ($x,$y,...) = rgrep(sub, *HANDLE|"filename", [{OPTIONS}])'
         if $#_ > 2;

     my (@ret,@v,$nret); my ($m,$n)=(-1,0); # Count/PDL size
     my $pattern = shift;

     my $is_handle = _is_io_handle $_[0];
     my $fh = $is_handle ? $_[0] : gensym;
     open $fh, $_[0] or die "File $_[0] not found\n" unless $is_handle;

     if (ref($pattern) ne "CODE") {
         die "Got a ".ref($pattern)." for rgrep?!";
     }

	
     # set up default options
     my $opt = new PDL::Options( {
         DEFTYPE => $deftype,
         TYPES => [],
         UNDEFINED => $PDL::undefval,
	 BUFFERSIZE => 10000
         } );
     # Check if the user specified options
     my $u_opt = $_[1] || {};
     $opt->options( $u_opt);

     my $options = $opt->current();   

     # If UNDEFINED is set to .*bad.* then undefined are set to
     # bad - unless we have a Perl that is not compiled with Bad support
     my $undef_is_bad = ($$options{UNDEFINED} =~ /bad/i);
     if ($undef_is_bad && !$PDL::Bad::Status) {
	carp "UNDEFINED cannot be set to Badvalue when PDL hasn't been compiled with Bad value support - \$PDL::undefval used instead\n";
        $undef_is_bad = 0;
     }        
     barf "Unknown PDL type given for DEFTYPE.\n"
        unless ref($$options{DEFTYPE}) eq "PDL::Type";


     while(<$fh>) {
         next unless @v = &$pattern;

         $m++;  # Count got
         if ($m==0) {
           $nret = $#v;   # Last index of values to return

	   # Handle various columns as in rcols - added 18/04/05
           my @types = _handle_types( $nret, $$options{DEFTYPE}, $$options{TYPES} );	
           for (0..$nret) {
                # Modified 18/04/05 to use specified precision.
	 	$ret[$_] = [ PDL->zeroes($types[$_], 1), [] ];
           }
       } else { # perhaps should only carp once...
           carp "Non-rectangular rgrep" if $nret != $#v;
       }
       if ($n<$m) {
           for (0..$nret) {
               _ext_lastD( $ret[$_]->[0], $$options{BUFFERSIZE} ); # Extend PDL in buffered manner
           }
           $n += $$options{BUFFERSIZE};
      }
       for(0..$nret) { 
	# Set values - '1*' is to ensure numeric
	# We now (JB - 18/04/05) also check for defined values or not
	# Ideally this should include Badvalue support..
	if ($v[$_] eq '') {
	   # Missing value - let us treat this specially
	   if ($undef_is_bad) {
	       set $ret[$_]->[0], $m, $$options{DEFTYPE}->badvalue();
               # And set bad flag on $ref[$_]!
               $ret[$_]->[0]->badflag(1);
           } else {
               set $ret[$_]->[0], $m, $$options{UNDEFINED};
           } 
	} else {
    	   set $ret[$_]->[0], $m, 1*$v[$_];
	}
     } 
   }
                                 
   close($fh) unless $is_handle;
   for (@ret) { $_ = $_->[0]->slice("0:$m")->copy; }; # Truncate
   wantarray ? return(@ret) : return $ret[0];
}


=head2 rdsa

=for ref

  Read a FIGARO/NDF format file.

  Requires non-PDL DSA module. Contact Frossie (frossie@jach.hawaii.edu)

Usage:

=for usage

 ([$xaxis],$data) = rdsa($file)

=for example

 $a = rdsa 'file.sdf'

Not yet tested with PDL-1.9X versions

=cut

sub rdsa{PDL->rdsa(@_)}

use vars qw/ $dsa_loaded /;
sub PDL::rdsa {
    my $class = shift;
    barf 'Usage: ([$xaxis],$data) = rdsa($file)' if $#_!=0;
    my $file = shift; my $pdl = $class->new; my $xpdl;
    eval 'use DSA' unless $dsa_loaded++;
    barf 'Cannot use DSA library' if $@ ne "";

    my $status = 0;

    # Most of this stuff stolen from Frossie:

    dsa_open($status);
    dsa_named_input('IMAGE',$file,$status);
    goto skip if $status != 0;

    dsa_get_range('IMAGE',my $vmin,my $vmax,$status);
    my @data_dims;
    dsa_data_size('IMAGE',5, my $data_ndims, \@data_dims, my $data_elements, 
                  $status);
    dsa_map_data('IMAGE','READ','FLOAT',my $data_address,my $data_slot,
                 $status);

    @data_dims = @data_dims[0..$data_ndims-1];
    print "Dims of $file = @data_dims\n" if $PDL::verbose;
    $pdl->set_datatype($PDL_F);
    $pdl->setdims([@data_dims]);
    my $dref = $pdl->get_dataref;
    mem2string($data_address,4*$data_elements,$$dref);
    $pdl->upd_data();

    if (wantarray) { # Map X axis values
      my @axis_dims;
      dsa_axis_size('IMAGE',1,5, my $axis_ndims, \@axis_dims,
                    my $axis_elements, $status);
      dsa_map_axis_data('IMAGE',1,'READ','FLOAT',my $axis_address,
                    my $axis_slot,$status);
      @axis_dims = @axis_dims[0..$axis_ndims-1];
      $xpdl = $class->new;
      $xpdl->set_datatype($PDL_F);
      $xpdl->setdims([@axis_dims]);
      my $xref = $xpdl->get_dataref;
      mem2string($axis_address,4*$axis_elements,$$xref);
      $xpdl->upd_data();
    }

    skip: dsa_close($status);

    barf("rdsa: obtained DSA error") if $status != 0;

    return ($xpdl,$pdl);
}

=head2 isbigendian

=for ref

  Determine endianness of machine - returns 0 or 1 accordingly

=cut

!NO!SUBS!

# $isbigendian is set up at top of file
pp_addpm( "sub PDL::isbigendian { return $isbigendian; };\n*isbigendian = \\&PDL::isbigendian;\n");
pp_add_exported("", "isbigendian");

################################ XS CODE ######################################

sub defpdl {
        pp_def(
                $_[0],
                Pars => $_[1],
                OtherPars => $_[2],
                Code => $_[3],
                Doc  => $_[4],
        );
}

###### Read ASCII Function ##########
pp_addhdr(<<'EOH');

#define SWALLOWLINE(fp) while ((s = PerlIO_getc(fp)) != '\n' && s != EOF)
#define    TRAILING_WHITESPACE_CHECK(s) \
   if (s!=' ' && s!='\t' && s!='\r' && s!='\n' && s!=',')  return -1

int getfloat(PerlIO *fp, PDL_Float *fz)
{
  PDL_Float f = 0;
  int nread = 0;
  int i, s = PerlIO_getc(fp);
  int afterp = 0, aftere=0;
  int expo = 0;
  PDL_Float sig = 1.0, esig = 1.0;
  PDL_Float div = 1.0;

  if (s == EOF) return 0;
  while (1) {
    if (s == EOF)
      return 0;   /* signal end of line */
    if (s == '#')
      SWALLOWLINE(fp);
    if ((s >='0' && s <='9') || s =='.' || s == 'e' || s == 'E' 
        || s == '+' || s == '-') break; 
    if (s!=' ' && s!='\t' && s!='\r' && s!='\n' && s!=',')
      return -1;  /* garbage */      
    s = PerlIO_getc(fp); /* else skip whitespace */
  }
  /* parse number */
  while (1) {
    switch (s) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      if (aftere)
        expo = (expo*10) + (s - '0');
      else if (afterp) {
        div /= 10.0;
        f += div*(s - '0');
      } else
        f = (f*10) + (s - '0');
      break;
    case '+':
      /* ignore */
      break;
    case '-':
      if (aftere)
        esig = -1;
      else
        sig = -1;
      break;
    case 'e':
    case 'E':
      if (aftere)
        return -1;
      aftere = 1;
      break;
    case '.':
      if (afterp || aftere)
        return -1;
      afterp = 1;
      break;
    default:
      goto endread;
      break;
    }
    nread++;
    s = PerlIO_getc(fp);
  }
endread:
  f *= sig;
  for (i=0;i<expo; i++)
    f *= (esig > 0 ? 10.0 : 0.1);

  *fz = f;
  TRAILING_WHITESPACE_CHECK(s);
  return nread;
}

int getdouble(PerlIO *fp, PDL_Double *fz)
{
  PDL_Double f = 0;
  int nread = 0;
  int i, s = PerlIO_getc(fp);
  int afterp = 0, aftere=0;
  int expo = 0;
  PDL_Double sig = 1.0, esig = 1.0;
  PDL_Double div = 1.0;

  if (s == EOF) return 0;
  while (1) {
    if (s == EOF)
      return 0;   /* signal end of line */
    if (s == '#')
      SWALLOWLINE(fp);
    if ((s >='0' && s <='9') || s =='.' || s == 'e' || s == 'E' 
        || s == '+' || s == '-') break; 
    if (s!=' ' && s!='\t' && s!='\r' && s!='\n' && s!=',')
      return -1;  /* garbage */      
    s = PerlIO_getc(fp); /* else skip whitespace */
  }
  /* parse number */
  while (1) {
    switch (s) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      if (aftere)
        expo = (expo*10) + (s - '0');
      else if (afterp) {
        div /= 10.0;
        f += div*(s - '0');
      } else
        f = (f*10) + (s - '0');
      break;
    case '+':
      /* ignore */
      break;
    case '-':
      if (aftere)
        esig = -1;
      else
        sig = -1;
      break;
    case 'e':
    case 'E':
      if (aftere)
        return -1;
      aftere = 1;
      break;
    case '.':
      if (afterp || aftere)
        return -1;
      afterp = 1;
      break;
    default:
      goto endread;
      break;
    }
    nread++;
    s = PerlIO_getc(fp);
  }
endread:
  f *= sig;
  for (i=0;i<expo; i++)
    f *= (esig > 0 ? 10.0 : 0.1);

  *fz = f;
  TRAILING_WHITESPACE_CHECK(s);
  return nread;
}

EOH

pp_add_exported('', 'rasc rcube');
pp_addpm(<<'EOPM');


=head2 rasc

=for ref

  Simple function to slurp in ASCII numbers quite quickly,
  although error handling is marginal (to nonexistent).

=for usage

  $pdl->rasc("filename"|FILEHANDLE [,$noElements]);

      Where:
        filename is the name of the ASCII file to read or open file handle
        $noElements is the optional number of elements in the file to read.
            (If not present, all of the file will be read to fill up $pdl).
        $pdl can be of type float or double (for more precision).

=for example

  #  (test.num is an ascii file with 20 numbers. One number per line.)
  $in = PDL->null;
  $num = 20;
  $in->rasc('test.num',20);
  $imm = zeroes(float,20,2);
  $imm->rasc('test.num');

=cut

sub rasc {PDL->rasc(@_)}
sub PDL::rasc {
  use IO::File;
  my ($pdl, $file, $num) = @_;
  $num = -1 unless defined $num;
  my $fi = $file;
  my $is_openhandle = defined fileno $fi ? 1 : 0;
  unless ($is_openhandle) {
    barf 'usage: rasc $pdl, "filename"|FILEHANDLE, [$num_to_read]'
       if !defined $file || ref $file;
    $fi = new IO::File "<$file" or barf "Can't open $file";
  }
  $pdl->_rasc(my $ierr=null,$num,$fi);
  close $fi unless $is_openhandle;
  return all $ierr > 0;
}

# ----------------------------------------------------------

=head2 rcube

=for ref

 Read list of files directly into a large data cube (for efficiency)

=for usage

 $cube = rcube \&reader_function, @files;

=for example

 $cube = rcube \&rfits, glob("*.fits");

This IO function allows direct reading of files into a large data cube,
Obviously one could use cat() but this is more memory efficient.

The reading function (e.g. rfits, readfraw) (passed as a reference)
and files are the arguments.

The cube is created as the same X,Y dims and datatype as the first
image specified. The Z dim is simply the number of images.

=cut

sub rcube {

    my $reader = shift;

    barf "Usage: blah" unless ref($reader) eq "CODE";

    my $k=0;
    my ($im,$cube,$tmp,$nx,$ny);
    my $nz = scalar(@_);

    for my $file (@_) {
       print "Slice ($k) - reading file $file...\n" if $PDL::verbose;
       $im = &$reader($file);
       ($nx, $ny) = dims $im;
       if ($k == 0) {
          print "Creating $nx x $ny x $nz cube...\n" if $PDL::verbose;
          $cube = $im->zeroes($im->type,$nx,$ny,$nz);
        }
        else {
          barf "Dimensions do not match for file $file!\n" if
             $im->getdim(0) != $nx or $im->getdim(1) != $ny ;

       }
       $tmp = $cube->slice(":,:,($k)");
       $tmp .= $im;
       $k++;
      }

      return $cube;
}


EOPM

# in the future this function should return a state indicating an error
# if appropriate
pp_def('_rasc',
       Pars => '[o] nums(n); int [o] ierr(n)',
       OtherPars => 'int num => n; SV* fd',
       GenericTypes => [F,D],
       Code => q@ 
                 int ns, i, j;
                 PerlIO *fp;
                 IO *io;

                 /* io = GvIO(gv_fetchpv($COMP(fd),FALSE,SVt_PVIO)); */
                 io = sv_2io($COMP(fd));
                 if (!io || !(fp = IoIFP(io)))
                        croak("Can\'t figure out FP");
                 ns = $SIZE(n);
                 threadloop %{
                   for (i=0;i<ns; i++) {
                       if (($ierr(n=>i) =
                           $TFD(getfloat,getdouble)(fp, &($nums(n=>i)))) <= 0)
                              break;
                   }
                   for (j=i+1; j<ns; j++)
                        $ierr(n=>j) = $ierr(n=>i); /* inherit error flags */
                 %}
                @,
#       Doc => 'Internal Function used by rasc. '
        Doc => undef,
);



pp_done();