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

filter: Statementstmt 0.0% 0 / 587 Branchbran 0.0% 0 / 274 Conditioncond 0.0% 0 / 57 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 953 CC 138 SCAR 59.8
CC
138
Cov
0%
wdata
992.0
whash
650.0
find_prim
380.0
CRAP 394.5
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.04';
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 ($nrec, $app, $date, $i);
787  
788 # Read HISTORY information into a Hist header
789  
790 ndf_hnrec($indf,$nrec,$status);
791  
792 if ($status == &NDF::SAI__OK && ($nrec > 0)) {
793 print "Reading history information into 'Hist'...\n" if $PDL::verbose;
794  
795 $$header{Hist}{'Nrecords'} = $nrec;
796  
797 # Loop through the history components and find last "APPLICATION"
798 for $i (1..$nrec) {
799  
800 ndf_hinfo($indf, 'APPLICATION', $i, $app, $status);
801 ndf_hinfo($indf, 'DATE', $i, $date, $status);
802  
803 $$header{Hist}{"Application$i"} = $app;
804 $$header{Hist}{"Date$i"} = $date;
805  
806 print " $app on $date\n" if $PDL::verbose;
807 }
808 }
809 return $status;
810 }
811  
812  
813  
814 ################ Generic routines ###########################
815 #################### INTERNAL ###############################
816  
817 # Find primitive components below a given HDS locator
818 # FITS information is stored in Hdr
819 # NDF extensions stored in NDF
820  
821 sub find_prim {
822  
823 my ($loc, $href, $class, $status) = @_;
824 my ($prim, $type, $size, @dim, $ndims, $struct, $name, $nloc, $el);
825 my ($value, @values, $item, $entry, $maxdims);
826 my ($packtype, $ncomp, $packed, $comp);
827 my ($pntr, $nbytes, $comment, $dref);
828  
829 # Return if bad status
830 return $status if $status != &NDF::SAI__OK;
831  
832 # Most dimensions
833 $maxdims = 100;
834  
835 # Is it a primitive component
836 dat_prim($loc, $prim, $status);
837  
838 # Type, size and shape
839 dat_type($loc, $type, $status);
840 dat_size($loc, $size, $status);
841 dat_shape($loc, $maxdims, \@dim, $ndims, $status);
842 dat_name($loc, $name, $status);
843  
844 if ($prim) {
845 print "\tReading component: $name ($type) " if $PDL::verbose;
846  
847 # Store type of information
848 $$href{"_TYPES"}{"$name"} = $type;
849  
850 # Read it into the header
851 if (($size == 1) && ($ndims == 0)) {
852 dat_state( $loc, my $isdefined, $status );
853 if (!$isdefined) {
854 $value = undef;
855 } elsif ($type eq '_DOUBLE') {
856 # dat_get0c doesn't return full precision for doubles
857 dat_get0d($loc, $value, $status);
858 err_rep("", "Error reading $type $name scalar as double",
859 $status ) if $status != &NDF::SAI__OK;
860 } else {
861 dat_get0c($loc, $value, $status);
862 err_rep("", "Error reading scalar $name with type $type as string",
863 $status ) if $status != &NDF::SAI__OK;
864 }
865  
866 $$href{"$name"} = $value if ($status == &NDF::SAI__OK);
867 undef $value;
868  
869 } else {
870 @dim = @dim[0..$ndims-1];
871  
872 # Inform the user of dimensions
873 print "[@dim]" if $PDL::verbose;
874  
875 # Map arrays (don't need to unpack them)
876 if ($type =~ /CHAR|LOG/) {
877  
878 # Read in the data
879 dat_getvc($loc, $size, \@values, $el, $status);
880  
881 if ($status != &NDF::SAI__OK) {
882 err_rep("", "Error reading $name of type $type as string.",
883 $status );
884 } else {
885 $$href{"$name"} = [@values];
886 undef @values;
887 }
888  
889 } else {
890  
891 # map the data
892 dat_mapv($loc, $type, 'READ', $pntr, $el, $status);
893  
894 if ($status != &NDF::SAI__OK) {
895 err_rep("", "Error mapping $name with type $type", $status);
896 }
897  
898  
899 if ($status == &NDF::SAI__OK) {
900 # Create the pdl
901 $$href{"$name"} = $class->new;
902 $$href{"$name"}->set_datatype($startypes{$type});
903 $$href{"$name"}->setdims([@dim]);
904 $dref = $$href{"$name"}->get_dataref();
905  
906 # How many bytes in this data type?
907 $type =~ s/^_|^_U//;
908 $nbytes = &NDF::byte_size($type);
909  
910 mem2string($pntr, $nbytes*$el, $$dref);
911 $$href{"$name"}->upd_data();
912 }
913  
914 dat_unmap($loc,$status);
915 }
916 }
917 print "\n" if $PDL::verbose;
918  
919 } else {
920  
921 my ($ndimx, @dim, $ndim);
922 dat_shape($loc, 20, \@dim, $ndim, $status);
923  
924 # If we have a single dimension ($ndim=0) then
925 # proceed. Cant yet cope with multi-dimensional
926 # extensions
927 if ($ndim == 0) {
928 dat_ncomp($loc, $ncomp, $status);
929 print "$name ($type) has $ncomp components\n" if $PDL::verbose;
930  
931 # Store type of extension
932 $$href{$name}{"_TYPES"}{STRUCT}{"$name"} = $type;
933  
934 for $comp (1..$ncomp) {
935 dat_index($loc, $comp, $nloc, $status);
936 $status = &find_prim($nloc, \%{$$href{$name}}, $class, $status);
937 dat_annul($nloc, $status);
938 }
939 } else {
940 print "Extension $name is an array structure -- skipping\n"
941 if $PDL::verbose;
942 }
943  
944 }
945 return $status;
946 }
947  
948  
949 ###### Routines for WRITING data ######################################
950  
951 sub wdata {
952  
953 my ($outndf, $pdl, $status) = @_;
954 my (@bounds, $ndims, @lower, @comps, $dcomp, $temppdl, $type);
955 my ($pntr, $el, $nbytes, $axis, $axcomp, $axpntr, %hdr, %axhdr);
956 my ($entry, $value, $i, $axndims, $axtype, $tcomp, @acomps);
957  
958  
959 # Return if bad status
960 return $status if $status != &NDF::SAI__OK;
961  
962 ####################################################################
963 # D I M S #
964 ####################################################################
965 # Change the bounds to match the PDL
966 @bounds = $pdl->dims;
967 $ndims = $#bounds;
968 @lower = map { 1 } (0..$ndims);
969  
970 &ndf_sbnd($ndims+1, \@lower, \@bounds, $outndf, $status);
971  
972  
973 ####################################################################
974 # D A T A + V A R I A N C E + Q U A L I T Y #
975 ####################################################################
976 # Map data, variance, quality...
977 @comps = ('Data','Errors','Quality');
978  
979 # Retrieve header and check that the header is a hash ref
980 my $hdr = $pdl->gethdr;
981 if (ref($hdr) eq 'HASH') {
982 %hdr = %$hdr;
983 } else {
984 %hdr = ();
985 }
986  
987 for $dcomp (@comps) {
988  
989 if ($dcomp eq 'Data') {
990 $temppdl = $pdl;
991 } else {
992 if (exists $hdr{"$dcomp"}) {
993 $temppdl = $hdr{"$dcomp"};
994 # Check that we have a PDL
995 next unless UNIVERSAL::isa($temppdl, 'PDL');
996 } else {
997 next; # Skip this component
998 }
999 }
1000  
1001 # Check that we have some data
1002 if ($temppdl->nelem > 0) {
1003  
1004 if (($dcomp eq 'Quality') && ($temppdl->get_datatype != $PDL_B)) {
1005 # Quality must be bytes so convert to BYTE if this is not true
1006 $temppdl = byte ($$pdl{"$dcomp"});
1007 }
1008  
1009 $type = $pdltypes{$temppdl->get_datatype};
1010 $type = '_UBYTE' if $dcomp eq 'Quality'; # No choice for QUALITY
1011  
1012 # Set the output type of the NDF
1013 $tcomp = $dcomp;
1014 $tcomp = 'Variance' if $tcomp eq 'Errors';
1015 ndf_stype($type, $outndf, $tcomp, $status) unless $dcomp eq 'Quality';
1016  
1017 print "Mapping $dcomp , $type\n" if $PDL::verbose;
1018 # Map NDF
1019 $dcomp = 'Error' if $dcomp eq 'Errors';
1020 ndf_map($outndf, $dcomp, $type, 'WRITE', $pntr, $el, $status);
1021  
1022 if ($status == &NDF::SAI__OK) {
1023 # Number of bytes per entry
1024 $nbytes = PDL::Core::howbig($temppdl->get_datatype);
1025  
1026 # Convert to 1D data stream
1027 my $p1d = $temppdl->clump(-1);
1028 # Total number of bytes
1029 $nbytes *= $p1d->getdim(0);
1030  
1031 # Copy to disk
1032 string2mem(${$temppdl->get_dataref}, $nbytes, $pntr);
1033  
1034 # Write badbit mask
1035 if ($dcomp eq 'Quality') {
1036 ndf_sbb($$temppdl{Hdr}{BADBIT}, $outndf, $status)
1037 if defined $$temppdl{Hdr}{BADBIT};
1038 }
1039 }
1040 # Unmap Data
1041 ndf_unmap($outndf, $tcomp, $status);
1042  
1043 }
1044  
1045 # free the temporary pdl
1046 undef $temppdl;
1047  
1048 }
1049  
1050  
1051 ####################################################################
1052 # A X I S #
1053 ####################################################################
1054 # A X I S information is expected as an array in the header
1055 # called 'Axis'. These PDLs contain the CENTRE data and any further
1056 # info is stored in their header.
1057 # @bounds is accessed to find expected shape
1058  
1059  
1060 # Simply look in the header for a Axis
1061 if (exists $hdr{Axis}) {
1062 # Check that we have an array
1063 if (ref($hdr{Axis}) eq 'ARRAY') {
1064 # Now loop over axes
1065 for my $i (0..$#{$hdr{Axis}} ) {
1066 # Loop unless status is bad
1067 last unless $status == &NDF::SAI__OK;
1068  
1069 # Extract the ith axis PDL from the array
1070 my $axis = $hdr{Axis}->[$i];
1071  
1072 # If we have a PDL
1073 if (UNIVERSAL::isa($axis, 'PDL')) {
1074 # We now want to copy the data and if necessary the
1075 # Error array. Since there are only two I will do it the
1076 # long way by explcitly storing data and then error
1077  
1078 # Set data type
1079 $axtype = $pdltypes{$axis->get_datatype};
1080 ndf_astyp($axtype, $outndf, 'Centre', $i+1, $status);
1081  
1082 # Okay we can now map this pdl
1083 ndf_amap($outndf, 'Centre', $i+1, $axtype, 'WRITE', $axpntr,
1084 $el, $status);
1085  
1086 # Check that we have the correct number of entries
1087 my $nelem = $axis->nelem;
1088 if ($el == $nelem) {
1089 print "Mapping axis " , $i+1 , "\n" if $PDL::verbose;
1090  
1091 # Number of bytes per entry
1092 $nbytes = PDL::Core::howbig($axis->get_datatype) * $el;
1093  
1094 # Copy to disk
1095 string2mem( $ { $axis->get_dataref }, $nbytes, $axpntr)
1096 if ($status == &NDF::SAI__OK);
1097  
1098 } else {
1099 carp "Axis ",$i+1 .
1100 " is the wrong size ($el values required but got ".
1101 $nelem . ")- ignoring";
1102 }
1103 # Unmap
1104 ndf_aunmp($outndf, '*', $i+1, $status);
1105  
1106 # Errors
1107 my $axhdr = $axis->gethdr; # Retrieve and check header
1108 if (ref($axhdr) eq 'HASH') {
1109 %axhdr = %$axhdr;
1110 } else {
1111 %axhdr = ();
1112 }
1113  
1114 # Look for an Errors component in the header hash
1115 if (exists $axhdr{Errors}) {
1116 my $axerr = $axhdr{Errors};
1117 if (UNIVERSAL::isa($axerr, 'PDL')) {
1118  
1119 # Set data type
1120 $axtype = $pdltypes{$axerr->get_datatype};
1121 ndf_astyp($axtype, $outndf, 'Variance', $i+1, $status);
1122  
1123 # Okay we can now map this pdl
1124 ndf_amap($outndf, 'Errors', $i+1, $axtype, 'WRITE',
1125 $axpntr, $el, $status);
1126  
1127 # Check that we have the correct number of entries
1128 my $nelem = $axerr->nelem;
1129 if ($nelem == $el) {
1130 print "Mapping errors for axis " . $i+1 . "\n"
1131 if $PDL::verbose;
1132  
1133 # Number of bytes per entry
1134 $nbytes = PDL::Core::howbig($axerr->get_datatype) * $el;
1135  
1136 # Copy to disk
1137 string2mem($ {$axerr->get_dataref}, $nbytes, $axpntr)
1138 if ($status == &NDF::SAI__OK);
1139  
1140 } else {
1141 carp "Error PDL for Axis ",$i+1,
1142 " is the wrong size ($el values required but got ".
1143 $axerr->nelem . ")- ignoring";
1144 }
1145 # Unmap
1146 ndf_aunmp($outndf, '*', $i+1, $status);
1147  
1148 }
1149  
1150 }
1151  
1152 # Now character components
1153 foreach my $char (keys %axhdr) {
1154 if ($char =~ /LABEL|UNITS/i) {
1155 $value = $axhdr{"$char"};
1156 ndf_acput($value, $outndf, $char, $i+1, $status)
1157 if length($value) > 0;
1158 }
1159  
1160 }
1161  
1162 }
1163  
1164 }
1165  
1166 }
1167  
1168 }
1169  
1170 return $status;
1171 }
1172  
1173  
1174 # Write header information to NDF extension
1175 # This routine does not reconstruct an NDF identically to one that
1176 # was read in. FITS extensions are made. All non-integer numeric types
1177 # are written as doubles (apart from PDLs which carry there own type
1178 # information) unless _TYPES information exists in {NDF}.
1179  
1180  
1181 sub whdr {
1182  
1183 my ($outndf, $pdl, $status) = @_;
1184  
1185 my (%header, @fitsdim, $fitsloc, $value);
1186 my (%unused, @fits, $hashref, $hdr);
1187  
1188 # Return if bad status
1189 return $status if $status != &NDF::SAI__OK;
1190  
1191 print "Writing header information...\n" if $PDL::verbose;
1192  
1193 # Write FITS header from {Hdr}
1194  
1195 # Retrieve and check header from PDL
1196 $hdr = $pdl->gethdr;
1197 if (ref($hdr) eq 'HASH') {
1198 %header = %$hdr;
1199 } else {
1200 %header = ();
1201 }
1202  
1203 %unused = ();
1204 @fits = ();
1205  
1206 foreach my $key (sort keys %header) {
1207  
1208 next if $key eq '_COMMENTS';
1209  
1210 if ($key =~ /^TITLE$|^UNITS$|^LABEL$/i) {
1211 # This is not extension info
1212 ndf_cput($header{$key}, $outndf, $key, $status)
1213 if length($header{$key}) > 0;
1214 next;
1215 }
1216  
1217 # Only write scalars
1218 if (not ref($header{"$key"})) {
1219  
1220 my $item = Astro::FITS::Header::Item->new( Keyword => $key,
1221 Value => $header{$key},
1222 Comment => $header{'_COMMENTS'}{$key});
1223 if (defined $item) {
1224 push(@fits, $item->card() );
1225 } else {
1226 $unused{$key} = $header{$key};
1227 }
1228 } else {
1229 # Deal with later
1230 $unused{$key} = $header{$key};
1231 }
1232  
1233 }
1234  
1235 # Write the FITS extension
1236 if ($#fits > -1) {
1237 push(@fits, "END");
1238 # Write it out
1239 @fitsdim = ($#fits+1);
1240 ndf_xnew($outndf, 'FITS', '_CHAR*80', 1, @fitsdim, $fitsloc, $status);
1241 dat_put1c($fitsloc, $#fits+1, \@fits, $status);
1242 dat_annul($fitsloc, $status);
1243 }
1244  
1245 # Loop through all NDF header info and array Hdr information
1246 # Note that %unused still contains our NDF hash so
1247 # we must remove that before proceeding (else we end up with
1248 # an 'NDF_EXT' extension!
1249  
1250 delete $unused{$EXTNAME};
1251  
1252 foreach $hashref (\%unused, $header{$EXTNAME}) {
1253 $status = whash($hashref, $outndf, '', '', $status);
1254 }
1255 return $status;
1256 }
1257  
1258  
1259 #-----------------------------------------------------
1260 # This routine writes a hash array to a NDF extension
1261 # Keys that have leading underscores are skipped
1262 # $hashname contains the extension name to use by default.
1263 # This is extended by any '.' in the key.
1264  
1265 sub whash {
1266  
1267 my ($hash, $outndf, $hashname, $stypes, $status) = @_;
1268  
1269 my ($comp, $extension, $xtype, @dim, $ndims, $loc);
1270 my (@locs, $there, $type, $packed, $length);
1271 my (@bounds, $nbytes, $pntr, $maxsize, $which, $el);
1272 my ( $structs);
1273  
1274 my %header = (defined $hash ? %$hash : () );
1275 my $root = 1 if length($hashname) == 0; # Mark a ROOT structure
1276  
1277 # Return if bad status
1278 return $status if $status != &NDF::SAI__OK;
1279  
1280 foreach my $key (sort keys %header) {
1281  
1282 next if $key =~ /^_/;
1283  
1284 # If the key matches the Extensions (Axis or errors)
1285 # then skip. Should probably use the Extensions array
1286 # itself to work out which components to skip
1287  
1288 next if $key eq 'Axis';
1289 next if $key eq 'Errors';
1290 next if $key eq 'Extensions';
1291 next if $key eq 'Hist';
1292  
1293 # Deal with HASH arrays early
1294 ref($header{"$key"}) eq 'HASH' && do {
1295 my $nhashname = $hashname . ".$key";
1296 $nhashname =~ s/^\.//; # remove leading dot
1297 my $nstypes = $stypes . ".".$header{"$key"}{'_TYPES'}{STRUCT}{"$key"};
1298 $nstypes =~ s/^\.//; # remove leading dot
1299 $status = whash(\%{$header{"$key"}}, $outndf, $nhashname, $nstypes, $status);
1300 next;
1301 };
1302  
1303 my $path = $hashname . ".$key";
1304 $path =~ s/^\.//; # remove leading dot
1305  
1306 if ($key =~ /^TITLE$|^UNITS$|^LABEL$/i) {
1307 # This is not extension info
1308 ndf_cput($header{$key}, $outndf, $key, $status);
1309 } else {
1310  
1311 # Find nested structures
1312 my @structures = split(/\./, uc($path));
1313  
1314 # Last entry in structure is the important name
1315 $comp = pop(@structures);
1316  
1317 # Find list of structures
1318 $structs = join(".", @structures);
1319 $structs = 'PERLDL' unless (defined $structs && $structs =~ /./);
1320 $stypes = 'PERLDL_HDR' unless (defined $stypes && $stypes =~ /./);
1321  
1322 ($status, $loc) = mkstruct($outndf, $structs, $stypes, $status);
1323  
1324 # Now write the component
1325 # $loc is a locator to the last structure component
1326 $type = $header{"_TYPES"}{"$key"};
1327  
1328 # What is the data type?
1329 unless ($type =~ /./) {
1330 # number or character or array or pdl
1331 # All arrays are chars - should be PDLs if nums
1332 ref($header{"$key"}) eq 'ARRAY' && ($type = "_CHAR");
1333  
1334 ref($header{"$key"}) eq 'PDL' &&
1335 ($type = $pdltypes{$header{"$key"}{"Datatype"}});
1336  
1337 ref($header{"$key"}) || do {
1338 if ($header{"$key"} =~ /^(-?)(\d*)(\.?)(\d*)([Ee][-\+]?\d+)?$/) {
1339 $header{"$key"} =~ /\.|[eE]/
1340 && ($type = "_DOUBLE")
1341 || ($type = "_INTEGER");
1342 } else {
1343 ($type = '_CHAR') # Character
1344 }
1345 };
1346  
1347 }
1348  
1349 # Create and write component
1350 # PDLs
1351  
1352 if (ref($header{"$key"}) eq 'PDL') {
1353 my $pdl = $header{"$key"};
1354 @bounds = $pdl->dims;
1355 my $n = $#bounds + 1;
1356 dat_new($loc, $comp, $type, $n, \@bounds, $status);
1357 $nbytes = PDL::Core::howbig($pdl->get_datatype) *
1358 $pdl->nelem;
1359 cmp_mapv($loc, $comp, $type, 'WRITE', $pntr, $el, $status);
1360 string2mem(${$pdl->get_dataref}, $nbytes, $pntr)
1361 if ($status == &NDF::SAI__OK);
1362 cmp_unmap($loc, $comp, $status);
1363 }
1364  
1365 # SCALARS
1366 ref($header{"$key"}) || do {
1367  
1368 if ($type =~ /^_CHAR/) {
1369 $length = length($header{"$key"});
1370 dat_new0c($loc, $comp, $length, $status);
1371 cmp_put0c($loc, $comp, $header{"$key"}, $status)
1372 if $length > 0;
1373 } elsif ($type =~ /^_LOG/) {
1374 # In this case, add a check for FALSE or TRUE as strings
1375 dat_new0l($loc, $comp, $status);
1376 my $value = $header{$key};
1377 if (defined $value) {
1378 if ($value eq 'FALSE') {
1379 $value = 0;
1380 } elsif ($value eq 'TRUE') {
1381 $value = 1;
1382 }
1383 cmp_put0l($loc, $comp, $value, $status);
1384 }
1385 } else {
1386 # HDS does not have b,ub,w or uw types for new0 and put0
1387 # so we have to do create the item explicitly and put a bigger
1388 # type.
1389 my @dims = (0);
1390 dat_new( $loc, $comp, $type, 0, \@dims, $status );
1391 if ( $type =~ /_(BYTE|UBYTE|UWORD|WORD|INTEGER)$/) {
1392 cmp_put0i($loc, $comp, $header{$key}, $status);
1393 } elsif ($type =~ /_(REAL|DOUBLE)$/) {
1394 cmp_put0d($loc, $comp, $header{$key}, $status);
1395 } else {
1396 if ($status == &NDF::SAI__OK) {
1397 $status = &NDF::SAI__ERROR;
1398 err_rep("", "Unrecognized HDS type $type when writing component $comp",
1399 $status);
1400 }
1401 }
1402 }
1403 };
1404  
1405 # CHARACTER ARRAYS
1406 ref($header{"$key"}) eq 'ARRAY' && do {
1407 # First go through the array and remove any
1408 # entries that are references. I draw the line at storing
1409 # nested arrays
1410 my @norefs = grep { not ref($_) } @{$header{"$key"}};
1411  
1412 ($maxsize, $packed) = &NDF::pack1Dchar(\@norefs);
1413 $ndims = 1;
1414 @dim = ($#norefs+1);
1415 dat_newc($loc, $comp, $maxsize, $ndims, @dim, $status);
1416 cmp_putvc($loc, $comp, $dim[0], \@norefs, $status);
1417 };
1418  
1419 # Annul all the locators
1420 dat_annul($loc, $status);
1421  
1422 }
1423 }
1424  
1425 return $status;
1426 }
1427  
1428 # Subroutine to make extension structures of arbritrary depth
1429 # Just pass dot separated string to this function
1430 # A locator to the final structure is returned
1431  
1432 sub mkstruct {
1433  
1434 my ($outndf, $structs, $types, $status) = @_;
1435 my ($extension, @locs, @dim, $ndims, $xtype, $loc, $retloc);
1436 my ($set, $prmry, $there);
1437  
1438 my (@structures) = split('\.', $structs);
1439 my (@types) = split('\.', $types);
1440  
1441 return ($status, &NDF::DAT__NOLOC()) if $status != &NDF::SAI__OK();
1442  
1443 if ($#structures < 0) {
1444 $status = &NDF::SAI__ERROR;
1445 err_rep("", "Too few structures provided for mkstruct function (possible programming error)",
1446 $status);
1447 return ($status, &NDF::DAT__NOLOC());
1448 }
1449  
1450 # Does extension exist
1451  
1452 $extension = shift(@structures);
1453 $xtype = shift(@types);
1454  
1455 ndf_xstat($outndf, $extension, $there, $status);
1456  
1457 # Make it if necessary
1458 unless ($there) {
1459 print "Writing $extension extension ($xtype)...\n" if $PDL::verbose;
1460 @dim = (0); # No pdl extensions!
1461 $ndims = 0;
1462 ndf_xnew($outndf, $extension, $xtype, $ndims, @dim, $loc, $status);
1463 } else { # Get the locator to the extension
1464 ndf_xloc($outndf, $extension, 'UPDATE', $loc, $status);
1465 }
1466  
1467  
1468 @locs = (); # store the locators so that they can be annulled later
1469 push(@locs, $loc);
1470  
1471 # Make the structures, end up with a locator to the correct component
1472 for (0..$#structures) {
1473 dat_there($loc, $structures[$_], $there, $status);
1474 unless ($there) { # Make it if it isnt there
1475 my $type = $types[$_];
1476 @dim = (0);
1477 dat_new($loc, $structures[$_], $type, 0, @dim, $status);
1478 }
1479 dat_find($loc, $structures[$_], $loc, $status);
1480 push(@locs, $loc); # Store the new locator
1481 }
1482  
1483 # Clone the locator
1484 dat_clone($loc, $retloc, $status);
1485 $set = 1;
1486 $prmry = 1;
1487 dat_prmry($set, $retloc, $prmry, $status);
1488  
1489 # Annul all except the last locator
1490 foreach (@locs) {
1491 dat_annul($_, $status);
1492 }
1493  
1494 return ($status, ($status == &NDF::SAI__OK ? $retloc : &NDF::DAT__NOLOC() ));
1495 }
1496  
1497 # end of module
1498 1;
1499