
% ( out, flag ) = _var2array( in )
%
% if in is an array, out = in and flag = 0
% if in is a  scalar, out = [ in ] (ie a 1D array
% with 1 element) and flag = 1
%
% the intention is to make writing routines that handle scalars
% and arrays a little easier: just handle arrays and then
% convert back to the scalar at the end if input was a scalar
%
define _var2array (in) {
  if ( typeof(in) == Array_Type )
    return ( in, 0 );
  else
    return ( [ in ], 1 );
} % % _var2array()

% ra/dec conversion
define ra2hms (radeg) {
  variable in, aflag;
  ( in, aflag ) = _var2array(radeg);

  in /= 15.0;
  variable h = int( in );
  in -= h;
  in *= 60.0;
  variable m = int( in );
  in -= m;
  in *= 60.0;
  variable s = in;

  % loop through each element and create a string
  variable nin = length(in);
  variable out = String_Type [nin];
  variable i;
  foreach ( [0:nin-1] ) {
    % perhaps should use array_map() instead of this loop
    i = ();
    out[i] = sprintf("%02d:%02d:%05.2f",h[i],m[i],s[i]);
  }
  if ( aflag == 1 )
    return out[0];
  else
    return out;
} % ra2hms()

define dec2dms (decdeg) {
  variable in, aflag;
  ( in, aflag ) = _var2array(decdeg);

  variable sgn = in >= 0;
  in = abs(decdeg);
  variable d = int( in );
  in -= d;
  in *= 60.0;
  variable m = int( in );
  in -= m;
  in *= 60.0;
  variable s = in;


  % loop through each element and create a string
  variable nin = length(in);
  variable out = String_Type [nin];
  variable i;
  foreach ( [0:nin-1] ) {
    % perhaps should use array_map() instead of this loop
    i = ();
    if ( sgn[i] ) {
      out[i] = sprintf("+%02d:%02d:%05.2f",d[i],m[i],s[i]);
    } else {
      out[i] = sprintf("-%02d:%02d:%05.2f",d[i],m[i],s[i]);
    }
  }
  if ( aflag == 1 )
    return out[0];
  else
    return out;

} % dec2dms()

%
% convert ra/dec in degrees to sexagesimal format
% - input can be scalars or 1D arrays and the output 'format'
%   matches the input
%
% Example:
%   chips> foo = readfile("wavelet.srclist")
%   chips> (ra,dec) = deg2sexag(foo.RA,foo.DEC)
%   chips> writeascii("wavelet.ascii",foo.COMPONENT,ra,dec)
%   chips> writeascii(stdout,foo.COMPONENT,ra,dec,foo.X,foo.Y)
%   1       17:17:10.49     +67:09:30.40    3983.42 3826.55
%   2       17:16:51.72     +67:08:55.10    4205.64 3754.81
%   3       17:16:38.08     +67:11:55.85    4366.59 4122.35
%
% really should ensure that size or input arrays match
%
define deg2sexag(radeg,decdeg) {
  return ( ra2hms( radeg ), dec2dms( decdeg ) );
}

