blib/lib/PDL/IO/NDF.pm untested

filter: Statementstmt 0.0% 0 / 590 Branchbran 0.0% 0 / 276 Conditioncond 0.0% 0 / 57 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 958 SCAR 98.8
CC
139
Cov
0%
wdata
992.0
whash
650.0
find_prim
380.0
CRAP 19460.0
1  
2 # This file is automatically created by NDF.pm.PL
3 # - bad value support =
4  
5 package PDL::IO::NDF;
6  
7 =head1 NAME
8  
9 PDL::IO::NDF - PDL Module for reading and writing Starlink
10 N-dimensional data structures as PDLs.
11  
12 =head1 SYNOPSIS
13  
14 use PDL::IO::NDF;
15  
16 $a = PDL->rndf($file);
17  
18 $a = rndf('test_image');
19 $a = rndf('test_image', 1);
20  
21 $a->wndf($file);
22 wndf($a, 'out_image');
23  
24 propndfx($a, 'template', 'out_image');
25  
26 =head1 DESCRIPTION
27  
28 This module adds the ability to read and write Starlink N-dimensional data
29 files as N-dimensional PDLs.
30  
31 You must have the Starlink NDF library installed to use it. The library
32 is distributed under the GPL and is available from "http://www.starlink.ac.uk".
33  
34 =head1 FUNCTIONS
35  
36 =cut
37  
38 @EXPORT_OK = qw/rndf wndf/;
39 %EXPORT_TAGS = (Func=>[@EXPORT_OK]);
40  
41 @ISA = qw( PDL::Exporter );
42  
43 use PDL::Core;
44 use PDL::Types;
45 use PDL::Options;
46 use Carp;
47 use strict;
48  
49 use Astro::FITS::Header::Item;
50  
51 # Starlink data type conversion
52 use vars qw/%pdltypes %startypes $ndf_loaded $VERSION $EXTNAME/;
53  
54 $VERSION = '1.05';
55  
56 # Set PDL -> Starlink data types
57 %pdltypes = ("$PDL_B" => "_UBYTE", # was "_BYTE"
58 "$PDL_S" => "_WORD",
59 "$PDL_US" => "_UWORD",
60 "$PDL_L" => "_INTEGER",
61 "$PDL_F" => "_REAL",
62 "$PDL_D" => "_DOUBLE"
63 );
64  
65 # Set Starlink -> PDL data types
66 %startypes = ("_BYTE" =>$PDL_B,
67 "_UBYTE" =>$PDL_B,
68 "_WORD" =>$PDL_S,
69 "_UWORD" =>$PDL_US,
70 "_INTEGER" =>$PDL_L,
71 "_REAL" =>$PDL_F,
72 "_DOUBLE" =>$PDL_D
73 );
74  
75 # This is the name I use in the PDL header hash that contains the
76 # NDF extensions so that they can be recreated
77  
78 $EXTNAME = 'NDF_EXT';
79  
80 # load NDF library
81 sub _init_NDF {
82 return if $ndf_loaded++; # a bit pointless increasing each time?
83 # Sometimes $@ can give the wrong answer for test. Be explicit.
84 my $retval = eval 'use NDF; 1;';
85 croak "Cannot use NDF library: $@" if $retval != 1;
86 }
87  
88  
89 =head2 rndf()
90  
91 =for ref
92  
93 Reads a piddle from a NDF format data file.
94  
95 =for example
96  
97 $pdl = rndf('file.sdf');
98 $pdl = rndf('file.sdf',1);
99  
100 The '.sdf' suffix is optional. The optional second argument turns off
101 automatic quality masking and returns a quality array as well.
102  
103 A hash options version of rndf() also exists
104  
105 $pdl = rndf( 'file.sdf', nomask => 1, quickread => 1 );
106  
107 where the supported options are (defaults in square brackets):
108  
109 nomask => (boolean) Disable automatic quality masking. [false]
110 quickread => (boolean) If true, only read the primary data array and
111 FITS header [false]
112  
113 Header information and NDF Extensions are stored in the piddle as a hash
114 which can be retreived with the C<$pdl-E<gt>gethdr> command.
115 Array extensions are stored in the header as follows:
116  
117 $a - the base DATA_ARRAY
118  
119 If C<$hdr = $a-E<gt>gethdr>;
120  
121 then:
122  
123 %{$hdr} contains all the FITS headers plus:
124 $$hdr{Error} contains the Error/Variance PDL
125 $$hdr{Quality} The quality byte array (if reqeusted)
126 @{$$hdr{Axis}} Is an array of piddles containing the information
127 for axis 0, 1, etc.
128 $$hdr{NDF_EXT} Contains all the NDF extensions
129 $$hdr{Hist} Contains the history information
130 $$hdr{NDF_EXT}{_TYPES}
131 Data types for non-PDL NDF extensions so that
132 wndf can reconstruct a NDF.
133  
134 All extension information is stored in the header hash array.
135 Extension structures are preserved in hashes, so that the PROJ_PARS
136 component of the IRAS.ASTROMETRY extension is stored in
137 C<$$hdr{NDF_EXT}{IRAS}{ASTROMETRY}{'PROJ_PARS'}>. All array structures are
138 stored as arrays in the Hdr: numeric arrays are stored as PDLs,
139 logical and character arrays are stored as plain Perl arrays. FITS
140 arrays are a special case and are expanded as scalars into the header.
141  
142 PDL does not have a signed byte datatype, so any '_BYTE' data
143 is read into a C<byte> (unsigned) piddle and a warning is printed
144 to C<STDOUT>.
145  
146 =cut
147  
148 # This is one form of the new command
149  
150 sub rndf {PDL->rndf(@_)}
151  
152 # And this is the real form
153 # Allows the command to be called in OO form or as a function
154 sub PDL::rndf { # Read a piddle from a NDF file
155  
156 my $class = shift;
157 barf 'Usage: $a = rndf($file,[%args|$nomask]]); $a = PDL->rndf(...) '
158 if (@_ == 0);
159  
160 # ensure we have the NDF module
161 _init_NDF();
162  
163 # Setup the Header Hash
164 my $header = {};
165  
166 # Read in the filename
167 # And setup the new PDL
168 my $file = shift;
169 my $pdl = $class->new;
170  
171 # only one argument suggests we are using the old API, two
172 # or more indicates the hash API
173 my %opts = (nomask => 0, quickread => 0);
174 if (@_ == 1) {
175 $opts{nomask} = shift;
176 } else {
177 my %args = @_;
178 %opts = iparse( \%opts, \%args );
179 }
180  
181 my ($infile, $status, $indf, $entry, @info, $value);
182  
183 # Strip trailing .sdf if one is present
184 # remove the trailing extension names
185 # (anything after a `.' UNLESS it's part of a directory
186 # name, hence the check for ^/) and any trailing (...)
187 # specifier (NDF sections, a la PDL slices)
188 #
189 $file =~ s/\.sdf$//;
190  
191 $infile = $file;
192 $infile =~ s!\.[^/]*$!!;
193 $infile =~ s/\(.*\)$//;
194  
195 # If file is not there
196 croak "Cannot find $infile.sdf" unless -e "$infile.sdf";
197  
198 # Set status
199 $status = &NDF::SAI__OK;
200  
201 # Begin NDF and ERR session
202 err_begin($status);
203 ndf_begin();
204  
205 # Open the file
206 ndf_find(&NDF::DAT__ROOT(), $file, $indf, $status);
207  
208 # unset automatic quality masking if nomask is true
209 ndf_sqmf(!$opts{nomask}, $indf, $status);
210  
211 # Read the data array (need to pass the header as well)
212 my $badflag;
213 ( $status, $badflag ) = rdata($indf, $pdl, \%opts, $header, $class, $status);
214  
215 # Read the axes
216 $status = raxes($indf, $pdl, $header, $class, $status) unless $opts{quickread};
217  
218 # Read the header
219 $status = rhdr($indf, $pdl, $header, \%opts, $class, $status);
220  
221 # Read history information
222 $status = rhist($indf, $pdl, $header, $status) unless $opts{quickread};
223  
224 # Read labels
225 @info = ('Label', 'Title', 'Units');
226 for $entry (@info) {
227 $value = 'NULL';
228 ndf_cget($indf, $entry, $value, $status);
229 $$header{"$entry"} = $value if $value ne 'NULL';
230 print "$entry is $value\n" if ($PDL::verbose && $value ne 'NULL');
231 undef $value;
232 }
233  
234 # Tidy up
235 ndf_annul($indf, $status);
236 ndf_end($status);
237  
238 if ($status != &NDF::SAI__OK) {
239 my $starstat = $status;
240 my $starerr = err_flush_to_string($status);
241 err_end($status);
242 croak("rndf: Starlink NDF error reading $file ($starstat):\n$starerr\n");
243 }
244  
245 err_end($status);
246  
247 # Put the header into the main pdl
248 $pdl->sethdr($header);
249  
250 return $pdl;
251 }
252  
253 =head2 wndf()
254  
255 =for ref
256  
257 Writes a piddle to a NDF format file:
258  
259 =for example
260  
261 $pdl->wndf($file);
262 wndf($pdl,$file);
263  
264 wndf can be used for writing PDLs to NDF files.
265 The '.sdf' suffix is optional. All the extensions
266 created by rndf are supported by wndf. This means that error, axis
267 and quality arrays will be written if they exist. Extensions are also
268 reconstructed by using their name (ie FIGARO.TEST would be expanded as
269 a FIGARO extension and a TEST component). Hdr keywords Label, Title
270 and Units are treated as special cases and are written to the label,
271 title and units fields of the NDF.
272  
273 Header information is written to corresponding NDF extensions.
274 NDF extensions can also be created in the {NDF} hash by using a key
275 containing '.', ie {NDF}{'IRAS.DATA'} would write the information to
276 an IRAS.DATA extension in the NDF. rndf stores this as
277 C<$$hdr{NDF}{IRAS}{DATA}> and the two systems are interchangeable.
278  
279 rndf stores type information in {NDF}{'_TYPES'} and below so that
280 wndf can reconstruct the data type of non-PDL extensions. If no
281 entry exists in _TYPES, wndf chooses between characters, integer and
282 double on a best guess basis. Any perl arrays are written as CHAR
283 array extensions (on the assumption that numeric arrays will exist as
284 PDLs).
285  
286 =cut
287  
288 # This is one form of the new command
289 # OO version.
290  
291 *wndf = \&PDL::wndf;
292  
293 # And this is the real form
294 # Allows the command to be called in OO form or as a function
295 sub PDL::wndf { # Write a PDL to an NDF format file
296  
297 barf 'Usage: wndf($pdl,$file)' if $#_!=1;
298  
299 # ensure we have the NDF module
300 _init_NDF();
301  
302 my ($indf, $place, $status, $outndf);
303 my (@lbnd, @ubnd);
304  
305 my ($pdl, $outfile) = @_;
306  
307 # Check that we are dealing with a PDL
308 croak 'Argument is not a PDL variable' unless $pdl->isa('PDL');
309  
310 # Set status
311 $status = &NDF::SAI__OK;
312  
313 # Strip trailing .sdf if one is present
314 $outfile =~ s/\.sdf$//;
315  
316 # Begin context
317 ndf_begin();
318 err_begin($status);
319  
320 # Open the new file
321 ndf_place(&NDF::DAT__ROOT(), $outfile, $place, $status);
322  
323 # Need to create data_array component
324 # Change the bounds to match the PDL
325  
326 @ubnd = $pdl->dims;
327 @lbnd = ();
328 @lbnd = map { 1 } (0..$#ubnd);
329  
330 ndf_new($pdltypes{$pdl->get_datatype}, $#ubnd+1, \@lbnd, \@ubnd, $place,
331 $outndf, $status);
332  
333 # Set the application name
334 ndf_happn('PDL::wndf', $status);
335  
336 # Write the data to this file
337 $status = wdata($outndf, $pdl, $status);
338  
339 # Write the header and title
340 $status = whdr($outndf, $pdl, $status);
341  
342 # Create a history extension
343 ndf_hcre($outndf, $status);
344  
345 # Annul the identifier
346 ndf_annul($outndf, $status);
347  
348 # End context
349 ndf_end($status);
350  
351 if ($status != &NDF::SAI__OK) {
352 my $starstat = $status;
353 my $starerr = err_flush_to_string($status);
354 err_end($status);
355 croak "wndf: Starlink error writing NDF $outfile ($starstat)\n$starerr\n";
356 }
357  
358 err_end($status);
359  
360 return 1;
361 }
362  
363 =head2 propndfx()
364  
365 Routine to write a PDL to an NDF by copying the extension information
366 from an existing NDF and writing DATA,VARIANCE, QUALITY and AXIS info
367 from a PDL (if they exist).
368  
369 Extensions, labels and history are propogated from the old NDF.
370 No new extension information is written.
371  
372 This command has been superseded by L<wndf()|/wndf()>.
373  
374 =cut
375  
376 *propndfx = \&PDL::propndfx;
377  
378 sub PDL::propndfx { # Write a PDL to a NDF format file
379  
380 barf 'Usage: propndfx($pdl, $infile, $outfile)' if $#_!=2;
381  
382 # ensure we have the NDF module
383 _init_NDF();
384  
385 my ($indf, $in_place, $status, $outplace, $outndf);
386  
387 my ($pdl, $infile, $outfile) = @_;
388  
389 # Set status
390 $status = &NDF::SAI__OK;
391  
392 # Strip trailing .sdf if one is present
393 $outfile =~ s/\.sdf$//;
394 $infile =~ s/\.sdf$//;
395 # File is the first thing before a .
396 my $file = (split(/\./,$infile))[0];
397  
398 croak "$file does not exist\n" unless -e "$file.sdf";
399  
400 # Begin context
401 ndf_begin();
402 err_begin($status);
403  
404 # Open the old file
405 ndf_find(&NDF::DAT__ROOT(), $infile, $indf, $status);
406  
407 # Set the application name
408 ndf_happn('PDL::propndfx', $status);
409  
410 # Open the new file
411 ndf_place(&NDF::DAT__ROOT(), $outfile, $outplace, $status);
412  
413 # Copy the extension information to outfile
414 ndf_scopy($indf, ' ', $outplace, $outndf, $status);
415  
416 # Annul the input file identifier
417 ndf_annul($indf, $status);
418  
419 # Write the data to this file
420 $status = wdata($outndf, $pdl, $status);
421  
422 # Annul the identifier
423 ndf_annul($outndf, $status);
424  
425 # End context
426 ndf_end($status);
427  
428 if ($status != &NDF::SAI__OK) {
429 my $starstat = $status;
430 my $starerr = err_flush_to_string($status);
431 err_end($status);
432 croak "propndfx: Starlink error propagating from $infile to $outfile ($starstat)\n$starerr\n";
433 }
434  
435 err_end($status);
436  
437 return 1;
438 }
439  
440 =head1 NOTES
441  
442 The perl NDF module must be available. This is available from
443 Starlink (http://www.starlink.ac.uk).
444  
445 If an NDF is read which contains AST World Coordinate information
446 (a .WCS component) this information is currently ignored. Currently
447 WCS information can only be written and stored using standard FITS headers.
448 See L<http://www.starlink.ac.uk/ast> for more information on AST.
449  
450 =head1 AUTHOR
451  
452 This module was written by Tim Jenness E<lt>tjenness@cpan.orgE<gt>.
453  
454 PDL bad value support was added by Douglas Burke E<lt>dburke@cfa.harvard.eduE<gt>.
455  
456 Copyright (C) 1998 - 2012 Tim Jenness. All Rights Reserved. This program is free
457 software; you can redistribute it and/or modify it under the same
458 terms as Perl itself.
459  
460 =head1 SEE ALSO
461  
462 L<PDL::FAQ> for general information on the Perl Data language,
463 L<NDF> for information on the NDF module.
464  
465 =cut
466  
467  
468 #######################################################################
469  
470 # These are the generic routines used by the rndf command
471  
472 # RDATA
473 # Read Data, Quality and Variance
474  
475 # returns ( $status, $badflag ), where $badflag is:
476 #
477 # 1 - the piddle may contain bad data
478 # 0 - the piddle contains no bad data
479 #
480 # This reports starlink's bad-data flag (ie it's valid
481 # even in bad value support is not available in PDL)
482 #
483 sub rdata {
484 my ($indf, $pdl, $optref, $header, $class, $status) = @_;
485  
486 return ( $status, undef ) if $status != &NDF::SAI__OK;
487  
488 my ($maxdims, $ndim, @dim, $dcomp, $tcomp, $exist);
489 my ($type, $data_pntr, $el, $temppdl, $nbytes, $badbit, $dref);
490  
491 ####################################################################
492 # D I M S #
493 ####################################################################
494  
495 # Find the dimensions of the data array
496 $maxdims = 100; # Maximum number of dimensions allowed
497  
498 &ndf_dim($indf, $maxdims, \@dim, $ndim, $status);
499 @dim = @dim[0..$ndim-1];
500  
501 print "Dims = @dim\n" if $PDL::verbose;
502  
503 $$header{Extensions} = [];
504  
505 ####################################################################
506 # D A T A + V A R I A N C E + Q U A L I T Y #
507 ####################################################################
508  
509 my $badflag = 0;
510  
511 my @comps = ( "Data" );
512 if (!$optref->{quickread}) {
513 # we can read additional components
514 push(@comps, "Error");
515 push(@comps, 'Quality') if $optref->{nomask};
516 }
517  
518 for $dcomp (@comps) {
519  
520 $tcomp = $dcomp;
521 $tcomp = 'Variance' if $tcomp eq 'Error';
522  
523 ndf_state($indf, $tcomp, $exist, $status);
524  
525 if ($exist && ($status == &NDF::SAI__OK)) {
526  
527 # Find the type of the data array
528 ndf_type($indf, $tcomp, $type, $status);
529  
530 # Map the data array
531 ndf_map($indf, $dcomp, $type, 'READ', $data_pntr, $el, $status);
532  
533 # Check the bad-data status of this component
534 my $this_badflag = 0;
535 my $ecomp = ( $dcomp =~ /Err/ ? "Variance" : $dcomp);
536 ndf_bad($indf, $ecomp, 0, $this_badflag, $status );
537  
538 if ($status == &NDF::SAI__OK) {
539  
540 print "Reading $dcomp array...\n" if $PDL::verbose;
541  
542 # combine the bad data flag with the "global" one for
543 # the file
544 $badflag |= ($this_badflag != 0);
545  
546 # Create a temporary PDL to deal with separate components
547 if ($dcomp eq 'Data') {
548 $temppdl = $pdl;
549 } else {
550 $dcomp = 'Errors' if $dcomp eq 'Error';
551 $$header{"$dcomp"} = $class->new;
552 $temppdl = $$header{"$dcomp"};
553 }
554  
555 # Set up the PDL
556 $temppdl->set_datatype($startypes{$type});
557 $temppdl->setdims([@dim]);
558 $dref = $temppdl->get_dataref;
559  
560 # warning about data loss
561 if ( $type eq "_BYTE" ) {
562 warn "Warning: NDF type (signed byte) converted to PDL's unsigned byte.\n";
563 }
564  
565 # How many bytes in this data type?
566 $type =~ s/^_|^_U//;
567 $nbytes = &NDF::byte_size($type);
568  
569 mem2string($data_pntr, $nbytes*$el, $$dref);
570 $temppdl->upd_data();
571  
572 push(@{$$header{Extensions}}, $dcomp) if $dcomp ne 'Data';
573  
574 if ($dcomp eq 'Quality') {
575 # Quality bad bit mask
576 ndf_bb($indf, $badbit, $status);
577  
578 my $qhdr = {};
579 $$qhdr{BADBIT} = $badbit;
580 $temppdl->sethdr($qhdr);
581 }
582  
583 # Free temporary PDL
584 undef $temppdl;
585 }
586  
587 ndf_unmap($indf, $tcomp, $status);
588 }
589 }
590  
591 return ( $status, $badflag );
592 }
593  
594  
595  
596 ####################################################################
597 # A X I S #
598 ####################################################################
599  
600 # Axes are stored as follows:
601 # Array of PDL axes as an array in header of main pdl (called 'Axis')
602 # Header of this PDL contains label and errors and units etc.
603  
604 sub raxes {
605 my ($indf, $pdl, $header, $class, $status) = @_;
606  
607 return $status if $status != &NDF::SAI__OK;
608  
609 my ($there, $naxis, @dims, $axcomp, $exist, $axtype, $axpntr, $el);
610 my ($nbytes, $temppdl, $tcomp, $daxref, $dref);
611 my ($axhdr, $ndims);
612  
613 # Read in axis information
614 ndf_state($indf, 'Axis', $there, $status);
615  
616 $ndims = $pdl->getndims; # Find number of dimensions
617  
618 if ($there) {
619  
620 # Label from 0..$#dims to match array index handling
621 # Want to put the axes into an array of axes
622 # And update the extensions field
623 $$header{Axis} = [];
624 push(@{$$header{Extensions}}, "Axis");
625  
626 for $naxis (0..$ndims-1) {
627 # Does a CENTRE component exist
628 $axcomp = 'CENTRE';
629 ndf_astat($indf, $axcomp, $naxis+1, $exist, $status);
630  
631 if ($exist && ($status == &NDF::SAI__OK)) {
632  
633 print "Reading Axis $naxis...\n" if $PDL::verbose;
634 ndf_atype($indf, $axcomp, $naxis+1, $axtype, $status);
635  
636 ndf_amap($indf, $axcomp, $naxis+1, $axtype, 'READ', $axpntr,
637 $el, $status);
638  
639 # Set up new PDL for axis info if map was okay
640 if ($status == &NDF::SAI__OK) {
641 print "Number of elements: $el\n" if $PDL::verbose;
642 $$header{Axis}[$naxis] = $class->new;
643 $temppdl = $$header{Axis}[$naxis];
644 $temppdl->set_datatype($startypes{$axtype});
645 $temppdl->setdims([$el]);
646 $dref = $temppdl->get_dataref;
647  
648  
649 # How many bytes?
650 $axtype =~ s/^_|^_U//;
651 $nbytes = &NDF::byte_size($axtype);
652  
653 mem2string($axpntr, $nbytes*$el, $$dref);
654 $temppdl->upd_data();
655  
656 # Header info for axis
657 $axhdr = {}; # somewhere to put the pdl
658  
659 # Read VARIANCE array if there
660 $axcomp = 'Error';
661 $tcomp = 'Variance';
662 ndf_astat($indf, $tcomp, $naxis+1, $exist, $status);
663  
664 if ($exist && ($status == &NDF::SAI__OK)) {
665 print "Reading Axis $naxis errors...\n" if $PDL::verbose;
666 ndf_atype($indf, $tcomp, $naxis+1, $axtype, $status);
667  
668 ndf_amap($indf, $axcomp, $naxis+1, $axtype, 'READ', $axpntr,
669 $el, $status);
670  
671 # Set up new PDL for axis info if map was okay
672 if ($status == &NDF::SAI__OK) {
673  
674 $$axhdr{Errors} = $class->new;
675 $$axhdr{Extensions} = ["Errors"];
676  
677 $$axhdr{Errors}->set_datatype($startypes{$axtype});
678 $$axhdr{Errors}->setdims([$el]);
679 $daxref = $$axhdr{Errors}->get_dataref;
680  
681 # How many bytes?
682 $axtype =~ s/^_|^_U//;
683 $nbytes = &NDF::byte_size($axtype);
684  
685 mem2string($axpntr, $nbytes*$el, $$daxref);
686 $$axhdr{Errors}->upd_data();
687  
688 }
689 }
690  
691 # Get label and units
692 for my $entry ('Units', 'Label') {
693 ndf_astat($indf, $entry, $naxis+1, $exist, $status);
694 if ($exist) {
695 my $value = '';
696 ndf_acget($indf,$entry, $naxis+1, $value, $status);
697 $axhdr->{"$entry"} = $value;
698 }
699 }
700 }
701 ndf_aunmp($indf,'*',$naxis+1,$status);
702  
703 # Now store this header into temppdl
704 $temppdl->sethdr($axhdr);
705  
706 }
707  
708 }
709  
710 }
711  
712 return $status;
713 }
714  
715  
716 ####################################################################
717 # E X T E N S I O N S #
718 ####################################################################
719  
720 sub rhdr {
721 my ($indf, $pdl, $header, $optref, $class, $status) = @_;
722  
723 return $status if $status != &NDF::SAI__OK;
724  
725 my ($nextn, $xname, $xloc, $extn, $size, $entry, $value);
726 my ($comment, $item, $el);
727  
728 # Read in any header information from the extensions
729  
730 ndf_xnumb($indf, $nextn, $status);
731 print "Reading in header information...\n"
732 if (($nextn > 0) && $PDL::verbose);
733  
734 # Read in extensions one at a time
735 for $extn (1..$nextn) {
736  
737 $xname = 'NULL';
738 ndf_xname($indf, $extn, $xname, $status);
739  
740 undef $xloc;
741 ndf_xloc($indf, $xname, 'READ', $xloc, $status);
742  
743 # We only read a FITS header if quickread is enabled
744 if ($optref->{quickread} && $xname ne 'FITS') {
745 dat_annul( $xloc, $status );
746 next;
747 }
748  
749 # FITS is a special case and must be expanded
750 if ($xname eq 'FITS') {
751 # Read in the data
752 my @fits;
753 dat_size($xloc, $size, $status);
754 &dat_getvc($xloc, $size, \@fits, $el, $status);
755  
756 if ($status == &NDF::SAI__OK) {
757 print "Reading FITS header...\n" if $PDL::verbose;
758 # unfortunately we can not store a tied Astro::FITS::Header object
759 # because we are storing other things in the header
760 for my $card (@fits) {
761 my $item = Astro::FITS::Header::Item->new( Card => $card );
762 $header->{$item->keyword} = $item->value;
763 $header->{'_COMMENTS'}{$item->keyword} = $item->comment;
764 }
765 }
766 } else {
767  
768 # Read in extensions to $EXTNAME
769 $status = &find_prim($xloc, \%{$$header{$EXTNAME}}, $class, $status);
770 }
771  
772 dat_annul($xloc, $status);
773 }
774 return $status;
775 }
776  
777 ####################################################################
778 # H I S T O R Y #
779 ####################################################################
780  
781 sub rhist {
782 my ($indf, $pdl, $header, $status) = @_;
783  
784 return $status if $status != &NDF::SAI__OK;
785  
786 my $has_hist;
787 ndf_state( $indf, "HISTORY", $has_hist, $status );
788 return $status unless $has_hist;
789  
790 my ($nrec, $app, $date, $i);
791  
792 # Read HISTORY information into a Hist header
793  
794 ndf_hnrec($indf,$nrec,$status);
795  
796 if ($status == &NDF::SAI__OK && ($nrec > 0)) {
797 print "Reading history information into 'Hist'...\n" if $PDL::verbose;
798  
799 $$header{Hist}{'Nrecords'} = $nrec;
800  
801 # Loop through the history components and find last "APPLICATION"
802 for $i (1..$nrec) {
803  
804 ndf_hinfo($indf, 'APPLICATION', $i, $app, $status);
805 ndf_hinfo($indf, 'DATE', $i, $date, $status);
806  
807 $$header{Hist}{"Application$i"} = $app;
808 $$header{Hist}{"Date$i"} = $date;
809  
810 print " $app on $date\n" if $PDL::verbose;
811 }
812 }
813 return $status;
814 }
815  
816  
817  
818 ################ Generic routines ###########################
819 #################### INTERNAL ###############################
820  
821 # Find primitive components below a given HDS locator
822 # FITS information is stored in Hdr
823 # NDF extensions stored in NDF
824  
825 sub find_prim {
826  
827 my ($loc, $href, $class, $status) = @_;
828 my ($prim, $type, $size, @dim, $ndims, $struct, $name, $nloc, $el);
829 my ($value, @values, $item, $entry, $maxdims);
830 my ($packtype, $ncomp, $packed, $comp);
831 my ($pntr, $nbytes, $comment, $dref);
832  
833 # Return if bad status
834 return $status if $status != &NDF::SAI__OK;
835  
836 # Most dimensions
837 $maxdims = 7;
838  
839 # Is it a primitive component
840 dat_prim($loc, $prim, $status);
841  
842 # Type, size and shape
843 dat_type($loc, $type, $status);
844 dat_size($loc, $size, $status);
845 dat_shape($loc, $maxdims, \@dim, $ndims, $status);
846 dat_name($loc, $name, $status);
847  
848 if ($prim) {
849 print "\tReading component: $name ($type) " if $PDL::verbose;
850  
851 # Store type of information
852 $$href{"_TYPES"}{"$name"} = $type;
853  
854 # Read it into the header
855 if (($size == 1) && ($ndims == 0)) {
856 dat_state( $loc, my $isdefined, $status );
857 if (!$isdefined) {
858 $value = undef;
859 } elsif ($type eq '_DOUBLE') {
860 # dat_get0c doesn't return full precision for doubles
861 dat_get0d($loc, $value, $status);
862 err_rep("", "Error reading $type $name scalar as double",
863 $status ) if $status != &NDF::SAI__OK;
864 } else {
865 dat_get0c($loc, $value, $status);
866 err_rep("", "Error reading scalar $name with type $type as string",
867 $status ) if $status != &NDF::SAI__OK;
868 }
869  
870 $$href{"$name"} = $value if ($status == &NDF::SAI__OK);
871 undef $value;
872  
873 } else {
874 @dim = @dim[0..$ndims-1];
875  
876 # Inform the user of dimensions
877 print "[@dim]" if $PDL::verbose;
878  
879 # Map arrays (don't need to unpack them)
880 if ($type =~ /CHAR|LOG/) {
881  
882 # Read in the data
883 dat_getvc($loc, $size, \@values, $el, $status);
884  
885 if ($status != &NDF::SAI__OK) {
886 err_rep("", "Error reading $name of type $type as string.",
887 $status );
888 } else {
889 $$href{"$name"} = [@values];
890 undef @values;
891 }
892  
893 } else {
894  
895 # map the data
896 dat_mapv($loc, $type, 'READ', $pntr, $el, $status);
897  
898 if ($status != &NDF::SAI__OK) {
899 err_rep("", "Error mapping $name with type $type", $status);
900 }
901  
902  
903 if ($status == &NDF::SAI__OK) {
904 # Create the pdl
905 $$href{"$name"} = $class->new;
906 $$href{"$name"}->set_datatype($startypes{$type});
907 $$href{"$name"}->setdims([@dim]);
908 $dref = $$href{"$name"}->get_dataref();
909  
910 # How many bytes in this data type?
911 $type =~ s/^_|^_U//;
912 $nbytes = &NDF::byte_size($type);
913  
914 mem2string($pntr, $nbytes*$el, $$dref);
915 $$href{"$name"}->upd_data();
916 }
917  
918 dat_unmap($loc,$status);
919 }
920 }
921 print "\n" if $PDL::verbose;
922  
923 } else {
924  
925 my ($ndimx, @dim, $ndim);
926 dat_shape($loc, 7, \@dim, $ndim, $status);
927  
928 # If we have a single dimension ($ndim=0) then
929 # proceed. Cant yet cope with multi-dimensional
930 # extensions
931 if ($ndim == 0) {
932 dat_ncomp($loc, $ncomp, $status);
933 print "$name ($type) has $ncomp components\n" if $PDL::verbose;
934  
935 # Store type of extension
936 $$href{$name}{"_TYPES"}{STRUCT}{"$name"} = $type;
937  
938 for $comp (1..$ncomp) {
939 dat_index($loc, $comp, $nloc, $status);
940 $status = &find_prim($nloc, \%{$$href{$name}}, $class, $status);
941 dat_annul($nloc, $status);
942 }
943 } else {
944 print "Extension $name is an array structure -- skipping\n"
945 if $PDL::verbose;
946 }
947  
948 }
949 return $status;
950 }
951  
952  
953 ###### Routines for WRITING data ######################################
954  
955 sub wdata {
956  
957 my ($outndf, $pdl, $status) = @_;
958 my (@bounds, $ndims, @lower, @comps, $dcomp, $temppdl, $type);
959 my ($pntr, $el, $nbytes, $axis, $axcomp, $axpntr, %hdr, %axhdr);
960 my ($entry, $value, $i, $axndims, $axtype, $tcomp, @acomps);
961  
962  
963 # Return if bad status
964 return $status if $status != &NDF::SAI__OK;
965  
966 ####################################################################
967 # D I M S #
968 ####################################################################
969 # Change the bounds to match the PDL
970 @bounds = $pdl->dims;
971 $ndims = $#bounds;
972 @lower = map { 1 } (0..$ndims);
973  
974 &ndf_sbnd($ndims+1, \@lower, \@bounds, $outndf, $status);
975  
976  
977 ####################################################################
978 # D A T A + V A R I A N C E + Q U A L I T Y #
979 ####################################################################
980 # Map data, variance, quality...
981 @comps = ('Data','Errors','Quality');
982  
983 # Retrieve header and check that the header is a hash ref
984 my $hdr = $pdl->gethdr;
985 if (ref($hdr) eq 'HASH') {
986 %hdr = %$hdr;
987 } else {
988 %hdr = ();
989 }
990  
991 for $dcomp (@comps) {
992  
993 if ($dcomp eq 'Data') {
994 $temppdl = $pdl;
995 } else {
996 if (exists $hdr{"$dcomp"}) {
997 $temppdl = $hdr{"$dcomp"};
998 # Check that we have a PDL
999 next unless UNIVERSAL::isa($temppdl, 'PDL');
1000 } else {
1001 next; # Skip this component
1002 }
1003 }
1004  
1005 # Check that we have some data
1006 if ($temppdl->nelem > 0) {
1007  
1008 if (($dcomp eq 'Quality') && ($temppdl->get_datatype != $PDL_B)) {
1009 # Quality must be bytes so convert to BYTE if this is not true
1010 $temppdl = byte ($$pdl{"$dcomp"});
1011 }
1012  
1013 $type = $pdltypes{$temppdl->get_datatype};
1014 $type = '_UBYTE' if $dcomp eq 'Quality'; # No choice for QUALITY
1015  
1016 # Set the output type of the NDF
1017 $tcomp = $dcomp;
1018 $tcomp = 'Variance' if $tcomp eq 'Errors';
1019 ndf_stype($type, $outndf, $tcomp, $status) unless $dcomp eq 'Quality';
1020  
1021 print "Mapping $dcomp , $type\n" if $PDL::verbose;
1022 # Map NDF
1023 $dcomp = 'Error' if $dcomp eq 'Errors';
1024 ndf_map($outndf, $dcomp, $type, 'WRITE', $pntr, $el, $status);
1025  
1026 if ($status == &NDF::SAI__OK) {
1027 # Number of bytes per entry
1028 $nbytes = PDL::Core::howbig($temppdl->get_datatype);
1029  
1030 # Convert to 1D data stream
1031 my $p1d = $temppdl->clump(-1);
1032 # Total number of bytes
1033 $nbytes *= $p1d->getdim(0);
1034  
1035 # Copy to disk
1036 string2mem(${$temppdl->get_dataref}, $nbytes, $pntr);
1037  
1038 # Write badbit mask
1039 if ($dcomp eq 'Quality') {
1040 ndf_sbb($$temppdl{Hdr}{BADBIT}, $outndf, $status)
1041 if defined $$temppdl{Hdr}{BADBIT};
1042 }
1043 }
1044 # Unmap Data
1045 ndf_unmap($outndf, $tcomp, $status);
1046  
1047 }
1048  
1049 # free the temporary pdl
1050 undef $temppdl;
1051  
1052 }
1053  
1054  
1055 ####################################################################
1056 # A X I S #
1057 ####################################################################
1058 # A X I S information is expected as an array in the header
1059 # called 'Axis'. These PDLs contain the CENTRE data and any further
1060 # info is stored in their header.
1061 # @bounds is accessed to find expected shape
1062  
1063  
1064 # Simply look in the header for a Axis
1065 if (exists $hdr{Axis}) {
1066 # Check that we have an array
1067 if (ref($hdr{Axis}) eq 'ARRAY') {
1068 # Now loop over axes
1069 for my $i (0..$#{$hdr{Axis}} ) {
1070 # Loop unless status is bad
1071 last unless $status == &NDF::SAI__OK;
1072  
1073 # Extract the ith axis PDL from the array
1074 my $axis = $hdr{Axis}->[$i];
1075  
1076 # If we have a PDL
1077 if (UNIVERSAL::isa($axis, 'PDL')) {
1078 # We now want to copy the data and if necessary the
1079 # Error array. Since there are only two I will do it the
1080 # long way by explcitly storing data and then error
1081  
1082 # Set data type
1083 $axtype = $pdltypes{$axis->get_datatype};
1084 ndf_astyp($axtype, $outndf, 'Centre', $i+1, $status);
1085  
1086 # Okay we can now map this pdl
1087 ndf_amap($outndf, 'Centre', $i+1, $axtype, 'WRITE', $axpntr,
1088 $el, $status);
1089  
1090 # Check that we have the correct number of entries
1091 my $nelem = $axis->nelem;
1092 if ($el == $nelem) {
1093 print "Mapping axis " , $i+1 , "\n" if $PDL::verbose;
1094  
1095 # Number of bytes per entry
1096 $nbytes = PDL::Core::howbig($axis->get_datatype) * $el;
1097  
1098 # Copy to disk
1099 string2mem( $ { $axis->get_dataref }, $nbytes, $axpntr)
1100 if ($status == &NDF::SAI__OK);
1101  
1102 } else {
1103 carp "Axis ",$i+1 .
1104 " is the wrong size ($el values required but got ".
1105 $nelem . ")- ignoring";
1106 }
1107 # Unmap
1108 ndf_aunmp($outndf, '*', $i+1, $status);
1109  
1110 # Errors
1111 my $axhdr = $axis->gethdr; # Retrieve and check header
1112 if (ref($axhdr) eq 'HASH') {
1113 %axhdr = %$axhdr;
1114 } else {
1115 %axhdr = ();
1116 }
1117  
1118 # Look for an Errors component in the header hash
1119 if (exists $axhdr{Errors}) {
1120 my $axerr = $axhdr{Errors};
1121 if (UNIVERSAL::isa($axerr, 'PDL')) {
1122  
1123 # Set data type
1124 $axtype = $pdltypes{$axerr->get_datatype};
1125 ndf_astyp($axtype, $outndf, 'Variance', $i+1, $status);
1126  
1127 # Okay we can now map this pdl
1128 ndf_amap($outndf, 'Errors', $i+1, $axtype, 'WRITE',
1129 $axpntr, $el, $status);
1130  
1131 # Check that we have the correct number of entries
1132 my $nelem = $axerr->nelem;
1133 if ($nelem == $el) {
1134 print "Mapping errors for axis " . $i+1 . "\n"
1135 if $PDL::verbose;
1136  
1137 # Number of bytes per entry
1138 $nbytes = PDL::Core::howbig($axerr->get_datatype) * $el;
1139  
1140 # Copy to disk
1141 string2mem($ {$axerr->get_dataref}, $nbytes, $axpntr)
1142 if ($status == &NDF::SAI__OK);
1143  
1144 } else {
1145 carp "Error PDL for Axis ",$i+1,
1146 " is the wrong size ($el values required but got ".
1147 $axerr->nelem . ")- ignoring";
1148 }
1149 # Unmap
1150 ndf_aunmp($outndf, '*', $i+1, $status);
1151  
1152 }
1153  
1154 }
1155  
1156 # Now character components
1157 foreach my $char (keys %axhdr) {
1158 if ($char =~ /LABEL|UNITS/i) {
1159 $value = $axhdr{"$char"};
1160 ndf_acput($value, $outndf, $char, $i+1, $status)
1161 if length($value) > 0;
1162 }
1163  
1164 }
1165  
1166 }
1167  
1168 }
1169  
1170 }
1171  
1172 }
1173  
1174 return $status;
1175 }
1176  
1177  
1178 # Write header information to NDF extension
1179 # This routine does not reconstruct an NDF identically to one that
1180 # was read in. FITS extensions are made. All non-integer numeric types
1181 # are written as doubles (apart from PDLs which carry there own type
1182 # information) unless _TYPES information exists in {NDF}.
1183  
1184  
1185 sub whdr {
1186  
1187 my ($outndf, $pdl, $status) = @_;
1188  
1189 my (%header, @fitsdim, $fitsloc, $value);
1190 my (%unused, @fits, $hashref, $hdr);
1191  
1192 # Return if bad status
1193 return $status if $status != &NDF::SAI__OK;
1194  
1195 print "Writing header information...\n" if $PDL::verbose;
1196  
1197 # Write FITS header from {Hdr}
1198  
1199 # Retrieve and check header from PDL
1200 $hdr = $pdl->gethdr;
1201 if (ref($hdr) eq 'HASH') {
1202 %header = %$hdr;
1203 } else {
1204 %header = ();
1205 }
1206  
1207 %unused = ();
1208 @fits = ();
1209  
1210 foreach my $key (sort keys %header) {
1211  
1212 next if $key eq '_COMMENTS';
1213  
1214 if ($key =~ /^TITLE$|^UNITS$|^LABEL$/i) {
1215 # This is not extension info
1216 ndf_cput($header{$key}, $outndf, $key, $status)
1217 if length($header{$key}) > 0;
1218 next;
1219 }
1220  
1221 # Only write scalars
1222 if (not ref($header{"$key"})) {
1223  
1224 my $item = Astro::FITS::Header::Item->new( Keyword => $key,
1225 Value => $header{$key},
1226 Comment => $header{'_COMMENTS'}{$key});
1227 if (defined $item) {
1228 push(@fits, $item->card() );
1229 } else {
1230 $unused{$key} = $header{$key};
1231 }
1232 } else {
1233 # Deal with later
1234 $unused{$key} = $header{$key};
1235 }
1236  
1237 }
1238  
1239 # Write the FITS extension
1240 if ($#fits > -1) {
1241 push(@fits, "END");
1242 # Write it out
1243 @fitsdim = ($#fits+1);
1244 ndf_xnew($outndf, 'FITS', '_CHAR*80', 1, @fitsdim, $fitsloc, $status);
1245 dat_put1c($fitsloc, $#fits+1, \@fits, $status);
1246 dat_annul($fitsloc, $status);
1247 }
1248  
1249 # Loop through all NDF header info and array Hdr information
1250 # Note that %unused still contains our NDF hash so
1251 # we must remove that before proceeding (else we end up with
1252 # an 'NDF_EXT' extension!
1253  
1254 delete $unused{$EXTNAME};
1255  
1256 foreach $hashref (\%unused, $header{$EXTNAME}) {
1257 $status = whash($hashref, $outndf, '', '', $status);
1258 }
1259 return $status;
1260 }
1261  
1262  
1263 #-----------------------------------------------------
1264 # This routine writes a hash array to a NDF extension
1265 # Keys that have leading underscores are skipped
1266 # $hashname contains the extension name to use by default.
1267 # This is extended by any '.' in the key.
1268  
1269 sub whash {
1270  
1271 my ($hash, $outndf, $hashname, $stypes, $status) = @_;
1272  
1273 my ($comp, $extension, $xtype, @dim, $ndims, $loc);
1274 my (@locs, $there, $type, $packed, $length);
1275 my (@bounds, $nbytes, $pntr, $maxsize, $which, $el);
1276 my ( $structs);
1277  
1278 my %header = (defined $hash ? %$hash : () );
1279 my $root = 1 if length($hashname) == 0; # Mark a ROOT structure
1280  
1281 # Return if bad status
1282 return $status if $status != &NDF::SAI__OK;
1283  
1284 foreach my $key (sort keys %header) {
1285  
1286 next if $key =~ /^_/;
1287  
1288 # If the key matches the Extensions (Axis or errors)
1289 # then skip. Should probably use the Extensions array
1290 # itself to work out which components to skip
1291  
1292 next if $key eq 'Axis';
1293 next if $key eq 'Errors';
1294 next if $key eq 'Extensions';
1295 next if $key eq 'Hist';
1296  
1297 # Deal with HASH arrays early
1298 ref($header{"$key"}) eq 'HASH' && do {
1299 my $nhashname = $hashname . ".$key";
1300 $nhashname =~ s/^\.//; # remove leading dot
1301 my $nstypes = $stypes . ".".$header{"$key"}{'_TYPES'}{STRUCT}{"$key"};
1302 $nstypes =~ s/^\.//; # remove leading dot
1303 $status = whash(\%{$header{"$key"}}, $outndf, $nhashname, $nstypes, $status);
1304 next;
1305 };
1306  
1307 my $path = $hashname . ".$key";
1308 $path =~ s/^\.//; # remove leading dot
1309  
1310 if ($key =~ /^TITLE$|^UNITS$|^LABEL$/i) {
1311 # This is not extension info
1312 ndf_cput($header{$key}, $outndf, $key, $status);
1313 } else {
1314  
1315 # Find nested structures
1316 my @structures = split(/\./, uc($path));
1317  
1318 # Last entry in structure is the important name
1319 $comp = pop(@structures);
1320  
1321 # Find list of structures
1322 $structs = join(".", @structures);
1323 $structs = 'PERLDL' unless (defined $structs && $structs =~ /./);
1324 $stypes = 'PERLDL_HDR' unless (defined $stypes && $stypes =~ /./);
1325  
1326 ($status, $loc) = mkstruct($outndf, $structs, $stypes, $status);
1327  
1328 # Now write the component
1329 # $loc is a locator to the last structure component
1330 $type = $header{"_TYPES"}{"$key"};
1331  
1332 # What is the data type?
1333 unless ($type =~ /./) {
1334 # number or character or array or pdl
1335 # All arrays are chars - should be PDLs if nums
1336 ref($header{"$key"}) eq 'ARRAY' && ($type = "_CHAR");
1337  
1338 ref($header{"$key"}) eq 'PDL' &&
1339 ($type = $pdltypes{$header{"$key"}{"Datatype"}});
1340  
1341 ref($header{"$key"}) || do {
1342 if ($header{"$key"} =~ /^(-?)(\d*)(\.?)(\d*)([Ee][-\+]?\d+)?$/) {
1343 $header{"$key"} =~ /\.|[eE]/
1344 && ($type = "_DOUBLE")
1345 || ($type = "_INTEGER");
1346 } else {
1347 ($type = '_CHAR') # Character
1348 }
1349 };
1350  
1351 }
1352  
1353 # Create and write component
1354 # PDLs
1355  
1356 if (ref($header{"$key"}) eq 'PDL') {
1357 my $pdl = $header{"$key"};
1358 @bounds = $pdl->dims;
1359 my $n = $#bounds + 1;
1360 dat_new($loc, $comp, $type, $n, \@bounds, $status);
1361 $nbytes = PDL::Core::howbig($pdl->get_datatype) *
1362 $pdl->nelem;
1363 cmp_mapv($loc, $comp, $type, 'WRITE', $pntr, $el, $status);
1364 string2mem(${$pdl->get_dataref}, $nbytes, $pntr)
1365 if ($status == &NDF::SAI__OK);
1366 cmp_unmap($loc, $comp, $status);
1367 }
1368  
1369 # SCALARS
1370 ref($header{"$key"}) || do {
1371  
1372 if ($type =~ /^_CHAR/) {
1373 $length = length($header{"$key"});
1374 dat_new0c($loc, $comp, $length, $status);
1375 cmp_put0c($loc, $comp, $header{"$key"}, $status)
1376 if $length > 0;
1377 } elsif ($type =~ /^_LOG/) {
1378 # In this case, add a check for FALSE or TRUE as strings
1379 dat_new0l($loc, $comp, $status);
1380 my $value = $header{$key};
1381 if (defined $value) {
1382 if ($value eq 'FALSE') {
1383 $value = 0;
1384 } elsif ($value eq 'TRUE') {
1385 $value = 1;
1386 }
1387 cmp_put0l($loc, $comp, $value, $status);
1388 }
1389 } else {
1390 # HDS does not have b,ub,w or uw types for new0 and put0
1391 # so we have to do create the item explicitly and put a bigger
1392 # type.
1393 my @dims = (0);
1394 dat_new( $loc, $comp, $type, 0, \@dims, $status );
1395 if ( $type =~ /_(BYTE|UBYTE|UWORD|WORD|INTEGER)$/) {
1396 cmp_put0i($loc, $comp, $header{$key}, $status);
1397 } elsif ($type =~ /_(REAL|DOUBLE)$/) {
1398 cmp_put0d($loc, $comp, $header{$key}, $status);
1399 } else {
1400 if ($status == &NDF::SAI__OK) {
1401 $status = &NDF::SAI__ERROR;
1402 err_rep("", "Unrecognized HDS type $type when writing component $comp",
1403 $status);
1404 }
1405 }
1406 }
1407 };
1408  
1409 # CHARACTER ARRAYS
1410 ref($header{"$key"}) eq 'ARRAY' && do {
1411 # First go through the array and remove any
1412 # entries that are references. I draw the line at storing
1413 # nested arrays
1414 my @norefs = grep { not ref($_) } @{$header{"$key"}};
1415  
1416 ($maxsize, $packed) = &NDF::pack1Dchar(\@norefs);
1417 $ndims = 1;
1418 @dim = ($#norefs+1);
1419 dat_newc($loc, $comp, $maxsize, $ndims, @dim, $status);
1420 cmp_putvc($loc, $comp, $dim[0], \@norefs, $status);
1421 };
1422  
1423 # Annul all the locators
1424 dat_annul($loc, $status);
1425  
1426 }
1427 }
1428  
1429 return $status;
1430 }
1431  
1432 # Subroutine to make extension structures of arbritrary depth
1433 # Just pass dot separated string to this function
1434 # A locator to the final structure is returned
1435  
1436 sub mkstruct {
1437  
1438 my ($outndf, $structs, $types, $status) = @_;
1439 my ($extension, @locs, @dim, $ndims, $xtype, $loc, $retloc);
1440 my ($set, $prmry, $there);
1441  
1442 my (@structures) = split('\.', $structs);
1443 my (@types) = split('\.', $types);
1444  
1445 return ($status, &NDF::DAT__NOLOC()) if $status != &NDF::SAI__OK();
1446  
1447 if ($#structures < 0) {
1448 $status = &NDF::SAI__ERROR;
1449 err_rep("", "Too few structures provided for mkstruct function (possible programming error)",
1450 $status);
1451 return ($status, &NDF::DAT__NOLOC());
1452 }
1453  
1454 # Does extension exist
1455  
1456 $extension = shift(@structures);
1457 $xtype = shift(@types);
1458  
1459 ndf_xstat($outndf, $extension, $there, $status);
1460  
1461 # Make it if necessary
1462 unless ($there) {
1463 print "Writing $extension extension ($xtype)...\n" if $PDL::verbose;
1464 @dim = (0); # No pdl extensions!
1465 $ndims = 0;
1466 ndf_xnew($outndf, $extension, $xtype, $ndims, @dim, $loc, $status);
1467 } else { # Get the locator to the extension
1468 ndf_xloc($outndf, $extension, 'UPDATE', $loc, $status);
1469 }
1470  
1471  
1472 @locs = (); # store the locators so that they can be annulled later
1473 push(@locs, $loc);
1474  
1475 # Make the structures, end up with a locator to the correct component
1476 for (0..$#structures) {
1477 dat_there($loc, $structures[$_], $there, $status);
1478 unless ($there) { # Make it if it isnt there
1479 my $type = $types[$_];
1480 @dim = (0);
1481 dat_new($loc, $structures[$_], $type, 0, @dim, $status);
1482 }
1483 dat_find($loc, $structures[$_], $loc, $status);
1484 push(@locs, $loc); # Store the new locator
1485 }
1486  
1487 # Clone the locator
1488 dat_clone($loc, $retloc, $status);
1489 $set = 1;
1490 $prmry = 1;
1491 dat_prmry($set, $retloc, $prmry, $status);
1492  
1493 # Annul all except the last locator
1494 foreach (@locs) {
1495 dat_annul($_, $status);
1496 }
1497  
1498 return ($status, ($status == &NDF::SAI__OK ? $retloc : &NDF::DAT__NOLOC() ));
1499 }
1500  
1501 # end of module
1502 1;
1503