#!/usr/bin/perl

$ngcfile = ".NGC2000_0.txt";
$mfile = "m.txt";
$mdatafile = "messier1.dat";
$creffile = "dsos-cr.txt" ;
$pixfile = "pix.txt";
$capfile = "cap.txt";
$mpixdir = "http://messier.seds.org/JpgSm/";
$mcapdir = "http://messier.seds.org/m/";

$NGCmax = 7840;
$ICmax = 5386;
$Mmax = 110;

$mnum = 0; # Initialization

%types = (
  "Gx",  "Galaxy",
  "OC",  "Open star cluster",
  "Gb",  "Globular star cluster", 
  "Nb",  "Bright (emission and/or reflection) nebula",
  "Pl",  "Planetary nebula",
  "C+N", "Cluster associated with nebulosity",
  "Ast", "Asterism or group of a few stars",
  "Kt",  "Knot or nebulous region in an external galaxy",
  "***", "Triple star",
  "D*",  "Double star",
  "D*?", "Double star (?)",
  "*",   "Single star",
  "*?",  "Single star (?)",
  "?",   "Object of uncertain type or may not exist,",
  "",    "Unidentified at the place given, or type unknown,",
  "-",   "Object called nonexistent in the RNGC (Sulentic and Tifft 1973),",
  "PD",  "Photographic plate defect",
);

%constell = (
  "And", "Andromeda",
  "Ant", "Antlia",
  "Aps", "Apus",
  "Aqr", "Aquarius",
  "Aql", "Aquila",
  "Ara", "Ara",
  "Ari", "Aries",
  "Aur", "Auriga",
  "Boo", "Bootes",
  "Cae", "Caelum",
  "Cam", "Camelopardalis",
  "Cnc", "Cancer",
  "CVn", "Canes Venatici",
  "CMa", "Canis Major",
  "CMi", "Canis Minor",
  "Cap", "Capricornus",
  "Car", "Carina",
  "Cas", "Cassiopeia",
  "Cen", "Centaurus",
  "Cep", "Cepheus",
  "Cet", "Cetus",
  "Cha", "Chamaeleon",
  "Cir", "Circinus",
  "Col", "Columba",
  "Com", "Coma Berenices",
  "CrA", "Corona Australis",
  "CrB", "Corona Borealis",
  "Crv", "Corvus",
  "Crt", "Crater",
  "Cru", "Crux",
  "Cyg", "Cygnus",
  "Del", "Delphinus",
  "Dor", "Dorado",
  "Dra", "Draco",
  "Equ", "Equuleus",
  "Eri", "Eridanus",
  "For", "Fornax",
  "Gem", "Gemini",
  "Gru", "Grus",
  "Her", "Hercules",
  "Hor", "Horologium",
  "Hya", "Hydra",
  "Hyi", "Hydrus",
  "Ind", "Indus",
  "Lac", "Lacerta",
  "Leo", "Leo",
  "LMi", "Leo Minor",
  "Lep", "Lepus",
  "Lib", "Libra",
  "Lup", "Lupus",
  "Lyn", "Lynx",
  "Lyr", "Lyra",
  "Men", "Mensa",
  "Mic", "Microscopium",
  "Mon", "Monoceros",
  "Mus", "Musca",
  "Nor", "Norma",
  "Oct", "Octans",
  "Oph", "Ophiuchus",
  "Ori", "Orion",
  "Pav", "Pavo",
  "Peg", "Pegasus",
  "Per", "Perseus",
  "Phe", "Phoenix",
  "Pic", "Pictor",
  "Psc", "Pisces",
  "PsA", "Piscis Austrinus",
  "Pup", "Puppis",
  "Pyx", "Pyxis",
  "Ret", "Reticulum",
  "Sge", "Sagitta",
  "Sgr", "Sagittarius",
  "Sco", "Scorpius",
  "Scl", "Sculptor",
  "Sct", "Scutum",
  "Ser", "Serpens",
  "Sex", "Sextans",
  "Tau", "Taurus",
  "Tel", "Telescopium",
  "Tri", "Triangulum",
  "Tra", "Triangulum Australe",
  "Tuc", "Tucana",
  "UMa", "Ursa Major",
  "UMi", "Ursa Minor",
  "Vel", "Vela",
  "Vir", "Virgo",
  "Vol", "Volans",
  "Vul", "Vulpecula",
);

###########################################

$catnum = $ENV{ 'QUERY_STRING' } ;

if ( $catnum eq "HOMEPAGE" ) {
  open HOMEPAGE , "ngc.html" ;
  @lines = <HOMEPAGE> ;
  close HOMEPAGE ;
  print "Content-type: text/html\n\n";
  print @lines ;
  exit 0 ;
}

$catnum =~ s/\x2b/ /g ; # "+" of  parameters -> spaces
$catnum =~ s/^[ ]*// ;  # remove leading spaces

if ($catnum =~ /^i/i) { # IC catalog number
  $cat = "IC";
  $catnum =~ s/\D//g; $catnum = $catnum + 0;
  if ($catnum > $ICmax) {
    $errstr ="IC number ($catnum) out of range (1-$ICmax).";
    $cat = "";
    $title = "NGC Error !";
    $catnum = 0;
  } else {
    $title = "IC " . $catnum;
    if ($catnum == 4725) { # M25, the only Messier with an IC number
      $mnum = 25;
      $title .= " = M25";
    } elsif ($catnum == 4715) { # possibly M24, perhaps a second ..
      $mnum = 24;
      $title .= " = M24?";
    } elsif ($catnum == 4703) { # nebula with M16
      $mnum = 16;
      $title .= " associated with M16";
    }
    $cnum = "I " . (" " x (4-length($catnum))) . $catnum;
    $catnum = "I" . (" " x (4-length($catnum))) . $catnum;
  }
} elsif ($catnum =~ /^[n\d]/i) { # NGC number 
  $cat = "NGC";
  $catnum =~ s/\D//g; $catnum = $catnum + 0;
  if ($catnum > $NGCmax) {
    $errstr ="NGC number ($catnum) out of range (1-$NGCmax).";
    $cat = "";
    $title = "NGC Error !";
    $catnum = 0;
  } else {
    $cnum = "N " . (" " x (4-length($catnum))) . $catnum;
    $catnum = "N" . (" " x (4-length($catnum))) . $catnum;
    $mline = `grep "$catnum" $mfile`; # find possible Messier number
    if ($mline =~ /^M[ ]*(\d*) =/) {
      $mnum = $1;
    };
    $catnum =~ s/N/ /;
    $title = "NGC" . $catnum;
    if ($mnum) {
      $title .= " = M" . $mnum;
      if ($mnum ==  24) {$title =~ s/=/in/};
      if ($mnum ==   8) {
        if (($catnum == 6526) or ($catnum == 6530) or ($catnum == 6533)) {
          $title =~ s/=/in/
        }
      }
    };
  };
} elsif ($catnum =~ /^m/i) { # Messier number
  $cat = "M";
  $catnum =~ s/\D//g; $catnum = $catnum + 0;
  if ($catnum > $Mmax) {
    $errstr ="Messier number ($catnum) out of range (1-$Mmax).";
    $cat = "";
    $title = "NGC Error !";
    $catnum = 0;
  } else {
    $mnum = $catnum;
    $catnum = "M" . (" " x (3 - length($catnum))) . $catnum;
    $cnum = $catnum;
    $mline = `grep "$catnum" $mfile`;
    if ($mline =~ /.*([NI][ ]*\d*)/) {
      $catnum = $1;
      $catnum =~ s/N/ /;
      if ($mnum == 24) {
        $title = "M24 (= IC 4715?) with NGC 6603";
      } else {
        $catnum =~ s/ /NGC /  || $catnum =~ s/I/IC /;
        $title = $catnum . " = M" . $mnum;
        $catnum =~ s/NGC / /  || $catnum =~ s/IC /I/;
      };
    } else { # M45, M40
      $title = "M" . $mnum;
      $catnum = 0; # No NGC or IC number
    };
  };
} else { # erroneous input
  $cat = "";
  $title = "NGC Error !";
  $catnum = 0;
  $errstr ="Only NGC, IC, and Messier catalog inquiries accepted.";
}

if ($catnum) {
  # Get the NGC 2000 data..
  $ngc2000line = `grep "^$catnum" $ngcfile`;
  $ngc2000line =~
    /.{6}(.{3}).(.{2}).(.{4}).{2}(.{3}).(.{2}).(.).{2}(.{3})(.{6}).{2}(.{5}).(.*)/;
  $type=$1; $RA=$2 . " : " . $3; $Dec=$4 . " : " . $5;  $Mod=$6;
  $con=$7; $Dim=$8; $Mag=$9; $Desc=$10;
  # Is there an image ?
  $pixline = `grep "^$catnum:" $pixfile`;
  chomp($pixline);
  if (  $pixline =~ s/^[^:]*: //) {
    if (($pixline =~ /(.) ([-\w]{1,3}) (.*) "(.*)"/) ||
       ($pixline =~ /(.) ([-\w]{1,3}) (.*)/)) {
    $display=$1;
    $own=$2;
    $pix=$3;
    $pixcap=$4;
    }
  }
  # Is there a caption ?
  $capline = `grep "^$catnum:" $capfile`;
  if ($capline =~ /.*: (.*)/) {$caption = $1;};
}

if (!$Desc) {$Desc="None"} # No description
if ($mnum) {
  # Get Messier data
  ###if ($mnum==102) {$lin = "102?"} else {
  ###  $lin = ('0' x (3-length($mnum))) . $mnum;
  ###}
  $lin = ('0' x (3-length($mnum))) . $mnum;
  $mdataline = `grep "^$lin" $mdatafile`;
  chomp ($mdataline);
  $mdataline =~
    /.{27}(.{6}).{10}(..).(.{4}).(...).(..).(.{4}).(.{9}).(.{5,10})(.*)/;
  $Dist=$8; $MDesc=$9;
  if (!$catnum) {$con=$1; $RA=$2 . " : " . $3; $Dec=$4 . " : " . $5};
  if (!$Mag) {$Mag=$6};
  if (!$Dim) {$Dim=$7};
  if ($mnum==40) {$type="D*"}; #M40
  if ($mnum==45) {$type="C+N"}; #M45
  $Desc =~ s/;.*//;    # correct incomplete NGC 2000 data for M number
  if ($mnum==24) {
    $Desc = $Desc . "; in M24";
  ### } elsif ($mnum==102) {
  ###   $Desc = $Desc . "; = M102 (?)";
  } elsif ($mnum==8) {
    if (($catnum==6526) or ($catnum==6530) or ($catnum==6533)) {
      $Desc = $Desc . "; in M8";
    } else {
      $Desc = $Desc . "; = M$mnum";
    }
  } elsif ($mnum!=51) {
    $Desc = $Desc . "; = M$mnum";
  }
}

if ($cat ne "" ) {
  # Get cross references
  if ( $cat eq "M" ) { $cnum = "^" . "." x 25 . $cnum } else
    { $cnum = "^" . "." x 31 . $cnum } ;

  open CREFFILE , "grep '$cnum' $creffile |" ;
  @creflines = <CREFFILE> ;
  close CREFFILE ;
  if ( $#creflines == 0 ) {
    $crefline = $creflines[0]
  } else {
    ( $crefline ) = grep "$cnum " , @creflines 
  }

  # $crefline = `grep "$cnum" $creffile` ;
  ($CRm, $CRngcic, $CRgc, $CRh33, $CRh47, $CRwh, $CRlac, $CRdun, $CRrest, ) =
    $crefline =~
      /^.{25}(.{4})..(.{8})(.{9})(.{8})(.{8})(.{9})(.{9})..(.{9})(.*)$/;
  $CRm     =~ s/^ *//; $CRm     =~ s/ *$//;
  $CRngcic =~ s/^ *//; $CRngcic =~ s/ *$//;
  $CRgc    =~ s/^ *//; $CRgc    =~ s/ *$//;
  $CRh33   =~ s/^ *//; $CRh33   =~ s/ *$//;
  $CRh47   =~ s/^ *//; $CRh47   =~ s/ *$//;
  $CRwh    =~ s/^ *//; $CRwh    =~ s/ *$//;
  $CRlac   =~ s/^ *//; $CRlac   =~ s/ *$//;
  $CRdun   =~ s/^ *//; $CRdun   =~ s/ *$//;
  $CRrest  =~ s/^ *//; $CRrest  =~ s/ *$//;
  if ( $CRrest ne "" ) { $CRrest .=  "." }

  if (($CRm ne "") and ($CRm ne "M" . " " x (3-length($mnum)) . $mnum)) {
    $title = "* WARNING *" ;
    $errstr = "Messier number in Cross Ref File ($creffile): $CRm\n" .
      "doesn't match Messier number: $mnum" ;
    $cat = "";
  }

  if (($CRngcic ne "") and ! ($CRngcic =~ s/[NI] //) and ($CRngcic != $catnum )) {
    $title = "* WARNING *" ;
    $errstr = "NGC/IC number in Cross Ref File ($creffile): $CRngcic\n" .
      "doesn't match NGC/IC number: $catnum" ;
    $cat = "";
  }

  $CRefs = join ", ", $CRgc, $CRh33, $CRh47, $CRwh, $CRlac, $CRdun;
  $CRefs =~ s/(, )+/, /g; $CRefs =~ s/^, //; $CRefs =~ s/, $//;
  if ( $CRefs ne "" ) {
    $CRefs .= ".\n" . $CRrest ; 
  } else {
    $CRefs = $CRrest ;
  }
}

$con =~ s/ //g;
$type =~ s/ //g;
$con=$constell{$con};
$type=$types{$type};

if ( $cat ne "" ) {
  $field=15;
  if ($Dim > 12.0) {
    if ($Dim < 50.0) {$field = 1.2*$Dim; } else { $field = 60; };
  }
  $tit = $title; $tit =~ s/ /!/g;
  $dssquery = "obj=$tit&r=$RA&d=$Dec&e=J2000&h=$field&w=$field&f=GIF&c=none";
  $dssquery =~ s/ //g;
}

print "Content-type: text/html\n\n";
printf "<html><head>\n<title>%15s</title>\n\n", $title;
print '<link rev="owner" title="Contact Maintainer" href="http://spider.seds.org/Contact/spider.html">',
  "\n" , '<meta name="author" content="Hartmut Frommert">' , "\n" ,
  '<meta name="distribution" value="global">' , "\n</head>\n\n<body>\n\n";
if ($mnum) {
  ### if ($mnum==102) { $mpic = "ngc5866" ; } else { $mpic = "m$mnum" ; } ;
  $mpic = "m$mnum" ;
  print '<a href="' , $mpixdir , $mpic, '.jpg">',  "\n",
        '<img src="', $mpixdir , $mpic, '.jpg" alt="[M', $mnum, 
        ' image]" align=right>' , "</a>\n";
} elsif ($pix) {
  if ($display eq "r") {$display='align=right';$br=''}
  else {$display='';$br='<br>'};
  print '<a href="', $pix, '">', "\n<img ", $display, ' src="', $pix, 
        '" alt="[', $title, ' image]"></a>', $br, "\n";
  if ($pixcap) {print $pixcap, "\n";};
};
printf "<h2>%15s</h2>\n\n", $title;

if ($cat eq "") { # error
  print "Erroneous input !\n$errstr\n<p>\n\n";
} else { # NGC, IC, M
  print "$type in $con\n<p>\n\n";
  if ($MDesc) {print "<b>$MDesc</b>\n<p>\n\n";};
  print "<b><a href=\"des.html\">Dreyer's description</a></b>:\n<tt>$Desc</tt>\n<p>\n\n";
  if ( $CRefs ne "" ) {
    print "<b><a href=\"cid.html\">Cross Identifications</a></b>: $CRefs\n<p>\n" ;
  }
  if ($mnum) {
#
#    print "\n<p>\n<b>Testing !</b><br>\n  mdataline: $mdataline\n<p>\n\n";
#    print "RA: $RA, Dec: $Dec\n<p>\n\n";
#  
    print '<li><a href="' , $mcapdir , 'm', ('0' x (3-length($mnum))), $mnum,
          '.html">More on ', $title, " (SEDS)</a>\n<p>\n\n";
  } elsif ($caption) {
    chomp($caption);
    $caption = '<li><a href="' . $caption . '">More on ' . $title . "</a>\n<p>\n\n";
    print $caption;
  };
  print "\n<br clear=all>\n";
  print "<table border=2 cellpadding=5 cellspacing=0>\n";
  print "  <tr><th align=left>Right Ascension: </th><td>", $RA, " (hours : minutes)<br></td></tr>\n";
  print "  <tr><th align=left>Declination:    </th><td>", $Dec, " (degrees : minutes)<br></td></tr>\n";
  if ($Dist) {
    print "  <tr><th align=left>Distance: </th><td>", $Dist, " (* 1,000 light years)<br></td></tr>\n";
  };
  print "  <tr><th align=left>Apparent Magnitude: </th><td>", $Mag, "<br></td></tr>\n";
  print "  <tr><th align=left>Apparent Diameter: </th><td>", $Dim, " (arc minutes)<br></td></tr>\n";
  print "</table>\n<p>\n\n";

  print '<a href="ngc.html"><img alt="" src="ngc.jpg" border=0> NGC Home</a>', "\n";

  if ($catnum) {
    if ($catnum =~ /^i/i) {
      $inum = $catnum; $inum =~ s/i//i;
      if ($inum==1) {$num=$ICmax} else {$num=$inum-1};
      print '<img src="left.jpg" alt="<"><a href="ngc.cgi?i', $num, '"> IC ', $num, "</a> |\n";
      if ($inum==$ICmax) {$num=1} else {$num=$inum+1};
      print '<a href="ngc.cgi?i', $num, '">IC ', $num, '</a> <img src="right.jpg" alt=">">', "\n";
    } else {
      if ($catnum==1) {$num=$NGCmax} else {$num=$catnum-1};
      print '<img src="left.jpg" alt="<"> <a href="ngc.cgi?', $num, '"> NGC ', $num, "</a> |\n"; 
      if ($catnum==$NGCmax) {$num=1} else {$num=$catnum+1};
      print '<a href="ngc.cgi?', $num, '">NGC ', $num, '</a> <img src="right.jpg" alt=">">', "\n";
    };
  };  
  if ($mnum) {
    if ($mnum==1) {$num=$Mmax} else {$num=$mnum-1};
    print '<img src="left.jpg" alt="<"> <a href="ngc.cgi?m', $num, '">M', $num, "</a> |\n";
    if ($mnum==$Mmax) {$num=1} else {$num=$mnum+1};
    print '<a href="ngc.cgi?m', $num, '">M', $num, '</a> <img src="right.jpg" alt=">">', "\n";
  };
  print "<p>\n\n", '<li><a href="ngcdss.cgi?', $dssquery, '">Digital Sky Survey image</a>', "\n\n";

  if ($catnum) {
    $inum = $catnum; 
    if ( $catnum =~ /^i/i ) { # IC
      $inum =~ s/^i */IC/i;
    } else { # NGC
      $inum =~ s/^ */NGC/i;
    }
    print '<li><a href="revngcic.cgi?' , $inum , '">Revised NGC/IC data</a>' ,
      "\n\n" ;
    print '<li><a href="ngcic.cgi?' , $inum , '">NGC/IC data</a>' , "\n\n" ;
  }

  if ($mnum) {
    $ned = "M$mnum";
  } else {
    $ned = $catnum; $ned =~ s/[^0-9]//g; $ned = "$cat$ned";
  }
  print '<li><a href="http://simbad.u-strasbg.fr/sim-id.pl?Ident=' , $ned ,
    '">SIMBAD data</a>' , "\n\n";
#  print '<li><a href="http://archive.stsci.edu/cgi-bin/hst?action=search&resolver=SIMBAD&radius=10.0&sort1=ang_sep&max_rows=500&target=' ,
  print '<li><a href="http://archive.stsci.edu/hst/search.php?action=Search&resolver=SIMBAD&radius=10.0&ordercolumn1=ang_sep&max_records=500&outputformat=HTML_Table&sci_aec=S&showquery=on&target=' ,
    $ned, '">HST Archive images</a>', "\n\n";

#  if ($type eq "Galaxy") {
  if ($mnum) {
    if ($mnum == 102) {
      $ned = "NGC+5866";
    } else {
      $ned = "M+$mnum";
    }
  } else {
    $ned = $catnum; $ned =~ s/[^0-9]//g; $ned = "$cat+$ned";
  }
  print '<li><a href="http://nedwww.ipac.caltech.edu/cgi-bin/nph-objsearch?objname=',
    $ned, '&extend=no&out_equinox=J2000.0">NED data</a>', "\n\n";
#  }

  if ($mnum) {
    $ned = "M+$mnum"; 
  } else {
    $ned = $catnum; $ned =~ s/[^0-9]//g; $ned = "$cat+$ned";
  }
  print '<li><a href="http://adsabs.harvard.edu/cgi-bin/abs_connect?db_key=AST&sim_query=YES&object=',
    $ned, '">Publications and References (ADS)</a>' , "\n\n" ;

  if ($cat eq "M") {
    $catalog = "Messier" ;
    $ids = $mnum ;
  } else {
    $catalog = $cat ;
    $ids = $catnum; $ids =~ s/[^0-9]//g;
  }   
  print '<li><a href="http://www.visualdeepsky.org/cgi-bin/search.cgi?' ,
    "catalogs=$catalog&ids=$ids\">Observing Reports</a> (IAAC Netastrocatalog)";
    
}

print <<'EofF';
<hr>

<b>New search</b>:
<p>

Please type in the NGC number (number only, or preceded by "N" or "NGC")
or the IC number preceded by "I" or "IC",
or the Messier number preceded by "M".

<isindex action="ngc.cgi" prompt="Enter your Catalog Number:">

<p>
<a href="http://spider.seds.org/">Hartmut Frommert</a>
<a href="../Contact/spider.html">[contact]</a>
<p>
<a href="../index.html"><img src="../Jco/spider.ico.jpg" alt="[Spider] @"></a>
<a href="http://www.seds.org/"><img src="../Jco/seds.jpg" alt="[SEDS]"></a>

</body></html>
EofF
