#! /usr/bin/perl
$DEBUG = 0;
#**************************************************************
# Program    : ucatdmi310.pl                                  |
# Author     : L C Wright                                     |
# Date       : 5 March 2009                                   |
# Usage      : Data Managers Interface for UKERC Publications |
#              Catalogue                                      |
#              Handles input, update and delete of records    |
# Argument   :                                                |
# Called From: UCAT301.html                                   |
# Calls To   : None                                           |
# Last U/D   : 08/01/21 10:00                                 |
#-------------------------------------------------------------*
# Change Log                                                  |
# Date      Author     Modification                           |
# 16/04/09  LC Wright  Add new condition where research theme |
#                      99 is not displayed, but all articles  |
#                      submitted withouta research theme have |
#                      it applied                             |
# 22/04/09  LC Wright  Add the update function                |
# 23/04/09  LC Wright  Add the delete function                |
# 24/04/09  LC Wright  Fix bug where wrong classification in  |
#                      delete details display                 |
# 24/06/09  LC Wright  Fix line end "\n" appearing as n in    |
#                      UCAT323                                |
# 19/02/10  LC Wright  Add new pub type PhD Thesis            |
# 17/08/10  LCW        Modify for Oracle 11g                  |
# 18/08/10  LCW        Modify header and footer for new look  |
# 20/04/11  LCW        Add new pub type Policy Briefing Paper |
# 13/07/11  LCW        Read Oracle variables from file        |
# 25/01/12  LCW        Change copyright to 2014               |
# 22/01/13  LCW        Change to work as scheme in ERUDB      |
# 13/07/16  LCW        Add ArticleID to confirmation screen   |
# 27/07/16  LCW        Add classification by UKERC III theme  |
#                      and Energy Category                    |
# 03/08/16  LCW        Modify for a single level of theme     |
# 05/08/16  LCW        Check non-null URLs have http          |
# 18/07/17  LCW        Make it work in new path structure     |
# 19/07/17  LCW        Alter validation to use current year   |
#                      as maximum publication date.  Also add |
#                      aide-memoire on URL fields             |
# 27/09/17  LCW        Add link to HTML markup page           |
# 20/03/18  LCW        Add abstract                           |
# 27/03/18  LCW        Use modified version of NiceVal        |
# 07/12/18  LCW        Modify to use ERCP and tables with     |
#                      PUBS in their names                    |
# 16/01/20  LCW        On Input and Edit, changed the FORM    |
#                      method from get to post as the size    |
#                      limit of 2000 was too small            |
# 08/10/20  LCW        Add DOI support & New Look             |
# 07/12/20  PH         Added string "Energy Efficiency - " to |
#                      first four entries of energy sector    |
# 08/01/21  PH         Removed where editor variables have    |
#                      (Ed.) appended to them                 |
#21/09/2022 CM         Updated Breadcrumbs and titles         |
#-------------------------------------------------------------*
$last_updated = "08/01/21 10:00";
#------------------------------------------------*
# Declare which Perl packages we need            |
#------------------------------------------------*
use CGI qw(param);
use DBI;
use DateTime;

$sid        = "erudb";
$usrfile    = "oracle_us.txt";
$ourproj    = "UKERC";

#------------------------------------------------*
# Which machine are we on, and are we in test?   |
#------------------------------------------------*
$machine    = $ENV{SERVER_NAME};
$scriptname = $ENV{SCRIPT_NAME};
$scriptpath = substr($scriptname,1,4);
$EXTERNAL   = 0;
$TEST       = 0;

if    ($machine eq "ukerc.rl.ac.uk")          {$EXTERNAL = 1;}
elsif ($machine eq "ukerc8.rl.ac.uk")         {$EXTERNAL = 1;}
elsif ($machine eq "ukerc9.rl.ac.uk")         {$EXTERNAL = 1;}
elsif ($scriptpath eq "TEST")                 {$TEST     = 1;}
else {;}

if    ($EXTERNAL == 1) {$errm = "This does not run on external machines"; $ERROR = 1;}
elsif ($TEST     == 1) {$ourproj = "UKERC"; $mode = "TEST";}
else                   {$ourproj = "UKERC"; $mode = "INT";}

#------------------------------------------------*
# Get connect credentials                        |
#------------------------------------------------*
open(ORA,$usrfile);
@uvars      = <ORA>;
close(ORA);
for $i(0..$#uvars)
{
   chop ($uvars[$i]);
   ($uvproj, $uvmode, $uvname, $uvtext) = split(/]/, $uvars[$i]);
   if ($uvproj eq $ourproj && $uvmode eq $mode)
   {
      $username = $uvname;
      $userpw   = $uvtext;
   }
}

#------------------------------------------------*
# Set some variables                             |
#------------------------------------------------*
$pagecontact   = "ERCPManager@rl.ac.uk";
$toppagepath   = "https://$machine";
$extpath       = "https://ukerc.rl.ac.uk/";
$ukerchome     = "http://www.ukerc.ac.uk/";
$interface     = "Data Managers Interface";
$pagetitle     = "UKERC Roadmaps Data Managers Interface";
$ukerclogo     = "<img src=\"$atlaspath/Images/UKERC_logo.gif\" alt=\"UKERC Logo\" title=\"Go to UKERC Website\">";$ercr301       = "ERC721";
$ercr302       = "ERC722";
$ercr320       = "ERC723";
$dt            = DateTime->now;
$thisyear      = $dt->year;
$pdfcomment    = "<span class=\"obread\">Path name starts https://ukerc.rl.ac.uk/UCAT/PUBLICATIONS/ ".
                 "and is followed by the PDF name - max number of characters = 120</span>";

#------------------------------------------------*
# TEST: UKERC Library Test System                |
#------------------------------------------------*
if ($TEST == 1)
{
   $pagepath          = "https://".$machine;
   $progpath          = "https://$machine/cgi-bin";
   $atlaspath         = "https://$machine";
   $interface         = "$interface - TEST";
}
#------------------------------------------------*
# ERCP: UKERC RR Internal and External Live      |
#       Systems                                  |
#------------------------------------------------*
else
{
   $pagepath          = "https://$machine";
   $progpath          = "https://$machine/cgi-bin";
   $atlaspath         = "https://".$machine;
}

#----------------------------------------------------------------*
# Set variables that depend on the location                      |
#----------------------------------------------------------------*
$stylesheet    = $toppagepath."/StyleSheets/site-style.css";
$imgpath       = $toppagepath."/Images";
$pubpath       = $extpath."/UCAT/PUBLICATIONS";			#Needs sorting out for roadmaps
$liblink       = "$progpath/road_query.pl";
$rrhome        = $liblink;
$dmihome       = $atlaspath."/cgi-bin/ercdmi1.pl";
$markpage      = $toppagepath."/html-markup.html";
$prog          = $progpath."/roadmapdmi310.pl";
$menuprog      = $progpath."/roadmapdmi1.pl";
$returnmenu    = $dmihome;
$logout        = $atlaspath."/ERCR300.html";
$breadcrumbs   = "      <a class=\"gbread\" href=\"$ukerchome\">Home</a>".
                 "      | <a class=\"gbread\" href=\"$atlaspath\">EDC</a>".
                 "      | <a class=\"gbread\" href=\"$dmihome\">".
                 "      Data Managers Interface</a>".
                 "      | <a class=\"gbread\" href=\"$menuprog\">".
                 "      UKERC Roadmaps </a>";
$ERROR         = 0;

#------------------------------------------------*
# Get the input parameters from command line     |
#------------------------------------------------*
&ParaGet;

#------------------------------------------------*
# Write page header                              |
#------------------------------------------------*
&ShowHeader;

if ($DEBUG == 1)
{
   print "<b>Start of DEBUG</b><br>";
   print "machine is $machine<br>";
   print "scriptpath is $scriptpath<br>";
   print "sid is $sid<br>";
   if ($TEST == 1) {print "Mode is TEST<br>";}
   else            {print "Mode is LIVE<br>";}
   print "username is $username<br>";
   print "Action is $action<br>";
   while ( ($key, $value) = each(%input) ) 
   {
      print "$key is $value<br />\n";
   }
   print "Pagepath $pagepath<br>";
   print "Image path $imgpath<br>";
   print "Style Sheet $stylesheet<br>";
   print "<b>End of DEBUG</b><br>";
   print "<hr>";
} # END OF DEBUG

#----------------------------------------------------------------*
# Call subroutine in response to calling button                  |
#----------------------------------------------------------------*
if ($ERROR == 0) 
{
   if ($action  eq "Start Working" && $achoose eq "Input")  {&ShowInput;    $scrget = "UCAT310";} # <-------------------
   if ($action  eq "Submit Record")                         {&InputRecord;  $scrget = "UCAT319";}
   if ($action  eq "Start Working" && ($achoose eq "Update" || $achoose eq "Delete")) 
                                                            {&ShowSearch;   $scrget = "UCAT320";}
   if ($action  eq "Search for Publications")               {&RunSearch;    $scrget = "UCAT321";}
   if ($action  eq "Work with this Publication" && $achoose eq "Update")
                                                            {&ShowDetails;   $scrget = "UCAT322";}
   if ($action  eq "Work with this Publication" && $achoose eq "Delete")   
                                                            {&ShowDetails;   $scrget = "UCAT323";}
   if ($action  eq "Update Record")                         {&UpdateRecord;  $scrget = "UCAT319";}
   if ($action  eq "Destroy Record Now!")                   {&DeleteRecord;  $scrget = "UCAT319";}
}

if ($ERROR == 0) {eval "&".$scrget;}
if ($ERROR == 1) {&ErrmShow;}

&ShowFooter;

exit;

#-------------------------------------------------------------------------------------*
# Processing Subroutines                                                              |
# CreateCitation : Create formal citation according to publication type               |
# DeleteRecord: Delete the record from the database                                   |
# InputRecord : Insert record into database                                           |
# RunSearch   : Create and run search SQL and produce a list of records               |
# ShowInput   : Get the information needed to show the input record screen            |
# ShowSearch  : Show search screen for Edit and Delete                                |
# ShowDetails  : Show the update screen                                               |
# UpdateRecord: Update record in database                                             |
# Validation  : Validate input                                                        |
#-------------------------------------------------------------------------------------*

#----------------------------------------------------------------*
# Subroutine  : CreateCitation                                   |
# Purpose     : Create the formal citation according to the type |
#               of publication                                   |
# Called From : InputRecord                                      |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             CreateCitation
{
   if ($DEBUG == 1) {print "In CreateCitation<br>\n";}
   #---------------------------------------------*
   # Almost everything starts with               |
   # Authors (Year). Title                       |
   #---------------------------------------------*
   $acitstart                                  = "<b>$aauthors ($ayear)</b>. $atitle. ";
   #---------------------------------------------*
   # Book                                        |
   # Author (Year). Title.                       |
   # Publisher, ISBN [Pages]                     |
   #---------------------------------------------*
   if ($apubtype == 1) 
   {
      $acitation                               = $acitstart."$apublisher. ISBN $aisbn";
      if ($apages ne "")           {$acitation = $acitation." ($apages pp.)";}
   }
   #---------------------------------------------*
   # Book Chapter                                |
   # Author (Year). title.                       |
   # In Editors (Ed.) OpusTitle (Chapter number).|
   # Publisher. ISBN isbn                        |
   #---------------------------------------------*
   if ($apubtype == 2) 
   {
      $acitation                               = $acitstart.
                                                 " In <b>$aeditor (Eds)</b> $aopustitle (Chapter $apages). $apublisher. ".
                                                 "ISBN $aisbn";
   }
   #---------------------------------------------*
   # Conference Publication                      |
   # Authors (Year). Title. [OpusTitle           |
   # Conference dates. Venue. Publisher. ISBN]   |
   #---------------------------------------------*
   if ($apubtype == 3) 
   {
      $acitation                               = $acitstart;
      if ($aopustitle       ne "") {$acitation = $acitation." <i>$aopustitle</i>";}
      if ($aconferencedates ne "") {$acitation = $acitation." $aconferencedates ";}
      if ($avenue ne "")           {$acitation = $acitation." $avenue. ";}
      if ($apublisher ne "")       {$acitation = $acitation." $apublisher. ";}
      if ($aisbn ne "")            {$acitation = $acitation." ISBN $aisbn ";}
   }
   #---------------------------------------------*
   # Response to Government Consultation         |
   # Authors. (Year). Title. [UKERC Report No],  |
   # Publisher                                   |
   #---------------------------------------------*
   if ($apubtype == 4) 
   {
      $acitation                               = $acitstart;
      if ($aukercrn         ne "") {$acitation = $acitation." UKERC Report $aukercrn. ";}
      if ($apublisher       ne "") {$acitation = $acitation." $apublisher. ";}
   }
   #---------------------------------------------*
   # Journal Article                             |
   # Authors. (Year). Title. Journal, Volume     |
   # [(Issue)]: pages                            |
   #---------------------------------------------*
   if ($apubtype == 5) 
   {
      if ($ajournal eq "") {$ajournal = $aopustitle;}
      $acitation                               = $acitstart." <i>$ajournal</i>, <b>$avolume</b>";
      if ($aissue   ne "")         {$acitation = $acitation." ($aissue)";}
      $acitation                               = $acitation.": $apages";
   }
   #---------------------------------------------*
   # Media Material                              |
   # Authors. (Year). Title. Publication Date    |
   #---------------------------------------------*
   if ($apubtype == 6) 
   {
      $acitation                               = $aauthors." ($apubdate). $atitle. Press Notes. ";
      if ($apublisher ne "")       {$acitation = $acitation. "$apublisher";}
   }
   #---------------------------------------------*
   # Meeting Place Workshop Report               |
   # Authors. (Year). Title. UKERC Report Number,|
   # Publisher, Pages                            |
   #---------------------------------------------*
   if ($apubtype == 7) 
   {
      $acitation                               = $acitstart." UKERC Report $aukercrn. $apublisher";
      if ($apages ne "")           {$acitation = $acitation." ($apages pp.)";}
   }
   #---------------------------------------------*
   # Research Atlas Landscape or Roadmap         |
   # Authors. (Year). Title.                     |
   #---------------------------------------------*
   if ($apubtype == 8 || $apubtype == 9) # This one for Roadmaps - others not needed, still needs adjusting to different table
   {
      $acitation                               = $acitstart;
   }
   #---------------------------------------------*
   # TPA Report                                  |
   # Authors. (Year). Title. TPA Report Number,  |
   # [UKERC Report Number]. Publisher            |
   #---------------------------------------------*
   if ($apubtype == 10) 
   {
      $acitation                               = $acitstart." TPA Report $atparn.";
      if ($aukercrn         ne "") {+$acitation = $acitation." UKERC Report $aukercrn." ;}
      $acitation                               = $acitation." $apublisher. ";
   }
   #---------------------------------------------*
   # UKERC Report and UKERC Working Paper        |
   # Authors. (Year). Title. UKERC Report Number,|
   # Publisher                                   |
   #---------------------------------------------*
   if ($apubtype == 11 || $apubtype == 12) 
   {
      $acitation                               = $acitstart;
      if ($aukercrn         ne "") {$acitation = $acitation." UKERC Report $aukercrn. ";}
      if ($apublisher       ne "") {$acitation = $acitation. "$apublisher";}
   }
   #---------------------------------------------*
   # Conference Paper                            |
   # Authors. (Year). Title. Conference Name,    |
   # [dates, venue, publisher, isbn]             |
   #---------------------------------------------*
   if ($apubtype == 13) 
   {
      $acitation                               = $acitstart." <i>$aopustitle</i>";
      if ($aconferencedates ne "") {$acitation = $acitation." $aconferencedates ";}
      if ($avenue           ne "") {$acitation = $acitation." $avenue ";}
      if ($apublisher       ne "") {$acitation = $acitation.". $apublisher ";}
      if ($aisbn            ne "") {$acitation = $acitation." ISBN $aisbn";}
   }
   #---------------------------------------------*
   # PhD Thesis                                  |
   # Authors. (Year). Title. University, [url,   |
   # pages]                                      |
   #---------------------------------------------*
   if ($apubtype == 14) 
   {
      $acitation                               = $acitstart." PhD Thesis, $aopustitle";
      if ($apages           ne "") {$acitation = $acitation." $apages p. ";}
   }
   #---------------------------------------------*
   # Policy Briefing Paper                       |
   # Authors. (Year). Title. UKERC Report No,    |
   # [url]                                       |
   #---------------------------------------------*
   if ($apubtype == 15) 
   {
      $acitation                               = $acitstart;
      if ($aukercrn         ne "") {$acitation = $acitation." UKERC Report $aukercrn. ";}
   }
   #---------------------------------------------*
   # Anything can have a DOI                     |
   #---------------------------------------------*
   if ($adoi ne "" && $adoi ne "(none)")
   {
      $acitation = $acitation." DOI: <a href=\"$adoi\" target=\"_blank\">$adoi</a>";
   }
   #---------------------------------------------*
   # Tidy up the final citation                  |
   #---------------------------------------------*
   $icitation = &NiceVal($acitation);
}

#----------------------------------------------------------------*
# Subroutine  : DeleteRecord                                     |
# Purpose     : Remove the record from the tables                |
# Called From : Main Routine                                     |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
#This won't be needed
sub             DeleteRecord
{
   if ($DEBUG == 1) {print "In DeleteRecord<br>\n";}
   $breadcrumbs = $breadcrumbs.
                 "      | <span class=\"obread\">Record Deletion Complete</span>";
   $title     = "Deleted Record";
   $infoline  = "The following record has been completely removed from the database";
   #---------------------------------------------*
   # Set up for completion screen                |
   # Do this BEFORE deleting!                    |
   #---------------------------------------------*
   $newartid    = $uradio;
   if ($ERROR == 0)
   {
      $select   = "SELECT   PubType ".
                  "FROM     tbl_PUBS_Pubtype ".
                  "WHERE    TypeID = $apubtype";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $apubname = $ids[1];
   }
   if ($ERROR == 0)
   {
      $select   = "SELECT   Citation ".
                  "FROM     tbl_PUBS_Article ".
                  "WHERE    ArticleID = $uradio";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $acitation = $ids[1];
   }
   if ($ERROR == 0)
   {
      $select   = "SELECT   r.U1Name ".
                  "FROM     tbl_PUBS_ArticleResearchtheme a, tbl_PUBS_Researchtheme r ".
                  "WHERE    r.ThemeID = a.ThemeID ".
                  "AND      r.ThemeID < 99 ".
                  "AND      a.ArticleID = $uradio ".
                  "ORDER BY r.U1Name ASC";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $au1themes = "";
      if ($#ids > 0)
      {
         for $i(1..$#ids)
         {
            $au1themes = $au1themes.$ids[$i]."<br />";
         }
      }
      if ($au1themes eq "") {$au1themes = "None selected<br />";}
   }
   if ($ERROR == 0)
   {
      $select   = "SELECT   e.SectorName ".
                  "FROM     tbl_PUBS_ArticleEnergycat a, tbl_PUBS_Energysector e ".
                  "WHERE    e.CatID = a.CatID ".
                  "AND      a.ArticleID = $uradio ".
                  "ORDER BY e.SectorName ASC";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $asectors   = "";
      if ($#ids > 0)
      {
         for $i(1..$#ids)
         {
            $asectors = $asectors.$ids[$i]."<br />";
         }
      }
      if ($asectors eq "") {$asectors = "None selected<br />";}
   }
   if ($ERROR == 0)
   {
      $select   = "SELECT   r.TagType ".
                  "FROM     tbl_PUBS_ArticleTagtype a, tbl_PUBS_Tagtype r ".
                  "WHERE    r.TagID     = a.TagID ".
                  "AND      a.ArticleID = $uradio ".
                  "ORDER BY r.Tagtype ASC";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $aothertypes = "";
      for $i(1..$#ids)
      {
         $aothertypes = $aothertypes."$ids[$i]<br />";
      }
      if ($aothertypes eq "") {$aothertypes = "None found";}
   }
   $select      = "SELECT   TxData ".
                  "FROM     tbl_PUBS_Text ".
                  "WHERE    ArticleID = $uradio ".
                  "AND      TxType    = 'A' ".
                  "ORDER BY TxNo ASC";
   &RunQuery("$select?S");
   &ProcessRows("1A");
   for $i(1..$#ids)
   {
      $aabstract= $aabstract.
                  $ids[$i];
   }
   $buttonlegend = "";
   #---------------------------------------------*
   # Do the deletion                             |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $delete = "DELETE ".
                "FROM   tbl_PUBS_ArticlePubtype ".
                "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $delete = "DELETE ".
                "FROM   tbl_PUBS_ArticleResearchtheme ".
                "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $delete = "DELETE ".
                "FROM   tbl_PUBS_ArticleEnergycat ".
                "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $delete = "DELETE ".
                "FROM   tbl_PUBS_ArticleTagtype ".
                "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $delete = "DELETE ".
                "FROM   tbl_PUBS_Text ".
                "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $delete = "DELETE ".
                "FROM   tbl_PUBS_Article ".
                "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
   }
}

#----------------------------------------------------------------*
# Subroutine  : InputRecord                                      |
# Purpose     : Validate the input data, and if OK, enter into   |
#               the database                                     |
# Called From : Main Routine                                     |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             InputRecord
{
   if ($DEBUG == 1) {print "In InputRecord<br>\n";}
   $breadcrumbs = $breadcrumbs.
                 "      | <span class=\"obread\">Input Complete</span>";
   $title     = "Input New Record";
   $infoline  = "The following record has been added to the system";
   &Validation;
   #---------------------------------------------*
   # If the record was valid, input into the     |
   # article table                               |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $select   = "SELECT MAX(ArticleID) ".
                  "FROM   tbl_PUBS_Article";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $maxartid = $ids[1] + 1;
      # if ($apubtype == 3)
      # {
      #    $aauthors = $aauthors;
      # }
      $iauthors = &NiceVal($aauthors);
      $ipauthor = $apauthor;
      $ipauthor =~ y/a-z/A-Z/;
      $ipauthor = &NiceVal($ipauthor);
      $ititle   = &NiceVal($atitle);
      $ihead    = "INSERT INTO tbl_PUBS_Article (ArticleID, AuthorsUC, Authors, Title, Year, ";
      $itail    = "VALUES ($maxartid, '".$ipauthor."', '".$iauthors."', '".$ititle."', $ayear, ";
      if ($aisbn      ne "") {$ihead    = $ihead."ISBN, ";
                              $itail    = $itail."'".$aisbn."', ";}
      if ($aissue     ne "") {$ihead    = $ihead."Issue, ";
                              $iissue   = &NiceVal($aissue); 
                              $itail    = $itail."'".$iissue."', ";}
      if ($ajournal   ne "") {$ihead    = $ihead."OpusTtile, ";
                              $ijournal = &NiceVal($ajournal);
                              $itail    = $itail."'".$ijournal."', ";}
      if ($apages     ne "") {$ihead    = $ihead."Pages, ";
                              $ipages   = &NiceVal($apages);
                              $itail    = $itail."'".$ipages."', ";}
      if ($apublisher ne "") {$ihead    = $ihead."Publisher, ";  
                              $ipub     = &NiceVal($apublisher);
                              $itail    = $itail."'".$ipub."', ";}
      if ($adoi       ne "") {$ihead    = $ihead."DOI, ";
                              $idoi     = &NiceVal($adoi);
                              $itail    = $itail."'".$idoi."', ";}
      if ($aurl       ne "") 
      {
         if (substr($aurl,0,4) ne "http")
         {
                              $aurl     = $pubpath."/".$aurl;
         }
                              $ihead    = $ihead."URL, ";
                              $iurl     = &NiceVal($aurl);
                              $itail    = $itail."'".$iurl."', ";
      }
      if ($avolume    ne "") {$ihead    = $ihead."Volume, ";
                              $itail    = $itail."'".$avolume."', ";}
      if ($aeditor    ne "") {$ihead    = $ihead."Editor, ";
                              $ieditor  = &NiceVal($aeditor);
                              $itail    = $itail."'".$ieditor."', ";}
      if ($aukercrn   ne "") {$ihead    = $ihead."UKERCReportNo, ";
                              $iukercrn = &NiceVal($aukercrn);
                              $itail    = $itail."'".$iukercrn."', ";}
      if ($aopustitle ne "") {$ihead    = $ihead."OpusTitle, ";
                              $iopus    = &NiceVal($aopustitle);
                              $itail    = $itail."'".$iopus."', ";}
      if ($aconferencedates ne "") 
                             {$ihead    = $ihead."ConferenceDates, ";
                              $icondate = &NiceVal($aconferencedates);
                              $itail    = $itail."'".$icondagte."', ";}
      if ($avenue     ne "") {$ihead    = $ihead."Venue, ";
                              $ivenue   = &NiceVal($avenue);
                              $itail    = $itail."'".$ivenue."', ";}
      &CreateCitation;
      $ihead  = $ihead."Citation) ";
      $itail  = $itail."'".$icitation."')";
      $insert = $ihead.$itail;
      if ($DEBUG == 1) {print "$insert<br>";}
      else             {&RunQuery("$insert?I");}
   }
   #---------------------------------------------*
   # Put an entry into the table that links      |
   # article and publication type                |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $insert = "INSERT INTO tbl_PUBS_ArticlePubtype (ArticleID, TypeID) ".
                "VALUES ($maxartid, $apubtype)";
      if ($DEBUG == 1) {print "$insert<br>";}
      else             {&RunQuery("$insert?I");}
   }
   #---------------------------------------------*
   # Put entries into the table that links       |
   # article and research themes                 |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $a1tno     = "";
      while ( ($key, $value) = each(%atheme1) )
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleResearchtheme (ArticleID, ThemeID) ".
                   "VALUES ($maxartid, $key)";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
         $a1tno  = $a1tno.$key.", ";
      }
      chop($a1tno); chop ($a1tno);
      if ($a1tno eq "")
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleResearchtheme (ArticleID, ThemeID) ".
                   "VALUES ($maxartid, 99)";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
   }
   #---------------------------------------------*
   # If appropriate, put entries into the table  |
   # that links article and tags                 |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      if ($auwide eq "on")
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleTagtype (ArticleID, TagID) ".
                   "VALUES ($maxartid, 2)";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
      if ($amedia eq "on")
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleTagtype (ArticleID, TagID) ".
                   "VALUES ($maxartid, 1)";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
   }
   #---------------------------------------------*
   # If appropriate, put entries into the table  |
   # that links energy category and article      |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $nsects    = "";
      for $j(1..$#newsect)
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleEnergycat (ArticleID, CatID) ".
                   "VALUES ($maxartid, '".$newsect[$j]."')";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
         $nsects = $nsects."'".$newsect[$j]."',";
      }
      chop($nsects);
   }
   #---------------------------------------------*
   # If the record was valid, and has an abstract|
   # chop into 900 char bits and load into       |
   # text table with type A                      |
   #---------------------------------------------*
   if ($ERROR == 0 && $aabstract ne "")
   {
      $select = "SELECT MAX(XID) ".
                "FROM   tbl_PUBS_Text";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $maxxid = $ids[1];
      &ChopText("900]$aabstract");
      for $i(1..$#outtext)
      {
         $maxxid++;
#print "Outtext: $outtext[$i]<br>\n";
         $indat  = "'".&NiceVal($outtext[$i])."'";
#print "Indat: $indat<br>\n";
         $insert = "INSERT INTO tbl_PUBS_Text (XID, ArticleID, TxType, TxNo, TxData) ".
                   "VALUES                    ($maxxid, $maxartid, 'A', $i, $indat) ";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
   }
   #---------------------------------------------*
   # Set up for completion screen                |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $newartid   = $maxartid;
      $buttonlegend = "                <form action=\"$menuprog\" method=\"get\">\n".
                      "                 <input type=\"submit\" name=\"GoButton\" value=\"Input Another Record\">\n".
                      "                </form>\n";
      $select   = "SELECT   PubType ".
                  "FROM     tbl_PUBS_Pubtype ".
                  "WHERE    TypeID = $apubtype";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $apubname = $ids[1];
   }
   if ($ERROR == 0 && $a1tno ne "")
   {
      $select   = "SELECT   U1Name ".
                  "FROM     tbl_PUBS_Researchtheme ".
                  "WHERE    ThemeID IN ($a1tno) ".
                  "ORDER BY U1Name ASC";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $au1themes = "";
      if ($#ids > 0)
      {
         for $i(1..$#ids)
         {
            $au1themes = $au1themes.$ids[$i]."<br />";
         }
      }
      if ($au1themes eq "") {$au1themes = "None selected<br />";}
   }
   if ($ERROR == 0)
   {
      $aothertypes = "";
      $i = 0;
      if ($amedia ne "")
      {
         $i++;
         $aotypes[$i] = "Media";
      }
      if ($auwide ne "")
      {
         $i++;
         $aotypes[$i] = "Non-Project-Specific";
      }
      for $i(1..$#aotypes)
      {
         $aothertypes = $aothertypes."$aotypes[$i]<br />";
      }
      if ($aothertypes eq "") {$aothertypes = "None selected<br />";}
   }
   if ($ERROR == 0)
   {
      $select    = "SELECT   SectorName ".
                   "FROM     tbl_PUBS_Energysector ".
                   "WHERE    CatID IN ($nsects) ".
                   "ORDER BY CatID ASC";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      for $j(1..$#ids)
      {
         $asectors  = $asectors.
                      $ids[$j].
                      "<br />";
      }
   }
}

#----------------------------------------------------------------*
# Subroutine  : RunSearch                                        |
# Purpose     : Create and run SQL, and get list of articles     |
#               meeting search criteria                          |
# Called From : Main Routine                                     |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             RunSearch
{
   if ($DEBUG == 1) {print "In RunSearch<br>\n";}
   if ($achoose eq "Update") {$pagetitle = "Update Record";}
   if ($achoose eq "Delete") {$pagetitle = "Delete Record";}
   if ($uartid eq "" && $uauthor eq "" && $utitle eq "" && $upubtype == 0 && $uyear == 0)
   {
      $ERROR  = 1;
      $errm   = "Please enter something to search for<br>&nbsp;";
   }
   if ($ERROR == 0)
   {
      $breadcrumbs = $breadcrumbs.
                     " | <a href=\"$prog?GoButton=Start Working&AChoose=$achoose\" class=\"gbread\">Search for Record</a> ".
                     " | <span class=\"obread\">Select Record</span>";
      $selargs     = "SELECT a.RoadID, a.Title ";
      $seltabs     = "FROM   tbl_Roadmaps a,tbl_RoadmapsEnergycat b ";
      $seljoin     = "WHERE a.RoadID = b.RoadID ";		# Need to come back and have a look at this
      $selsort     = "ORDER BY a.PubDate DESC ";
      #----------------------------------------------------------*
      # If an ArticleID was given, this is the most accurate     |
      #----------------------------------------------------------*
      if ($uartid ne "")
      {
         $seljoin   = $seljoin.
                      "AND    a.RoadID = $uartid ";
      }
      #----------------------------------------------------------*
      # Otherwise put together a wider search                    |
      #----------------------------------------------------------*
      else
      {
         if ($uauthor ne "")# Doing something with UC
         {
            if (index($uauthor, ",") > -1)
            {
               $authorarg = $uauthor;
               $seljoin   = $seljoin.
                            "AND    a.Author LIKE '%".$authorarg."%' ";
            }
            elsif (index($uauthor, " ") > -1)
            {
               (@authora) = split(/ /, $uauthor);
               for $i(0..$#authora)
               {
                  $authorarg = $authora[$i];
                  $authorarg =~ y/a-z/A-Z/;
                  $seljoin   = $seljoin.
                               "AND    a.AuthorUC LIKE '%".$authorarg."%' ";
               }
            }
            else
            {
               $authorarg = $uauthor;
               $authorarg =~ y/a-z/A-Z/;
               $seljoin   = $seljoin.
                            "AND    a.AuthorUC LIKE '%".$authorarg."%' ";
            }
         }
         if ($utitle ne "")
         {
            $utitleup     = $utitle;
            $utitleup     =~ y/a-z/A-z/;
            if (index($utitleup, " AND ") > -1)
            {
               (@titlea) = split(/ AND /, $utitleup);
               for $i(0..$#titlea)
               {
                  $seljoin   = $seljoin.
                               "AND    UPPER(a.Title) LIKE '%".$titlea[$i]."%' ";
               }
            }
            elsif (index($utitleup, " NOT ") > -1)
            {
               (@titlea) = split(/ NOT /, $utitleup);
               $seljoin   = $seljoin.
                            "AND    UPPER(a.Title) LIKE '%".$titlea[0]."%' ";
               for $i(1..$#titlea)
               {
                  $seljoin   = $seljoin.
                               "AND    UPPER(a.Title) NOT LIKE '%".$titlea[$i]."%' ";
               }
            }
            else
            {
               (@titlea) = split(/ /, $utitleup);
               for $i(0..$#titlea)
               {
                  $seljoin   = $seljoin.
                               "AND    UPPER(a.Title) LIKE '%".$titlea[$i]."%' ";
               }
            }
         }
         #if ($upubtype > 0)
         #{
         #   $seljoin   = $seljoin.
         #                "AND    j.TypeID = $upubtype ";
         #}
         if ($uyear > 0)
         {
            $seljoin   = $seljoin.
                         "AND    a.PubDate = $uyear ";
         }
      }
      $select       = $selargs." ".$seltabs." ".$seljoin." ".$selsort;
      &RunQuery("$select?S");
      &ProcessRows("2A");
      if ($#ids < 1)
      {
         $ERROR     = 1;
         $errm      = "Sorry - no records found from your search<br>&nbsp;";
      }
      else
      {
         $counttext = $#ids;
         @artid     = @ids;
         @citation  = @val;
      }
   }
}   

#----------------------------------------------------------------*
# Subroutine  : ShowDetails                                      |
# Purpose     : Show existing data for the chosen record, and    |
#               also drop-down menus of choices                  |
# Called From : Main Routine                                     |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ShowDetails
{
   if ($DEBUG == 1) {print "In ShowDetails<br>\n";}
   $backstr                       = "AChoose=$achoose&";
   if ($uartid   ne "") {$backstr = $backstr."UArtID=$uartid&";}
   if ($uauthor  ne "") {$backstr = $backstr."UAuthor=$uauthor&";}
   if ($utitle   ne "") {$backstr = $backstr."UTitle=$utitle&";}
   if ($upubtype ne "") {$backstr = $backstr."UPubType=$upubtype&";}
   if ($uyear    ne "") {$backstr = $backstr."UYear=$uyear&";}
   chop ($backstr);
   $breadcrumbs = $breadcrumbs.
                  " | <a href=\"$prog?GoButton=Start Working&AChoose=$achoose\" class=\"gbread\">Search for Record</a> ".
                  " | <a href=\"$prog?GoButton=Search for Publications&$backstr\" class=\"gbread\">Select Record</a> ";
   if ($achoose eq "Update")
   {
      $breadcrumbs = $breadcrumbs.
                     " | <span class=\"obread\">Update Record</span>";
   }
   if ($achoose eq "Delete")
   {
      $breadcrumbs = $breadcrumbs.
                     " | <span class=\"obread\">Delete Record</span>";
   }
   if ($achoose eq "Delete")
   {
      $select      = "SELECT PubDate ".				#Selecting citation from pubs table where the ID is equal to the selected data report - 993 in dmi310-Old
                     "FROM   tbl_Roadmaps ".		#Same logic stands for all simmilarly written/structured code
                     "WHERE  RoadID = $uradio ";	#Table for all will be tbl_roadmaps
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $ocitation   = $ids[1];
   }
   $select      = "SELECT Author, Title, PubDate, CatID ".
                  "FROM   tbl_Roadmaps ".
                  "WHERE  RoadID = $uradio ";
   &RunQuery("$select?S");
   &ProcessRows("4A");
   $oauthors    = $ids[1];
   $otitle  = $val[1];
   $oyear      = $tri[1];
   $odoi       = $qat[1];
   #$odoi        = $qin[1];
   if ($odoi eq "") {$odoi = "(none)";}
   $select      = "SELECT a.TypeID, p.PubType ".
                  "FROM   tbl_PUBS_ArticlePubtype a, tbl_PUBS_Pubtype p ".
                  "WHERE  a.TypeID = p.TypeID ".
                  "AND    a.ArticleID = $uradio ";
   &RunQuery("$select?S");
   &ProcessRows("2A");
   $apubtype    = $ids[1]; #try setting equal to 1
   $apubname    = $val[1];
   $select      = "SELECT   FieldName, Required, PreferredName ".
                  "FROM     tbl_PUBS_Metadata ".
                  "WHERE    TypeID = $apubtype ".
                  "ORDER BY FieldNo ASC";				#Accending order
   &RunQuery("$select?S");
   &ProcessRows("3A");
   $fieldtot    = $#ids;
   @fieldz      = @ids;
   @mandat      = @val;
   @fname       = @tri;
   $o        = 0;
   for $z(1..$fieldtot)
   { 
      $select   = "SELECT $fieldz[$z] ".
                  "FROM   tbl_PUBS_Article ".
                  "WHERE  ArticleID = $uradio";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $ovalue[$z] = $ids[1];
      $varname    = "A".$fieldz[$z];
      if ($fields[$z] eq "PublishedDate") 
      {
         $fname[$z]      = "Issued Date<br /><span class=\"obread\">as dd/mm/yy</span>";
      }
      if ($achoose eq "Update")
      {
         if ($mandat[$z]   eq "Y")           {$manmark    = "<span class=\"greentext\">* </span>";}
         else                                {$manmark    = "";}
         $o++; $outline[$o] = "                <tr>\n";
         $o++; $outline[$o] = "                  <td valign=\"top\"><b>$fname[$z]$manmark</b></td>\n";
         $o++; $outline[$o] = "                  <td colspan=\"2\">Was: <span class=\"greentext\">$ovalue[$z]</span><br><br>\n";
         $o++; $outline[$o] = "	                   <input name=\"$varname\" type=\"text\" size=\"100\" value=\"$ovalue[$z]\">\n";
         if ($varname eq "AURL")
         {
            $o++; $outline[$o] = "                    <br>$pdfcomment\n";
         }
         $o++; $outline[$o] = "                  </td>\n";
         $o++; $outline[$o] = "                </tr>\n";
      }
      if ($achoose eq "Delete")
      {
         $o++; $outline[$o] = "                <tr>\n";
         $o++; $outline[$o] = "                  <td valign=\"top\"><b>$fname[$z]</b></td>\n";
         $o++; $outline[$o] = "                  <td colspan=\"2\">$ovalue[$z]</td>\n";
         $o++; $outline[$o] = "                </tr>\n";
      }
   }
   $select      = "SELECT   TxData ".
                  "FROM     tbl_PUBS_Text ".
                  "WHERE    ArticleID = $uradio ".
                  "AND      TxType    = 'A' ".
                  "ORDER BY TxNo ASC";
   &RunQuery("$select?S");
   &ProcessRows("1A");
   for $i(1..$#ids)
   {
      $oabstract= $oabstract.
                  $ids[$i];
   }
   $select      = "SELECT   ThemeID, U1Name ".
                  "FROM     tbl_PUBS_Researchtheme ".
                  "WHERE    ThemeID < 99 ".
                  "ORDER BY U1Name ASC";
   &RunQuery("$select?S");
   &ProcessRows("2A");
   @theme1id    = @ids;
   @theme1      = @val;
   $notheme1    = "";
   for $i(1..$#theme1id)
   {
      $select      = "SELECT   ThemeID ".
                     "FROM     tbl_PUBS_ArticleResearchtheme ".
                     "WHERE    ArticleID = $uradio ".
                     "AND      ThemeID   = $theme1id[$i] ";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      if ($#ids > 0) {$otheme1[$i]     = "Was: "; $notheme1 = 1;}
      else           {$otheme1[$i]     = "";}
   }
   $select  = "SELECT TagID ".
              "FROM   tbl_PUBS_ArticleTagtype ".
              "WHERE  ArticleID = $uradio";
   &RunQuery("$select?S");
   &ProcessRows("1A");
   $ononproj = "";
   $omedia   = "";
   for $i(1..$#ids)
   {
      if ($ids[$i] == 1) {$omedia   = "checked"; $omediastatus   = "Was: ";}
      if ($ids[$i] == 2) {$ononproj = "checked"; $ononprojstatus = "Was: ";}
   }
   $select   = "SELECT   CatID, SectorName ".
               "FROM     tbl_PUBS_Energysector ".
               "ORDER BY CatID ";
   &RunQuery("$select?S");
   &ProcessRows("2A");
   @sectid   = @ids;
   @sectname = @val;
   $eetag = "Energy Efficiency – ";
   $sectname[1] = $eetag.$sectname[1];
   $sectname[2] = $eetag.$sectname[2];
   $sectname[3] = $eetag.$sectname[3];
   $sectname[4] = $eetag.$sectname[4];
   if ($DEBUG == 1) {print "array 0 $sectname[0]<br>\n";}
   if ($DEBUG == 1) {print "array 1 $sectname[1]<br>\n";}
   if ($DEBUG == 1) {print "array 2 $sectname[2]<br>\n";}
   if ($DEBUG == 1) {print "array 3 $sectname[3]<br>\n";}
   if ($DEBUG == 1) {print "array 4 $sectname[4]<br>\n";}
   $select   = "SELECT CatID ".
               "FROM   tbl_PUBS_ArticleEnergycat ".
               "WHERE  ArticleID = $uradio ";
   &RunQuery("$select?S");
   &ProcessRows("1A");
   @usectid  = @ids;
   $ebrk1    = 15;
   for $i(1..$#sectid)
   {
      $checked = "";
      for $j(1..$#usectid)
      {
         if ($sectid[$i] eq $usectid[$j]) 
         {
            $checked = "checked";
            $osect[$i] = "Was: ";
         }
      }
      if ($i < $ebrk1)
      {
         $esectcol1 = $esectcol1.
                      "                        <tr>\n".
                      "                          <td align=\"left\" valign=\"top\">\n".
                      "                            <input type=\"checkbox\" name=\"ESect_$sectid[$i]\" $checked />\n".
                      "                          </td>\n".
                      "                          <td align=\"left\" valign=\"top\">$sectname[$i]</td>\n".
                      "                        </tr>\n";
      }
      else
      {
         $esectcol2 = $esectcol2.
                      "                        <tr>\n".
                      "                          <td align=\"left\" valign=\"top\">\n".
                      "                            <input type=\"checkbox\" name=\"ESect_$sectid[$i]\" $checked \>\n".
                      "                          </td>\n".
                      "                          <td align=\"left\" valign=\"top\">$sectname[$i]</td>\n".
                      "                        </tr>\n";
      }
   }
}

#Drop down box code needs fixing to allow you to reach input page on the DMI
#----------------------------------------------------------------*
# Subroutine  : ShowInput                                        |
# Purpose     : Get values for drop-down lists for input record  |
#               Find out which fields to show for this pub type  |
#               and write the HTML to show them                  |
# Called From : Main Routine                                     |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ShowInput
{
   if ($DEBUG == 1) {print "In ShowInput<br>\n";}
   $breadcrumbs = $breadcrumbs.
                 "      | <span class=\"obread\">Input Record</span>";
   #---------------------------------------------*
   # The user must give a publication type       |
   #---------------------------------------------*
   if ($apubtype eq "")
   {
      $ERROR = 1;
      $errm  = "Please specify the publication type you are about to enter";
   }
   #---------------------------------------------*
   # Get fields for specific publication type    |
   #---------------------------------------------*
   else
   {
      $title    = "Input New Record";
      $select   = "SELECT   PubType ".
                  "FROM     tbl_PUBS_Pubtype ".
                  "WHERE    TypeID = $apubtype";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $apubname = $ids[1];
      if ($apubtype == 3)  {$authorname = "Editor(s)";}
      else                 {$authorname = "Author(s)";}
      if ($apubtype == 2)  {$titlename  = "Title of Chapter";}
      else                 {$titlename  = "Title";}
      $select   = "SELECT   FieldName, Required, PreferredName ".
                  "FROM     tbl_PUBS_Metadata ".
                  "WHERE    TypeID = $apubtype ".
                  "ORDER BY FieldNo ASC";
      &RunQuery("$select?S");
      &ProcessRows("3A");
      $fieldtot = $#ids;
      @fields   = @ids;
      @mandat   = @val;
      @fname    = @tri;
      $o        = 0;
      for $i(1..$fieldtot)
      {
         $varname           = "A".$fields[$i];
         if ($fields[$i] eq "PublishedDate") 
         {
            $fname[$i] = "Issued Date<br /><span class=\"obread\">as dd/mm/yy</span>";
         }
         if ($mandat[$i] eq "Y")             {$manmark    = "<span class=\"greentext\">* </span>";}
         else                                {$manmark    = "";}
         $o++; $outline[$o] = "                <tr>\n";
         $o++; $outline[$o] = "                  <td width=\"5%\" valign=\"top\">&nbsp;</td>\n";
         $o++; $outline[$o] = "                  <td valign=\"top\"><b>$fname[$i]$manmark</b></td>\n";
         $o++; $outline[$o] = "                  <td colspan=\"4\">\n";
         $o++; $outline[$o] = "	                   <input name=\"$varname\" type=\"text\" size=\"100\">\n";
         if ($varname eq "AURL")
         {
            $o++; $outline[$o] = "                    <br>$pdfcomment\n";
         }
         $o++; $outline[$o] = "                  </td>\n";
         $o++; $outline[$o] = "                </tr>\n";
      }
   }
   #---------------------------------------------*
   # Get Research Theme list values              |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $select = "SELECT   ThemeID, U1Name ".
                "FROM     tbl_PUBS_Researchtheme ".
                 "ORDER BY U1Name ASC";		#Name accending
      &RunQuery("$select?S");
      &ProcessRows("2A");
      @u1id   = @ids;
      @u1name = @val;
   }
   #---------------------------------------------*
   # Get Energy Category list values             |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $select   = "SELECT   CatID, SectorName ".
                  "FROM     tbl_PUBS_Energysector ".
                  "ORDER BY CatID ";
      &RunQuery("$select?S");
      &ProcessRows("2A");
      @sectid   = @ids;
      @sectname = @val;
      $eetag = "Energy Efficiency – ";
      $sectname[1] = $eetag.$sectname[1];
      $sectname[2] = $eetag.$sectname[2];
      $sectname[3] = $eetag.$sectname[3];
      $sectname[4] = $eetag.$sectname[4];
      $ebrk1    = 15;
      for $i(1..$#sectid)
      {
         if ($i < $ebrk1)
         {
            $esectcol1 = $esectcol1.
                         "                        <tr>\n".
                         "                          <td align=\"left\" valign=\"top\">\n".
                         "                            <input type=\"checkbox\" name=\"ESect_$sectid[$i]\" />\n".
                         "                          </td>\n".
                         "                          <td align=\"left\" valign=\"top\">$sectname[$i]</td>\n".
                         "                        </tr>\n";
         }
         else
         {
            $esectcol2 = $esectcol2.
                         "                        <tr>\n".
                         "                          <td align=\"left\" valign=\"top\">\n".
                         "                            <input type=\"checkbox\" name=\"ESect_$sectid[$i]\" \>\n".
                         "                          </td>\n".
                         "                          <td align=\"left\" valign=\"top\">$sectname[$i]</td>\n".
                         "                        </tr>\n";
         }
      }
   }
}

#----------------------------------------------------------------*
# Subroutine  : ShowSearch                                       |
# Purpose     : Get values for drop-down lists for screen to     |
#               find record to be updated or deleted.            |
#               and write the HTML to show them                  |
# Called From : Main Routine                                     |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ShowSearch
{
   if ($DEBUG == 1) {print "In ShowSearch<br>\n";}
   $breadcrumbs = $breadcrumbs.
                 "      | <span class=\"obread\">Search for Record</span>";
   if ($achoose eq "Update") {$pagetitle = "Update Record";}
   if ($achoose eq "Delete") {$pagetitle = "Delete Record";}
   $select    = "SELECT DISTINCT PubDate ".
                "FROM   tbl_Roadmaps ".
                "ORDER BY PubDate ASC ";
   &RunQuery("$select?S");
   &ProcessRows("1A");
   @years     = @ids;
   $select    = "SELECT p.TypeID, p.PubType ".								#This is only needed for pubs, can be removed in future
                "FROM   tbl_PUBS_Pubtype p ".
                "WHERE  p.TypeID IN ".
                      "(SELECT a.TypeID FROM tbl_PUBS_ArticlePubtype a) ".
                "ORDER BY p.DisplayNo ASC ";
   &RunQuery("$select?S");
   &ProcessRows("2A");
   @pubid     = @ids;
   @pubname   = @val;
}

#----------------------------------------------------------------*
# Subroutine  : Update Record                                    |
# Purpose     : Validate new values and update the database      |
# Called From : InputRecord                                      |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UpdateRecord
{
   if ($DEBUG == 1) {print "In UpdateRecord<br>\n";}
   $breadcrumbs = $breadcrumbs.
                 "      | <span class=\"obread\">Update Complete</span>";
   $title     = "Update Record";
   $infoline  = "The following record has been updated";
   &Validation;
   #---------------------------------------------*
   # If the record was valid, update the         |
   # article table                               |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      # if ($apubtype == 3)
      # {
      #    $aauthors = $aauthors;
      # }
      $iauthors = &NiceVal($aauthors);
      $ipauthor = $apauthor;
      $ipauthor =~ y/a-z/A-Z/;
      $ipauthor = &NiceVal($ipauthor);
      $ititle   = &NiceVal($atitle);
      $iissue   = &NiceVal($aissue); 
      $ipages   = &NiceVal($apages);
      $ipub     = &NiceVal($apublisher);
      $iurl     = &NiceVal($aurl);
      $idoi     = &NiceVal($adoi);
      $ieditor  = &NiceVal($aeditor);
      $iukercrn = &NiceVal($aukercrn);
      $iopus    = &NiceVal($aopustitle);
      $icondate = &NiceVal($aconferencedates);
      $ivenue   = &NiceVal($avenue);
      &CreateCitation;
      $update   = "UPDATE tbl_PUBS_Article ".
                  "SET    Authors         = '".$iauthors."', ".
                         "AuthorsUC       = '".$ipauthor."', ".
                         "Title           = '".$ititle."', ".
                         "Year            = '".$ayear."', ".
                         "ISBN            = '".$aisbn."', ".
                         "Issue           = '".$iissue."', ".
                         "Pages           = '".$ipages."', ".
                         "Publisher       = '".$ipub."', ".
                         "URL             = '".$iurl."', ".
                         "DOI             = '".$idoi."', ".                         
                         "Volume          = '".$avolume."', ".
                         "Editor          = '".$ieditor."', ".
                         "UKERCReportNo   = '".$iukercrn."', ".
                         "OpusTitle       = '".$iopus."', ".
                         "ConferenceDates = '".$icondate."', ".
                         "Venue           = '".$ivenue."', ".
                         "Citation  = '".$icitation."' ".
                  "WHERE  ArticleID = $uradio";
      if ($DEBUG == 1) {print "$update<br>";}
      else             {&RunQuery("$update?U");}
   }
   #---------------------------------------------*
   # Delete and replace entries into the text    |
   # table                                       |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $delete    = "DELETE ".
                   "FROM   tbl_PUBS_Text ".
                   "WHERE  TxType = 'A' ".
                   "AND    ArticleID = $uradio ";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
   }
   if ($ERROR == 0 && $aabstract ne "")
   {
      $select = "SELECT MAX(XID) ".
                "FROM   tbl_PUBS_Text";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $maxxid = $ids[1];
      &ChopText("900]$aabstract");
      for $i(1..$#outtext)
      {
         $maxxid++;
         $indat  = "'".&NiceVal($outtext[$i])."'";
         $insert = "INSERT INTO tbl_PUBS_Text (XID, ArticleID, TxType, TxNo, TxData) ".
                   "VALUES                    ($maxxid, $uradio, 'A', $i, $indat) ";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
   }
   #---------------------------------------------*
   # Delete and replace entries into the table   |
   # that links article and research themes      |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $delete    = "DELETE ".
                   "FROM   tbl_PUBS_ArticleResearchtheme ".
                   "WHERE  ArticleID = $uradio ";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $commit = "COMMIT";
      if ($DEBUG == 1) {print "$commit<br>";}
      else             {&RunQuery("$commit?D");}
      if ($ERROR == 0)
      {
         $a1tno     = "";
         while ( ($key, $value) = each(%atheme1) )
         {
            $select = "SELECT ArticleID ".
                      "FROM   tbl_PUBS_ArticleResearchtheme ".
                      "WHERE  ArticleID = $uradio ".
                      "AND    ThemeID   = $key";
            &RunQuery("$select?S");
            &ProcessRows("1A");
            if ($#ids < 1)
            {
               $insert = "INSERT INTO tbl_PUBS_ArticleResearchtheme (ArticleID, ThemeID) ".
                         "VALUES ($uradio, $key)";
               if ($DEBUG == 1) {print "$insert<br>";}
               else             {&RunQuery("$insert?I");}
            }
            $a1tno  = $a1tno.$key.", ";
         }
         chop($a1tno); chop ($a1tno);
      }
      if ($ERROR == 0)
      {
         if ($a1tno eq "")
         {
            $insert = "INSERT INTO tbl_PUBS_ArticleResearchtheme (ArticleID, ThemeID) ".
                      "VALUES ($uradio, 99)";
            if ($DEBUG == 1) {print "$insert<br>";}
            else             {&RunQuery("$insert?I");}
         }
      }
   }
   #---------------------------------------------*
   # If appropriate, put entries into the table  |
   # that links article and tags                 |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $delete = "DELETE ".
                "FROM   tbl_PUBS_ArticleTagtype ".
                "WHERE  ArticleID = $uradio ";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $commit = "COMMIT";
      if ($DEBUG == 1) {print "$commit<br>";}
      else             {&RunQuery("$commit?D");}
   }
   if ($ERROR == 0)
   {
      if ($auwide eq "on")
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleTagtype (ArticleID, TagID) ".
                   "VALUES ($uradio, 2)";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
      if ($amedia eq "on")
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleTagtype (ArticleID, TagID) ".
                   "VALUES ($uradio, 1)";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
      }
   }
   #---------------------------------------------*
   # Delete and replace entries into the table   |
   # that links article and energy sector        |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $delete = "DELETE ".
                "FROM   tbl_PUBS_ArticleEnergycat ".
                "WHERE  ArticleID = $uradio ";
      if ($DEBUG == 1) {print "$delete<br>";}
      else             {&RunQuery("$delete?D");}
      $commit = "COMMIT";
      if ($DEBUG == 1) {print "$commit<br>";}
      else             {&RunQuery("$commit?D");}
   }
   if ($ERROR == 0)
   {
      $nsects    = "";
      for $j(1..$#newsect)
      {
         $insert = "INSERT INTO tbl_PUBS_ArticleEnergycat (ArticleID, CatID) ".
                   "VALUES ($uradio, '".$newsect[$j]."')";
         if ($DEBUG == 1) {print "$insert<br>";}
         else             {&RunQuery("$insert?I");}
         $nsects = $nsects."'".$newsect[$j]."',";
      }
      chop($nsects);
   }
   #---------------------------------------------*
   # Set up for completion screen                |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $select   = "SELECT   PubType ".
                  "FROM     tbl_PUBS_Pubtype ".
                  "WHERE    TypeID = $apubtype";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      $apubname = $ids[1];
   }
   if ($ERROR == 0 && $a1tno ne "")
   {
      $select   = "SELECT   U1Name ".
                  "FROM     tbl_PUBS_Researchtheme ".
                  "WHERE    ThemeID IN ($a1tno) ".
                  "ORDER BY U1Name ASC";

      &RunQuery("$select?S");
      &ProcessRows("1A");
      $au1themes = "";
      if ($#ids > 0)
      {
         for $i(1..$#ids)
         {
            $au1themes = $au1themes.$ids[$i]."<br />";
         }
      }
      if ($au1themes eq "") {$au1themes = "None selected<br />";}
   }
    if ($ERROR == 0)
   {
      $aothertypes = "";
      $i = 0;
      if ($amedia ne "")
      {
         $i++;
         $aotypes[$i] = "Media";
      }
      if ($auwide ne "")
      {
         $i++;
         $aotypes[$i] = "Non-Project-Specific";
      }
      for $i(1..$#aotypes)
      {
         $aothertypes = $aothertypes."$aotypes[$i]<br />";
      }
   }
   if ($aothertypes eq "") {$aothertypes = "None selected<br />";}
   if ($ERROR == 0)
   {
      $select    = "SELECT   SectorName ".
                   "FROM     tbl_PUBS_Energysector ".
                   "WHERE    CatID IN ($nsects) ".
                   "ORDER BY CatID ASC";
      &RunQuery("$select?S");
      &ProcessRows("1A");
      for $j(1..$#ids)
      {
         $asectors  = $asectors.
                      $ids[$j].
                      "<br />";
      }
   }
   $newartid     = $uradio;
   $buttonlegend = "<a href=\"$prog\?GoButton=Start Working&AChoose=Update\">".
                   "   Update another Record".
                   "</a>\n";
}

#----------------------------------------------------------------*
# Subroutine  : Validation                                       |
# Purpose     : Make sure input is valid, and all mandatory      |
#               fields for this publication type are filled      |
# Called From : InputRecord                                      |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             Validation
{
   if ($DEBUG == 1) {print "In Validation<br>\n";}
   #---------------------------------------------*
   # All records must have author, surname, title|
   # year of publication                         |
   #---------------------------------------------*
   if ($ERROR == 0 && $aauthors eq "")
   {
      $errm   = "Please give the authors' names in citation format e.g. Higgins, R.S. and Post, Q. van der<br />";
      $ERROR  = 1;
   }
   if ($ERROR == 0 && $apauthor eq "")
   {
      $errm   = "Please give the surname of the principal authors e.g. O'Hara<br />".
                "This is so we can sort document lists in alphabetical order<br />";
      $ERROR  = 1;
   }
   if ($ERROR == 0 && $atitle eq "")
   {
      if ($apubtype == 2) {$errm   = "Please give the title of the Chapter<br />";}
      else                {$errm   = "Please give the title of this document<br />";}
      $ERROR  = 1;
   }
   if ($ERROR == 0 && $ayear eq "")
   {
      $errm   = "Please give the publication year of this document<br />".
                "This is so we can sort document lists in date order<br />";
      $ERROR  = 1;
   }
   if ($ERROR == 0 && ($ayear < 2004 || $ayear > $thisyear))
   {
      $errm   = "Dates should be in the range 2004 to $thisyear<br />".
                "They should be in <i>yyyy</i> format<br />";
      $ERROR  = 1;
   }
   #---------------------------------------------*
   # Each publication type has different fields  |
   # that must be given                          |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $select    = "SELECT FieldName, PreferredName ".
                   "FROM   tbl_PUBS_Metadata ".
                   "WHERE  TypeID   = $apubtype ".
                   "AND    Required = 'Y' ";
      &RunQuery("$select?S");
      &ProcessRows("2A");
      @mands     = @ids;
      @mname     = @val;
      for $i(1..$#mands)
      {
         if ($ERROR == 0)
         {
            undef $var; undef $vname; undef $errmtext; undef $testcmd;
            $var            = $mands[$i];
            $vname          = $mname[$i];
            if ($var eq "UKERCReportNo")               {$var   = "ukercrn";}
            if ($var eq "TPAReportNo")                 {$var   = "tparn";}
            if ($var eq "PublishedDate")               {$var   = "pubdate";} 
            $errmtext       = "For this publication type, please fill in the $mname[$i] field<br>";
            $var            =~ y/A-Z/a-z/;
            $testcmd        = "if (\$a".$var." eq \"\") {\$ERROR = 1\; \$errm = \"$errmtext\"\;}";
            eval $testcmd; 
         }
      }
   }
   #---------------------------------------------*
   # Check any publication date is valid         |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      if ($apubdate ne "")
      { 
         &CheckDate($apubdate);
         $apubdate = $CheckDateReturn;
      }
   }
   #---------------------------------------------*
   # Check at least one of UKERC II research     |
   # theme, UKERC I theme, Media Output or UKERC |
   # wide has been given                         |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      $FOUND    = 0;
      if    (%atheme3)      {$FOUND = 1;}
      if    (%atheme2)      {$FOUND = 1;}
      elsif (%atheme1)      {$FOUND = 1;}
      elsif ($amedia ne "") {$FOUND = 1;} 
      elsif ($auwide ne "") {$FOUND = 1;}
      if ($FOUND == 0)
      {
         $ERROR = 1;
         $errm  = "Please choose at least one UKERC III Research Theme, UKERC II Research Theme, ".
                  "UKERC I Research Theme, ".
                  "Media tag or UKERC-Wide tag<br />";
      }
   }
}


#-------------------------------------------------------------------------------------*
# Standard Subroutines                                                                |
#-------------------------------------------------------------------------------------*

#----------------------------------------------------------------*
# Subroutine  : ChDate                                           |
# Purpose     : Gives a date in any one of several recognised    |
#               formats                                          |
# Called from :                                                  |
# Calls       : None                                             |
# Arguments   : Date to handle, two format letters               |
#               &chdate($date?x?y)                               |
#               x and y can be C E G H h I L M m N O P R S U     |
#               C : Month Name capitals   MARCH                  |
#               E : European              dd/mm/yy               |
#               G : INGRES GMT format     yyyy_mm_dd hh:mm:ss GMT|
#               H : Month Name 3 chars uc MAR                    |
#               h : Month Name 3 chars lc mar                    |
#               I : INGRES format         dd-mon-yyyy            |
#               L : Last day of month     31                     |
#               M : Month Name            March                  |
#               m : Month Name 3 chars    Mar                    |
#               N : Month Number          06                     |
#               O :                       yy/mm/dd               |
#               P : Point format          d(d).m(m).yy           |
#               R : Swedish format        yyyy-mm-dd             |
#               S : Sortable (ISO) format yyyymmdd               |
#               U : USA                   mm/dd/yy               |
#               If both x and n are specified, both can be any   |
#               of the letters, but if x is M,m or N the result  |
#               will be either the month name or its number only |
#               Defaults: date = today                           |
#                            x = S                               |
#                            y = S                               |
#               eg &chdate(??) gives today's date as yyyymmdd    |
# Return Code : None                                             |
# Change Log  : 13/09/01 LCW Added new parameter G for INGRES    |
#                            GMT format 1993_01_11 00:00:00 GMT  |
#                            NB only outputs yyyy_mm_dd
#----------------------------------------------------------------*
sub             ChDate
{
   #---------------------------------------------*
   # Declare local variables                     |
   #---------------------------------------------*
#  local        ($argstring,$indate,$format1,$format2,$ERROR,
#                $day,$month,$year,@monstr,$newbie,$m1,$m2,
#                $m3,$m4,$m5,$m6,$i);
   #---------------------------------------------*
   # Get the arguments.                          |
   #---------------------------------------------*
   $argstring    = $_[0];
   ($indate,$format1,$format2)
                 = split(/\?/,$argstring);
   #---------------------------------------------*
   # Set variables                               |
   #---------------------------------------------*
   $ERROR        = 0;
   $day          = "";
   $month        = "";
   $year         = "";
   $allowed      = "CEGHhILMmNOPRSU";
   $monstr[0]    = "January-JANUARY-Jan-JAN-jan-01-31";
   $monstr[1]    = "February-FEBRUARY-Feb-FEB-feb-02-28";
   $monstr[2]    = "March-MARCH-Mar-MAR-mar-03-31";
   $monstr[3]    = "April-APRIL-Apr-APR-apr-04-30";
   $monstr[4]    = "May-MAY-May-MAY-may-05-31";
   $monstr[5]    = "June-JUNE-Jun-JUN-jun-06-30";
   $monstr[6]    = "July-JULY-Jul-JUl-jul-07-31";
   $monstr[7]    = "August-AUGUST-Aug-AUG-aug-08-31";
   $monstr[8]    = "September-SEPTEMBER-Sep-SEP-sep-09-30";
   $monstr[9]    = "October-OCTOBER-Oct-OCT-oct-10-31";
   $monstr[10]   = "November-NOVEMBER-Nov-NOV-nov-11-30";
   $monstr[11]   = "December-DECEMBER-Dec-DEC-dec-12-31";

   #---------------------------------------------*
   # Check the arguments, setting any defaults   |
   #---------------------------------------------*
   $ERROR        = 0;
   if ($indate   eq "") {$indate   = `date +%Y%m%d`;}
   if ($format1  eq "") {$format1  = "S";}
   if ($format2  eq "") {$format2  = "S";}

   if (index($allowed,$format1) == -1) {$ERROR = 1;}
   if (index($allowed,$format2) == -1) {$ERROR = 1;}

   #---------------------------------------------*
   # Only do the work if there was no error      |
   #---------------------------------------------*
   if ($ERROR == 0)
   {
      #------------------------------------------*
      # First cut up the incoming date           |
      # C : Month Name capitals   MARCH          |
      # E : European              dd/mm/yy       |
      # G : INGRES GMT    yyyy_mm_dd hh:mm:ss GMT|
      # E : European              dd/mm/yy       |
      # h : Month Name 3 chars lc mar            |
      # I : INGRES format         dd-mon-yyyy    |
      # M : Month Name            March          |
      # m : Month Name 3 chars    Mar            |
      # N : Month Number          06             |
      # O :                       yy/mm/dd       |
      # P : Point format          d(d).m(m).yy   |
      # R : Swedish format        yyyy-mm-dd     |
      # S : Sortable (ISO) format yyyymmdd       |
      # U : USA                   mm/dd/yy       |
      #------------------------------------------*
      if (index("EGIOPRSU",$format1) > -1)
      {
         #---------------------------------------*
         # Cut up the following whole date forms |
         # E : European              dd/mm/yy    |
         # G : INGRES GMT yyyy_mm_dd hh:mm:ss GMT|
         # I : INGRES format         dd-mon-yyyy |
         # O :                       yy/mm/dd    |
         # P : Point format          d(d).m(m).yy|
         # R : Swedish format        yyyy-mm-dd  |
         # S : Sortable (ISO) format yyyymmdd    |
         # U : USA                   mm/dd/yy    |
         #---------------------------------------*
         if     ($format1 eq "E")
            { ($day,$month,$year) = split(/\//,$indate) ;}
         elsif  ($format1 eq "G")
         {
            #------------------------------------*
            # cut up yyyy_mm_dd hh:mm:ss GMT     |
            #------------------------------------*
            ($one,$two,$three)    = split(/ /,$indate);
            ($year,$month,$day)   = split(/_/,$one); 
         }
         elsif  ($format1 eq "I")
         {
            ($day,$month,$year)   = split(/\-/,$indate);
            #------------------------------------*
            # find which month string to use     |
            #------------------------------------*
            foreach $i (0 .. $#monstr)
            {
               if (index($monstr[$i],$month) > -1)
               {
                  $mstring = $monstr[$i];
                  last;
               }
            }
            #------------------------------------*
            #choose correct part of month string |
            #------------------------------------*
            ($m1,$m2,$m3,$m4,$m5,$m6,$m7) = split(/\-/,$mstring);
            $month = $m6;
         }
         elsif  ($format1 eq "O")
            { ($year,$month,$day) = split(/\//,$indate) ;}
         elsif  ($format1 eq "P")
            { ($day,$month,$year) = split(/\./,$indate) ;}
         elsif  ($format1 eq "R")
            { ($year,$month,$day) = split(/\-/,$indate); }
         elsif     ($format1 eq "S")
         {
            $year   = substr($indate,0,4);
            $month  = substr($indate,4,2);
            $day    = substr($indate,6,2);
         }
         elsif  ($format1 eq "U")
            { ($month,$day,$year) = split(/\//,$indate) ;}
         else
            {;}
         #---------------------------------------*
         # Make year four character and add      |
         # leading zeros to month and date if    |
         # needed                                |
         #---------------------------------------*
         if (length($year)  < 4)
         {
            if ($year < 50) {$year = "20".$year;}
            else            {$year = "19".$year;}
         }
         if (length($month) < 2) {$month = "0".$month   ;}
         if (length($day)   < 2) {$day   = "0".$day     ;}
      }
      else
      {
         #---------------------------------------*
         # For the remaining part-date formats   |
         # C : Month Name capitals   MARCH       |
         # H : Month Name 3 chars uc MAR         |
         # h : Month Name 3 chars lc mar         |
         # M : Month Name            March       |
         # m : Month Name 3 chars    Mar         |
         # N : Month Number          06          |
         #---------------------------------------*
         $month = $indate;
      }
      #------------------------------------------*
      # Now convert the date to the required     |
      # output using the second format given.    |
      #------------------------------------------*
      #------------------------------------------*
      # For whole-date formats, reassemble       |
      # apart from INGRES format, where a month  |
      # name rather than number is needed        |
      #------------------------------------------*
      if     ($format2 eq "E")
         {$newbie = $day."/".$month."/".$year;}
      elsif  ($format2 eq "G")
         {$newbie = $year."_".$month."_".$day;}
      elsif  ($format2 eq "O")
         {$newbie = substr($year,2,2)."/".$month."/".$day;}
      elsif  ($format2 eq "P")
         {$newbie = $day.".".$month.".".substr($year,2,2);}
      elsif  ($format2 eq "R")
         {$newbie = $year."-".$month."-".$day;}
      elsif  ($format2 eq "S")
         {$newbie = $year.$month.$day;}
      elsif  ($format2 eq "U")
         {$newbie = $month."/".$day."/".substr($year,2,2);}
      #------------------------------------------*
      # For part-date formats, convert.          |
      # Also for whole-date in INGRES format, use|
      # this code as a month name is needed      |
      #------------------------------------------*
      else
      {
         foreach $i (0 .. $#monstr)
         {
            # first find which month string is appropriate
            if (index($monstr[$i],$month) > -1)
            {
               $mstring = $monstr[$i];
               last;
            }
         }
         #---------------------------------------*
         # Split up the correct monthstring      |
         # according to the format required      |
         #---------------------------------------*
         ($m1,$m2,$m3,$m4,$m5,$m6,$m7) = split(/\-/,$mstring);
         if ($format2 eq "M") {$newbie  = $m1;}
         if ($format2 eq "C") {$newbie  = $m2;}
         if ($format2 eq "m") {$newbie  = $m3;}
         if ($format2 eq "H") {$newbie  = $m4;}
         if ($format2 eq "h") {$newbie  = $m5;}
         if ($format2 eq "N") {$newbie  = $m6;}
         if ($format2 eq "L") {$newbie  = $m7;}
         if ($format2 eq "I") {$newbie  = $day."-".$m5."-".$year;}
      }
      $chdatereturn  = $newbie;
   }
}

#----------------------------------------------------------------*
# Subroutine  : CheckDate                                        |
# Purpose     : Check dates are valid                            |
# Called from : CLFM103                                          |
# Calls       : None                                             |
# Arguments   : Date                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             CheckDate
{
   local        ($derr, $emg, $indate, $d, $m, $y,$ldom);
   $ERROR     = 0;
   $derr      = "<br />Date should be in the form dd/mm/yyyy eg 25/01/2006. <br />";
   $emg       = "";
   $date      = $_[0];
   $date =~ s/\s+$//;
   $date =~ s/^\s+//;
   ($d,$m,$y) = split(/\//,$date);
   if ($m ==1||$m==3||$m==5||$m==7||$m==8||$m==10||$m==12) {$ldom = 31;}
   elsif ($m == 2)                                         {$ldom = 29;}
   else                                                    {$ldom = 30;}
   if (length($y) < 4 && $y <  50) {$y = "20".$y;}
   if (length($y) < 4 && $y >= 50) {$y = "19".$y;}
   if    ($date   eq "")    {$emg = "Please give a date of publication.";}
   elsif ($date=~m?[A-Z]?)  {$emg = "Date $date: should be numerical.";}
   elsif (index($date,"/") < 0)
                            {$emg = "Date $date: Please use / as divider.";}
   elsif (length($date) >10){$emg = "Date $date is too long.";}
   elsif (length($d) > 2)   {$emg = "Date $date: Day $d too long.";}
   elsif (length($m) > 2)   {$emg = "Date $date: Month $m too lomg.";}
   elsif (length($y) > 4)   {$emg = "Date $date: Year $y too long.";}
   elsif (length($y) < 4)   {$emg = "Date $date: Year $y too short.";}
   elsif ($m         < 1)   {$emg = "Date $date: month cannot be less than 1.";}
   elsif ($m         >12)   {$emg = "Date $date: month cannot be more than 12.";}
   elsif ($d         < 1)   {$emg = "Date $date: day cannot be less than 1.";}
   elsif ($d     > $ldom)   {$emg = "Date $date: There are not that many days in that month.";}
   elsif ($y     < 2004 )   {$emg = "Date $date: year must be more than 2003.";}
   elsif ($y     > 2016 )   {$emg = "Date $date: year must be less than 2017.";}
   else {;}
   if ($emg ne "")
   {
      $ERROR = 1;
      $errm  = $emg.$derr;
   }
   else
   {
      if (length($d) < 2) {$d = "0".$d;}
      if (length($m) < 2) {$m = "0".$m;}
      $CheckDateReturn = $d."/".$m."/".$y;
   }
}

#----------------------------------------------------------------*
# Subroutine  : ChopText                                         |
# Purpose     : Chop up incoming text string into arrays @outtext|
#               and @outtxno                                     |
# Called From : main routine                                     |
# Calls       :                                                  |
# Arguments   : Length of segments and string to chop            |
#               e.g. &ChopText("500]$string")                    |
# Return Code : @choppings                                       |
#----------------------------------------------------------------*
sub             ChopText
{
   local        ($string, $len, $i);
   undef @outtext; 
   undef $string;
   undef $len;
   $i         = 0;
   $argstring = $_[0];
   ($len, $string) 
              = split(/\]/,$argstring);
   $len--;
   until (length($string) <=0)
   {
      $i++;
      $outtext[$i] = substr($string,0,$len);
      $string      = substr($string,$len);
   }
}


#----------------------------------------------------------------*
# Subroutine  : ErrmShow                                         |
# Purpose     : Write out any error message in HTML format.      |
# Called From : gen_body                                         |
# Calls       :                                                  |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ErrmShow
{
   $errmtype    = $_[0];
   if ($errmtype eq "CONNECT") 
   {
      $errmline = "Could not connect to $sid with those credentials";
   }
   if ($errmtype eq "PREPARE") 
   {
      $errmline = "Could not run $sqlstmt";
   }
   if (substr($errm,11,6) eq "unique") 
   {
      $errmline = "You tried to enter a value that is already in the database.";
   }
   else
   {
      $errmline = $errm;
   }
   $errmline    = $errmline.
                  "<br>Use the Back button on the browser to return to the previous page ".
                  "and correct the data.";
&ShowHeader;
print <<EOM
<p align="center"><strong>SORRY!</strong></p>
<p align="center">I cannot do as you wish.</p>
<p align="center">The error message from the system was:</p>
<p align="center">
<strong>$errmline</strong>
</p>
EOM
;;

   &ShowFooter;
   exit;
}

#----------------------------------------------------------------*
# Subroutine  : NiceVal                                          |
# Purpose     : Process text fields for loading into Oracle.     |
#               Single quotes are doubled, and ampersands        |
#               replaced with &'||' as this is the only way to   |
#               get them to load.                                |
# Called from : Main routine                                     |
# Calls       : None                                             |
# Arguments   : Value to have commas inserted into               |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub NiceVal
{
   $argstring     =  $_[0];
   # Remove anything that is not in the approved list of characters
   $argstring     !~ s/[^[:ascii:]]//g;
   $argstring     =~ tr/\r//d;
   $argstring     =~ s/\?/&#063\;/g;
   $argstring     =~ s/\@/&#064\;/g;   $argstring    =~ s/\'/\'\'/g;
   $argstring     =~ s/\&/\&\'\|\|\'/g;
   $argstring     =~ s/\\r//g;
   $argstring     =~ s/\\n//g;
   $nicevalreturn = $argstring;
}

#----------------------------------------------------------------*
# Subroutine  : paraget                                          |
# Purpose     : Get all input parameters                         |
# Called from : Main routine                                     |
# Calls       : None                                             |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ParaGet 
{
   $action     = param("GoButton");
   $scrnfr     = param("ScrnFrom"); 
   $scrnto     = param("ScrnTo"); 
   $FIRST      = param("FIRST");
   $dmname     = param("DMName");
   $achoose    = param("AChoose");
   $apubtype   = param("APubType");
   $aauthors   = param("AAuthors");
   $apauthor   = param("APAuthor"); 
   $atitle     = param("ATitle"); 
   $adoi       = param("ADOI");
   $ayear      = param("AYear");
   $aisbn      = param("AISBN"); 
   $apublisher = param("APublisher"); 
   $aurl       = param("AURL"); 
   $aeditor    = param("AEditor"); 
   $apages     = param("APages"); 
   $ajournal   = param("AJournal"); 
   $avolume    = param("AVolume"); 
   $aissue     = param("AIssue"); 
   $aabstract  = param("AAbstract");
   $aopustitle = param("AOpusTitle"); 
   $aconferencedates
               = param("AConferenceDates");
   $avenue     = param("AVenue");
   $apubdate   = param("APublishedDate"); 
   $aukercrn   = param("AUKERCReportNo"); 
   $atparn     = param("ATPAReportNo"); 
   $amedia     = param("AMedia"); 
   $auwide     = param("AUWide"); 
   $uartid     = param("UArtID");
   $uauthor    = param("UAuthor");
   $utitle     = param("UTitle");
   $upubtype   = param("UPubType");
   $uyear      = param("UYear");
   $uradio     = param("URadio");
   $cgi = new CGI;
   for $key ( $cgi->param() ) 
   {
      $input{$key} = $cgi->param($key);
   }
   $k          = 0;
   while ( ($key, $value) = each(%input) )
   {
      if (substr($key,0,3) eq "AU3" || substr($key,0,5) eq "AUIII")
      {
         ($junk, $ecn)  = split(/_/, $key);
         $atheme3{$ecn} = "on";
      }
      if (substr($key,0,3) eq "AU2" || substr($key,0,4) eq "AUII")
      {
         ($junk, $ecn)  = split(/_/, $key);
         $atheme2{$ecn} = "on"; 
      }
      if (substr($key,0,3) eq "AU1" || substr($key,0,4) eq "AUI_")
      {
         ($junk, $ecn)  = split(/_/, $key);
         $atheme1{$ecn} = "on"; 
      }
      if (substr($key,0,5) eq "ESect")
      {
         $k++;
         ($junk, $newsect[$k])   = split(/_/, $key);
      }
   }
}

#----------------------------------------------------------------*
# Subroutine  : ProcessRows                                      |
# Purpose     : Convert the rows retrieved from SQL to variables |
# Called From : gen_body                                         |
# Calls       :                                                  |
# Arguments   : An indicator to say how to parse the records     |
#               found eg &processrows("C")                       |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ProcessRows
{
   local        ($i, $type);
   undef @ids; undef @val; undef @tri; undef @qat;
   $type      = $_[0];
   for $i(1..$#outrow)
   {
      #------------------------------------------*
      # 1A: One Field Parsing into one array     |
      #------------------------------------------*
      if ($type eq '1A')
      {
         $outrow[$i]   =~ s/  \s+/ /g;
         ($ids[$i]) =  split(/\]/,$outrow[$i]);
         $ids[$i]      =~ s/^\s+//;
         $ids[$i]      =~ s/\s+$//;
      }
      #------------------------------------------*
      # 2A: Two Field Parsing into two arrays    |
      #------------------------------------------*
      if ($type eq '2A')
      {
         $outrow[$i]   =~ s/  \s+/ /g;
         ($ids[$i], $val[$i]) =  split(/\]/,$outrow[$i]);
         $ids[$i]      =~ s/^\s+//;
         $ids[$i]      =~ s/\s+$//;
         $val[$i]      =~ s/^\s+//;
         $val[$i]      =~ s/\s+$//;
      }
      #------------------------------------------*
      # 3A: Three Field Parsing into three arrays|
      #------------------------------------------*
      if ($type eq '3A')
      {
         $outrow[$i]   =~ s/  \s+/ /g;
         $outrow[$i]   =~ s/ \& / &amp; /g;
         ($ids[$i], $val[$i], $tri[$i]) =  split(/\]/,$outrow[$i]);
         $ids[$i]      =~ s/^\s+//;
         $ids[$i]      =~ s/\s+$//;
         $val[$i]      =~ s/^\s+//;
         $val[$i]      =~ s/\s+$//;
         $tri[$i]      =~ s/^\s+//;
         $tri[$i]      =~ s/\s+$//;
      }
      #------------------------------------------*
      # 4A: Four Field Parsing into four arrays  |
      #------------------------------------------*
      if ($type eq '4A')
      {
         $outrow[$i]   =~ s/  \s+/ /g;
         $outrow[$i]   =~ s/ \& / &amp; /g;
         ($ids[$i], $val[$i], $tri[$i], $qat[$i]) =  split(/\]/,$outrow[$i]);
         $ids[$i]      =~ s/^\s+//;
         $ids[$i]      =~ s/\s+$//;
         $val[$i]      =~ s/^\s+//;
         $val[$i]      =~ s/\s+$//;
         $tri[$i]      =~ s/^\s+//;
         $tri[$i]      =~ s/\s+$//;
         $qat[$i]      =~ s/^\s+//;
         $qat[$i]      =~ s/\s+$//;
      }
      #------------------------------------------*
      # 5A: Five Field Parsing into five arrays  |
      #------------------------------------------*
      if ($type eq '5A')
      {
         $outrow[$i]   =~ s/  \s+/ /g;
         $outrow[$i]   =~ s/ \& / &amp; /g;
         ($ids[$i], $val[$i], $tri[$i], $qat[$i], $qin[$i]) =  split(/\]/,$outrow[$i]);
         $ids[$i]      =~ s/^\s+//;
         $ids[$i]      =~ s/\s+$//;
         $val[$i]      =~ s/^\s+//;
         $val[$i]      =~ s/\s+$//;
         $tri[$i]      =~ s/^\s+//;
         $tri[$i]      =~ s/\s+$//;
         $qat[$i]      =~ s/^\s+//;
         $qat[$i]      =~ s/\s+$//;
         $qin[$i]      =~ s/^\s+//;
         $qin[$i]      =~ s/\s+$//;
      }
   }
}

#----------------------------------------------------------------*
# Subroutine  : RunQuery                                         |
# Purpose     : Run the created SELECT statement in INGRES       |
# Called From : gen_body                                         |
# Calls       :                                                  |
# Arguments   : The statement to be run, and an indicator to say |
#               how to parse the records found eg                |
#               &runquery ("$select?C) for Course parsing        |
#               &runquery ("$select?T) for Structure parsing     |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             RunQuery
{
   local        ($i, $type, $array_ref, $row, @f);
   undef        (@outrow);
   $sqlstmt = $_[0];
   ($sqlstmt,$type) = split(/\?/,$sqlstmt);
   #---------------------------------------------*
   # Connect to the correct database             |
   #---------------------------------------------*
   $userpw =~ s/\s+$//;
#print "DEBUG :: RunQuery<br>Connecting Pg:dbname=$sid, $username, $userpw<br>\n";
   $dbh = DBI->connect("dbi:Pg:dbname=$sid", $username, $userpw) or &ErrmShow("CONNECT");
   #---------------------------------------------*
   # Processing for Selects.                     |
   #---------------------------------------------*
   if ($type eq "S")
   {
      #------------------------------------------*
      # Prepare and execute the statement        |
      #------------------------------------------*
      $sth = $dbh->prepare( " $sqlstmt " ) or &ErrmShow("PREPARE");
      $genrc   = $dbh->err();
      $errmstr = $dbh->errstr();
      $errcode = substr($errmstr,0,8);
      $errm    = $errcode;
      $sth->execute();
      #------------------------------------------*
      # Fetch all the data into a Perl data      |
      # structure                                |
      #------------------------------------------*
      $array_ref = $sth->fetchall_arrayref();
      #------------------------------------------*
      # Traverse the data structure and dump each|
      # piece of data out for each row in the    |
      # returned array reference                 |
      #------------------------------------------*
      $i = 0;
      foreach  $row (@$array_ref)
      {
         $i++;
         #---------------------------------------*
         # Split the row up and put back together|
         # with delimiter for later processing   |
         #---------------------------------------*
         (@fields) = @$row;
         for $j(0..$#fields)
         {
            $outrow[$i] = $outrow[$i].$fields[$j]."]";
         }
         chop ($outrow[$i]);
      }
   }
   #---------------------------------------------*
   # Processing for Inserts, Updates or Deletes  |
   #---------------------------------------------*
   else
   {
      $rows    = $dbh->do( $sqlstmt );
      $genrc   = $dbh->err();
      $errmstr = $dbh->errstr();
      $errcode = substr($errmstr,0,8);
      $errm    = $errmstr;
      $stt     = $dbh->state();
      # Attempted to insert duplicate record
      if    ($errcode eq 'E_US1194')
      {
         $errm = "DUP";
         $ERROR = 1;
      }
      # Cannot execute due to DB Reorganization
      elsif ($errcode eq 'E_US1265')
      {
         $ERROR   = 1;
         $DBREORG = 1;
      }
      elsif ($errcode eq 'E_CO0015')
      {
         $ERROR = 0;
      }
      elsif ($errcode eq 'E_US0845')
      {
         $ERROR   = 0;
         $NOTAB   = 1;
      }
   }
   #---------------------------------------------*
   # Any error code other than none or the       |
   # successful completion one is a 'real' error |
   #---------------------------------------------*
   if ($errcode ne '' && $errcode ne "ORA-0000")
   {
      $ERROR = 1;
      $errm  = $errmstr;
   }
   else
   {
      $ERROR = 0;
   }
   #---------------------------------------------*
   # Disconnect from the database                |
   #---------------------------------------------*
   $dbh->disconnect();
}


#----------------------------------------------------------------*
# Subroutines for displaying web pages                           |
#----------------------------------------------------------------*

#----------------------------------------------------------------*
# Subroutine  : SetHidden                                        |
# Purpose     : Set up the hidden parameters for a page          |
# Called from : All CLFMxxx subroutines                          |
# Calls       : None                                             |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             SetHidden 
{  
   @HPars = ("ScrnFrom","ScrnTo", "DMName", "APubType", "AChoose", "URadio", 
             "UArtID", "UAuthor", "UTitle", "UPubType", "UYear");
   @hpars = ($scrnfr   ,$scrnto , $dmname,  $apubtype,  $achoose , $uradio,
             $uartid, $uauthor, $utitle, $upubtype, $uyear);
   for $p(0 .. $#hpars)
   {
      if ($hpars[$p] ne "")
      {
        print "<input type=\"hidden\" name=\"$HPars[$p]\" value=\"$hpars[$p]\">\n";
      }
   }
}

#----------------------------------------------------------------*
# Subroutine  : ShowFooter                                       |
# Purpose     : Show Page Footer                                 |
# Called from : Main routine                                     |
# Calls       : &Prt                                             |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ShowFooter
{
   print <<EOM

<!-- End of page text -->

<!-- Start of footer -->
<div class="w-section footer">
  <div id="screennumber" class="screenno">
    <div align="right"> <a href="../../xyz.html"> <img src="../../Images/arrow.png" height="9" width="9"> </a> $scrno<br>
      Build of $last_updated
    </div>
  </div>
</div>
<!-- [if lte IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js"></script><![endif]--> 
<script type="text/javascript" src="js/script.js"></script> 
<script type="text/javascript" src="js/webflow.js"></script>
</body>
</html>
EOM
;;

}

#----------------------------------------------------------------*
# Subroutine  : ShowHeader                                       |
# Purpose     : Show Page Header                                 |
# Called from : Main routine                                     |
# Calls       : &Prt                                             |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             ShowHeader
{
   print "Content-type: text/html\n\n";
   print <<EOM
                        
<html>
<!DOCTYPE html>
<head>
  <meta content="text/html; charset=utf-8" http-equiv="content-type">
  <title>$pagetitle</title>
  <meta http-equiv="X-UA-Compatible" content="IE=8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="$stylesheet" rel="stylesheet" type="text/css" />
;
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
<script>
    WebFont.load({
      google: {
        families: ["Open Sans:300,300italic,400,400italic,600,600italic,700,700italic,800,800italic","Roboto:300,regular,500"]
      }
    });
  </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/modernizr.js"></script>
</head>
<body>
<div class="w-nav navigation-bar" data-collapse="medium" data-animation="default" data-duration="400" data-contain="1">
  <div class="w-container"> 
    <a class="w-nav-brand w-clearfix brand-link" href="http://www.ukerc.ac.uk"> 
      $ukerclogo
    </a>
  </div>
</div>
<!-- Page Header -->
<div class="w-section hero-section centered">
  <div class="w-container">
    <h1 class="hero-heading">UKERC ENERGY DATA CENTRE </h1>
  </div>
</div>
</div>

<!-- End of Header --> 
<!-- Start of page text -->

  <div class="w-row">
    <div class="w-col w-col-12">
      <div>
        <h3>$interface</h3>
        <div align="center">

EOM
;;

}

#-------------------------------------------------------------------------------------*
# Page Display Subroutines                                                            |
#-------------------------------------------------------------------------------------*
#----------------------------------------------------------------*
# Subroutine  : UCAT310                                          |
# Purpose     : Show the Input Record Page                       |
# Called from : Main Routine                                     |
# Calls       : &Prt, &SetHidden, &ShowHeader, &Show Footer,     |
#               &QueryRun,                                       |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UCAT310 
{ 
   $scrno     = "ERC721";
   $scrnct    = 0;
   print "          <form action=\"$prog\" method=\"post\">\n";
   &SetHidden;
   print <<EOM
          <table class="boundary-box" cellpadding="2" cellspacing="2">
            <tr>
              <td colspan="8" align="left" valign="top">
                <h5 align="left">UKERC Roadmaps Catalogue</h5>
                $breadcrumbs
                <hr color="#E8E8E8" />
              </td>
            </tr>
            <tr>
              <td colspan="6" align="left" valign="top">
                <h6>Input Metatdata Record for New $apubname</h6>
              </td>
            </tr>
            <tr>
              <td colspan="6" align="left" valign="top">
                Please enter the details of the new record 
                (<span class="greentext">* Mandatory Field</span>) <br>
                <a href="$markpage" title="Opens markup advice in new window" target="_blank">HTML Markup</a>
              </td>
            </tr>
            <tr>
	      <td colspan="2" valign="top"><b>$authorname<span class="greentext">* </span></b></td>
	      <td colspan="4">
	          <input name="AAuthors" type="text" size="100" maxlength="500">
	      </td>
            </tr>
            <tr>
	      <td colspan="2" valign="top">&nbsp;</td>
	      <td colspan="4" class="obread">
                eg Jones, D.L, Wilson A. and Simmons, Q.
                (as you wish them to appear in the formal citation)
              </td>
            </tr>
            <tr>
              <td colspan="2" valign="top"><b>Surname(s) of $authorname<span class="greentext">* </span></b></td>
	      <td colspan="4">
	        <input name="APAuthor" type="text" size="100">
	      </td>
            </tr>
            <tr>
              <td colspan="2" valign="top">&nbsp;</td>
	      <td colspan="4" class="obread">eg Jones Wilson Simmons. This is needed in order to list documents by author</td>
            </tr>
            <tr>
              <td colspan="2" valign="top"><b>$titlename<span class="greentext">* </span></b></td>
	      <td colspan="4">
	        <textarea name="ATitle" cols="70" rows="5" maxlength="10000"></textarea>
	        <br />
	        <span class="obread">All special characters such as quotes and question marks need to be
	        entered as HTML markup</span>
              </td>
            </tr>
            <tr>
              <td colspan="2" valign="top"><b>Publication Year<span class="greentext">* </span></b></td>
              <td colspan="4">
	        <input name="AYear" type="text" size="4" maxlength="4">
	        <span class="obread">eg 2006</span>
              </td>
            </tr>
            <tr>
               <td colspan="2" valign="top" class="dark"><b>$apubname:</b></td>
              <td colspan="4">&nbsp;</td>
	      </tr>

EOM
;;

   for $o(1..$#outline)
   {
      print "           ".$outline[$o]."\n";
   }

   print <<EOM
            <tr>
              <td colspan="2" valign="top"><b>DOI</b></td>
              <td colspan="4">
	        <input name="ADOI" type="text" size="100">
              </td>
            </tr>
            <tr>
              <td colspan="2" valign="top"><b>Abstract<span class="greentext">* </span></b></td>
              <td colspan="4">
	        <textarea name="AAbstract" cols="70" rows="5"></textarea>
	        <br />
	        <span class="obread">All special characters such as quotes need to be
	        entered as HTML markup<br>
                The abstract can be as long as you like</span>
              </td>
            </tr>
            <tr>
	        <td colspan="6" valign="top">
                  <hr color="#E8E8E8" />
	        </td>
	      </tr>
	    <tr>
	      <td colspan="2" valign="top"><h6>Classification</h6></td>
	      <td colspan="4">&nbsp;</td>
            </tr>
            <tr>
	      <td colspan="2" valign="top">&nbsp;</td>
	      <td colspan="4" valign="top">
                 <span class="obread">
                    Tick at least one of the following; please tick all that apply:
                 </span>
              </td>
            </tr>
            <tr>

EOM
;;

   for $i(1..$#u1id)
   {
      if ($i == 1) {$col1 = "<td colspan=\"2\" rowspan=\"$#u1id\" valign=\"top\">".
                            "<b>Research Theme</b></td>";}
      else         {$col1 = "";}
      print "            <tr>\n";
      print "              $col1\n";
      print "              <td valign=\"top\" width=\"5%\">\n";
      print "                <input name=\"AU1_$u1id[$i]\" type=\"checkbox\" value=\"on\">\n";
      print "              </td>\n";
      print "              <td valign=\"top\">$u1name[$i]</td>\n";
      print "              <td valign=\"top\">&nbsp;</td>\n";
      print "              <td valign=\"top\">&nbsp;</td>\n";
      print "            </tr>\n";
   }

   print <<EOM
	    <tr>
              <td colspan="2" valign="top"><b>Non-Project</b></td>
	        <td>
	          <input name="AUWide" type="checkbox" value="on">
              </td>
	      <td colspan="4">
	        <span class="obread">eg Consultations</span>
              </td>
            </tr>
            <tr>
	      <td colspan="2" valign="top"><b>Media Output</b></td>
	      <td colspan="4">
	        <input name="AMedia" type="checkbox" value="on">
              </td>
            </tr>
            <tr>
	      <td colspan="2" valign="top"><b>Energy Sector</b></td>
	      <td colspan="4">
	        <span class="obread">Tick at least one of the following; please tick all that apply:</span>
              </td>
            </tr>
            <tr>
	      <td colspan="6" valign="top" class="stripe">
                <table width="100%" border="0" cellpadding="0" cellspacing="0">
                  <td align="left" valign="top" width="50%">
                     <table width="100%" border="0" cellpadding="2" cellspacing="2">
                        $esectcol1
                     </table>
                  </td>
                  <td align="left" valign="top" width="50%">
                    <table width="95%" border="0" cellpadding="2" cellspacing="2">
                      $esectcol2
                     </table>
                  </td>
                </table>
              </td>
            </tr>
            <tr>
              <td colspan="6" align="left" valign="top">
              <input type="submit" name="GoButton" value="Submit Record">
              </td>
            </tr>
           <tr>
             <td colspan="6">
               <hr color="#E8E8E8" />
             </td>
           </tr>
           <tr>
             <td colspan="6">
               <a href="$returnmenu?DMName=$tdmname">
                 Return to Data Managers Menu
               </a>
               <br>
               <a href="$logout">
                 Log out of Data Managers Interface
               </a>
             </td>
           </tr>
         </table>
       </form>
EOM
;;
}

#----------------------------------------------------------------*
# Subroutine  : UCAT319                                          |
# Purpose     : Show the Completion Page                         |
# Called from : Main Routine                                     |
# Calls       : &Prt, &SetHidden, &ShowHeader, &Show Footer,     |
#               &QueryRun,                                       |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UCAT319 
{ 
   $scrno     = "ERC722";
   $scrnct    = 0; 
   print <<EOM
          <table class="boundary-box" cellpadding="2" cellspacing="2">
            <tr>
              <td colspan="2" align="left" valign="top">
                <h5 align="left">UKERC Roadmaps Catalogue</h5>
                $breadcrumbs
                <hr color="#E8E8E8" />
              </td>
            </tr>
            <tr>
              <td colspan="6" align="left" valign="top">
                <h6>Metatdata Record Change Completed</h6>
                The change is live in INT immediately, and will be live on EXT ovenight
              </td>
            </tr>
            <tr>
              <td colspan="2" align="left" valign="top">
              $infoline
              </td>
            </tr>
            <tr>
              <td colspan="2" align="left" valign="top">
                $acitation<br>
                Available from:
	        <a href="$aurl" class=text">$aurl</a>
              </td>
            </tr>
            <tr>
              <td><b>Article ID</b></td>
              <td>$newartid</td>
            </tr>
            <tr>
              <td valign="top"><b>Energy Sectors</b></td>
              <td>$asectors</td>
            </tr>
            <tr>
              <td><b>Publication Type</b></td>
              <td>$apubname</td>
            </tr>
            <tr>
              <td valign="top"><b>Research Themes</b></td>
              <td valign="top">$au1themes</td>
            </tr>
            <tr>
              <td valign="top"><b>Other Tags</b></td>
              <td valign="top">$aothertypes</td>
            </tr>
            <tr>
              <td valign="top"><b>Abstract</b></td>
              <td valign="top">$aabstract</td>
            </tr>
            <tr>
              <td valign="top">
	        $buttonlegend
             </td>
           </tr>
           <tr>
             <td colspan="2">
               <hr color="#E8E8E8" />
             </td>
           </tr>
           <tr>
             <td colspan="2">
               <a href="$returnmenu?DMName=$tdmname">
                 Return to Data Managers Menu
               </a>
               <br>
               <a href="$logout">
                 Log out of Data Managers Interface
               </a>
             </td>
           </tr>
         </table>
       </form>
EOM
;;
}

#----------------------------------------------------------------*
# Subroutine  : UCAT320                                          |
# Purpose     : Show the Search screen                           |
# Called from : Main Routine                                     |
# Calls       : &Prt, &SetHidden, &ShowHeader, &Show Footer,     |
#               &QueryRun,                                       |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UCAT320		#rename roadmap100 and give screen number
{ 
   $scrno     = "ERC723";
   $scrnct    = 0; 
   print "          <form action=\"$prog\" method=\"get\">\n";
   &SetHidden;
print <<EOM
          <table class="boundary-box" cellpadding="2" cellspacing="2">
            <tr>
              <td colspan="3" align="left" valign="top">
                <h5 align="left">UKERC Roadmaps Catalogue</h5>
                $breadcrumbs
                <hr color="#E8E8E8" />
              </td>
            </tr>
            <tr>
              <td colspan="6" align="left" valign="top">
                <h6>Search for Metatdata Record</h6>
              </td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top">
                You can search for articles in the catalogue using any combination of the items below
              </td>
            </tr>
            <tr>
              <td align="left" valign="top"><b>Article ID</b></td>
              <td align="left" valign="top">
                <input type="text" name="UArtID">
              </td>
              <td align="left" valign="top">
                <span class="obread">Each publication has a unique Article ID</span>
              </td>
            </tr>
            <tr>
              <td align="left" valign="top"><b>Author</b></td>
              <td align="left" valign="top">
                <input type="text" name="UAuthor">
              </td>
              <td align="left" valign="top">
                <span class="obread">Jones</span> <span class="greentext">or</span><br>
                <span class="obread">Jones, J</span> <span class="greentext">or</span><br>
                <span class="obread">Jones Smith</span>
              </td>
            </tr>
            <tr>
              <td align="left" valign="top"><b>Title</b></td>
              <td align="left" valign="top">
                <input name="UTitle" type="text" size="100">
              </td>
              <td align="left" valign="top">
                <span class="obread">wind</span> <span class="greentext">or</span><br>
                <span class="obread">wind and energy</span> <span class="greentext">or</span><br>
                <span class="obread">wind not wave</span>
              </td>
            </tr>
            <tr>
              <td align="left" valign="top"><b>Publication Type</b></td>
              <td colspan="2" align="left" valign="top">
                <select name="UPubType">
                  <option value="0" selected>No Publication Type selected</option>
EOM
;;
   for $i(1..$#pubid)
   {
      print "                  <option value=\"$pubid[$i]\">$pubname[$i]</option>\n";
   }
   print <<EOM
                </select>
              </td>
            </tr>
            <tr>
              <td align="left" valign="top"><b>Year of Publication</b></td>
              <td align="left" valign="top" colspan="2">
                <select name="UYear">
                  <option value="0" selected>No Year selected</option>
EOM
;;

   for $i(1..$#years)
   {
      print "                  <option value=\"$years[$i]\">$years[$i]</option>\n";
   }

   print <<EOM

                </select>
              </td>
            </tr>
            <tr>
              <td colspan="3">
              <input name="GoButton" type="submit" value="Search for Publications">
             </td>
            </tr>
            <tr>
             <td colspan="3">
               <hr color="#E8E8E8" />
             </td>
            </tr>
            <tr>
             <td colspan="3">
               <a href="$returnmenu?DMName=$tdmname">
                 Return to Data Managers Menu
               </a>
               <br>
               <a href="$logout">
                 Log out of Data Managers Interface
               </a>
             </td>
           </tr>
         </table>
       </form>
EOM
;;
}

#----------------------------------------------------------------*
# Subroutine  : UCAT321                                          |
# Purpose     : Show the results from the search                 |
# Called from : Main Routine                                     |
# Calls       : &Prt, &SetHidden, &ShowHeader, &Show Footer,     |
#               &QueryRun,                                       |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UCAT321
{ 
   $scrno     = "ERC724";
   $scrnct    = 0; 
   print "          <form action=\"$prog\" method=\"get\">\n";
   &SetHidden;
print <<EOM
          <table class="boundary-box" cellpadding="2" cellspacing="2">
            <tr>
              <td colspan="3" align="left" valign="top">
                <h5 align="left">UKERC Roadmaps Catalogue</h5>
                $breadcrumbs
                <hr color="#E8E8E8" />
              </td>
            </tr>
            <tr>
              <td colspan="6" align="left" valign="top">
                <h6>Metatdata Records Found</h6>
              </td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top">
                $counttext records were found from your search; please choose one to work with
              </td>
            </tr>
EOM
;;
   for $i(1..$#artid)
   {
      print "          <tr>\n";
      print "            <td valign=\"top\" width=\"5%\">\n";
      print "              <input type=\"radio\" name=\"URadio\" value=\"$artid[$i]\">\n";
      print "            </td>\n";
      print "            <td valign=\"top\">\n";
      print "              <b>$artid[$i]</b>\n";
      print "            </td>\n";
      print "            <td valign=\"top\">\n";
      print "              $citation[$i]\n";
      print "            </td>\n";
      print "          </tr>\n";
   }
print <<EOM
            <tr>
              <td colspan="3" align="left" valign="top">
                <input name="GoButton" type="submit" value="Work with this Publication">
              </td>
            </tr>
            <tr>
             <td colspan="3">
               <hr color="#E8E8E8" />
             </td>
            </tr>
            <tr>
             <td colspan="3">
               <a href="$returnmenu?DMName=$tdmname">
                 Return to Data Managers Menu
               </a>
               <br>
               <a href="$logout">
                 Log out of Data Managers Interface
               </a>
             </td>
           </tr>
         </table>
       </form>
EOM
;;
}

#----------------------------------------------------------------*
# Subroutine  : UCAT322                                          |
# Purpose     : Show the Update Details Page                     |
# Called from : Main Routine                                     |
# Calls       : &Prt, &SetHidden, &ShowHeader, &Show Footer,     |
#               &QueryRun,                                       |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UCAT322 
{ 
   $scrno     = "ERC725";
   $scrnct    = 0; 
   print "          <form action=\"$prog\" method=\"post\">\n";
   &SetHidden;
print <<EOM
          <table class="boundary-box" cellpadding="2" cellspacing="2">
            <tr>
              <td colspan="3" align="left" valign="top">
                <h5 align="left">UKERC Roadmaps Catalogue</h5>
                $breadcrumbs
                <hr color="#E8E8E8" />
              </td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top">
                <h6>Edit Metatdata Record - Update Record</h6>
              </td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top">
	        Please overtype with changes
               (<span class="greentext">* Mandatory Field</span>)<br>
                <a href="$markpage" title="Opens markup advice in new window" target="_blank">HTML Markup</a>
              </td>
            </tr>      
	    <tr>
	      <td><b>Article ID</b></td>
	      <td colspan="2">$uradio</td>
            </tr>
	    <tr>
	      <td valign="top"><b>Authors<span class="greentext">* </span></b></td>
	      <td colspan="2">
                Was: <span class="greentext">$oauthors</span><br> <br>
	        New: <input name="AAuthors" type="text" value="$oauthors" size="100" maxlength="500"> <br>
                <span class="obread">eg Jones, D.L, Wilson A. and Simmons, Q.</span>
              </td>
	    </tr>
	    <tr>
	      <td valign="top"><b>Surname of Author(s)<span class="greentext">* </span></b></td>
	      <td colspan="2">
                 Was: <span class="greentext">$oauthorsuc </span><br><br>
	         New: <input name="APAuthor" type="text" value="$oauthorsuc" size="100"><br>
                <span class="obread">eg Jones. This is needed in order to list documents by author</span>
              </td>
            </tr>
	    <tr>
	      <td valign="top"><b>Title<span class="greentext">* </span></b></td>
	      <td colspan="2" valign="top">
                Was: <span class="greentext">$otitle</span><br><br>
                New: <textarea name="ATitle" id="ATitle" cols="70" rows="5">$otitle</textarea>
              </td>
            </tr>
	    <tr>
	      <td valign="top"><b>Publication Year<span class="greentext">* </span></b></td>
	      <td colspan="2">
                Was: <span class="greentext">$oyear</span> <br><br>
                Now: <input name="AYear" type="text" value="$oyear" size="4"   ><br>
                <span class="obread">eg 2003</span>
              </td>
	    </tr>
	    <tr>
	      <td valign="top"><b>DOI</b></td>
	      <td colspan="2">
                Was: <span class="greentext">$odoi</span> <br><br>
                Now: <input name="ADOI" type="text" value="$odoi" size="70">
              </td>
	    </tr>

EOM
;;

   for $o(1..$#outline)
   {
      print "	    ".$outline[$o]."\n";
   }

   print <<EOM

	    <tr>
	      <td valign="top"><b>Abstract</b></td>
	      <td colspan="2">
                Was: <span class="greentext">$oabstract</span> <br><br>
                Now: <textarea name="AAbstract" id="AAbstract" cols="70" rows="5">$oabstract</textarea>
	      </td>
	    </tr>
            <tr>
	      <td colspan="3" valign="top">
                <hr color="#E8E8E8" />
	      </td>
	    </tr>
            <tr>
	      <td colspan="3" valign="top"><h6>Classification</h6></td>
	      </tr>
	    <tr>
	      <td colspan="3" valign="top">
                Tick at least one of the following; please tick all that apply:
              </td>
	    </tr>
EOM
;;

   for $i(1..$#theme1id)
   {
      print "            <tr>\n";
      if ($i == 1)
      {
         print "              <td valign=\"top\" rowspan=\"$#theme1\" >\n";
         print "                <b>Research Theme</b>\n";
         print "              </td>\n";
      }
      print "              <td valign=\"top\">\n";
      if ($otheme1[$i] ne "") {$checked = "checked";}
      else                    {$checked = "";}
      print "                <input name=\"AUI_$theme1id[$i]\" type=\"checkbox\" value=\"on\" $checked>\n";
      print "              </td>\n";
      print "              <td valign=\"top\">$theme1[$i]</td>\n";
      print "              <td>&nbsp;</td>\n";
      print "            </tr>\n";
   }   

   print <<EOM

	    <tr>
	      <td valign=\"top\"><b>Non-Project-Specific</b></td>
	      <td colspan="2">
                $ononprojstatus
	        <input name=\"AUWide\" type=\"checkbox\" value=\"on\" $ononproj>
	      </td>
	    </tr>
	    <tr>
	      <td valign=\"top\"><b>Media</b></td>
	      <td colspan="2">
                $omediastatus
                <input name=\"AMedia\" type=\"checkbox\" value=\"on\" $omedia>
	      </td>
	    </tr>
	    <tr>
	      <td  valign=\"top\"><b>Energy Sector</b></td>
	      <td colspan="2" valign=\"top\">
	      Tick at least one of the following; please tick all that apply:<br>
                <table width="100%" border="0" cellpadding="2" cellspacing="2">
                  <tr>
                    <td width="50%" valign="top">
                      <table width="95%" border="0" cellpadding="2" cellspacing="2">
                        $esectcol1
                      </table>
                    </td>
                    <td width="50%" valign="top">
                      <table width="95%" border="0" cellpadding="2" cellspacing="2">
                        $esectcol2
                      </table>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
            <tr>
             <td colspan="3">
	       <input name="GoButton" type="submit" value="Update Record">
              </td>
            </tr>
            <tr>
             <td colspan="3">
               <hr color="#E8E8E8" />
             </td>
            </tr>
            <tr>
             <td colspan="3">
               <a href="$returnmenu?DMName=$tdmname">
                 Return to Data Managers Menu
               </a>
               <br>
               <a href="$logout">
                 Log out of Data Managers Interface
               </a>
             </td>
           </tr>
         </table>
       </form>
EOM
;;
}

#----------------------------------------------------------------*
# Subroutine  : UCAT323                                          |
# Purpose     : Show the Delete Details Page                     |
# Called from : Main Routine                                     |
# Calls       : &Prt, &SetHidden, &ShowHeader, &Show Footer,     |
#               &QueryRun,                                       |
# Arguments   : None                                             |
# Return Code : None                                             |
#----------------------------------------------------------------*
sub             UCAT323 
{
   $scrno     = "ERC726";
   $scrnct    = 0; 
   print "          <form action=\"$prog\" method=\"get\">\n";
   &SetHidden;
   print <<EOM
          <table class="boundary-box" cellpadding="2" cellspacing="2">
            <tr>
              <td colspan="3" align="left" valign="top">
                <h5 align="left">UKERC Roadmaps Catalogue</h5>
                $breadcrumbs
                <hr color="#E8E8E8" />
              </td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top">
                <h6>Delete Metatdata Record</h6>
              </td>
            </tr>
            <tr>
              <td colspan="3" align="left" valign="top">
                Please make very sure this is the record you want to delete. <br>
                <b>Once done, this cannot be undone!</b><br>
                This does not delete the PDF file, but it will no longer be discoverable without the full URL
              </td>
            </tr>
	    <tr>
	      <td valign="top"><b>Article ID</b></td>
	      <td colspan="2">$uradio</td>
            </tr>
	    <tr>
	      <td valign="top"><b>Formal Citation</b></td>
	      <td colspan="2">$ocitation</td>
            </tr>
	    <tr>
	      <td valign="top"><b>Authors</b></td>
	      <td colspan="2">$oauthors</td>
	      </tr>
	    <tr>
	      <td valign="top"><b>Surname of Principal Author</b></td>
	      <td colspan="2">$oauthorsuc</td>
            </tr>
	    <tr>
	      <td valign="top"><b>Title</b></td>
	      <td colspan="2">$otitle</td>
            </tr>
            <tr>
	      <td valign="top"><b>Publication Year</b></td>
	      <td colspan="2">$oyear</td>
	    </tr>
	    <tr>
	      <td valign="top" class="dark"><b>Publication Type</b></td>
	      <td colspan="2" >$apubname</td>
	    </tr>
EOM
;;

   for $i(1..$#outline)
   {
      print "$outline[$i]\n";
   }
 
   print <<EOM

            <tr>

	      <td valign="top"><b>Abstract</b></td>
	      <td colspan="2">$oabstract</td>
	    </tr>

	    <tr>
	      <td colspan="3" valign="top">
	        <hr class="pale">
	        </td>
	      </tr>
	    <tr>
	      <td colspan="3" valign="top" class="otitle">Classification</td>
	      </tr>
            <tr>
              <td valign="top" colspan="2"><b>Research Theme</b></td>
              <td valign="top">
EOM
;;

   for $i(1..$#theme1id)
   {
      if ($otheme1[$i] ne "")
      {
         print "              $theme1[$i]<br>\n";
      }
   }
   if ($notheme1 eq "")
   {
       print "              (none)\n";
   }

   print <<EOM

              </td>
	    </tr>
            <tr>
              <td valign="top""><b>Energy Sector</b></td>
              <td valign="top" colspan="2>
EOM
;;
   for $i(1..$#sectid)
   {
      if ($osect[$i] ne "")
      {
         print "              $sectname[$i]<br>\n";
      }
   }
   if ($notheme1 eq "")
   {
       print "              (none)\n";
   }


   if ($ononprojstatus ne "")
   {
      print "            <tr>\n";
      print "              <td colspan=\"3\"><b>Non-Project-Specific</b></td>\n";
      print "            </tr>\n";
   }
   if ($omediastatus ne "")
   {
      print "            <tr>\n";
      print "              <td colspan=\"3\"><b>Media</b></td>\n";
      print "            </tr>\n";
   }

   print <<EOM

            <tr>
             <td colspan="3">
	       <input name="GoButton" type="submit" value="Destroy Record Now!">
             </td>
           </tr>
            <tr>
             <td colspan="3">
               <hr color="#E8E8E8" />
             </td>
            </tr>
            <tr>
             <td colspan="3">
               <a href="$returnmenu?DMName=$tdmname">
                 Return to Data Managers Menu
               </a>
               <br>
               <a href="$logout">
                 Log out of Data Managers Interface
               </a>
             </td>
           </tr>
         </table>
       </form>
EOM
;;
}
