/*
 * 
 * Serve
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.mar.AnException;
import net.mar.ParseCoords;
import net.mar.SLALIB;

import org.apache.log4j.Logger;

import uk.ac.roe.wfau.ATLASHTTPSession;
import uk.ac.roe.wfau.DatabaseConnection;
import uk.ac.roe.wfau.DatabaseURL;
import uk.ac.roe.wfau.FormatLines;
import uk.ac.roe.wfau.HTMLSnippets;
import uk.ac.roe.wfau.ImageSelect;
import uk.ac.roe.wfau.SQLMethods;
import uk.ac.roe.wfau.SesameClient;
import uk.ac.roe.wfau.TangentRectangle;
import uk.ac.roe.wfau.VDFSSchema;
import uk.ac.roe.wfau.VDFSSession;
import uk.ac.roe.wfau.VSASchema;
import uk.ac.roe.wfau.OSASchema;
import uk.ac.roe.wfau.WSAHTMLSchema;
import uk.ac.roe.wfau.WSASchema;
import uk.ac.roe.wfau.WSASession;

import com.javaexchange.dbConnectionBroker.DbConnectionBroker;

public class GetImage extends HttpServlet {
   /**
    * Log4j logger for record keeping 
    */
    private static Logger logger;
    
    //private DBConnectionManager connMgr; // previous connection pool
    private DbConnectionBroker myBroker;
    private static final int RUNNUM_UPPERLIMIT = 99999;

    private static int RunNumber = 0; // 'Unique' counter

    private static String tempPath;
    private static String colourTempPath;
    private static String photomTempPath;
    private static String LISTCGIDIRURL;
    private static String colourTempURL;

    private static String progPath;
    private static int NOFILTERS=10; // list driven
    private static String tempURL;

    private static String filePrefix;

    private static String BASESQL = "SELECT  multiframedetector.filterid,MultiFrameDetector.extNum,MultiFrame.filename, "
            + "programmeid,CurrentAstrometry.*, "
            + "MultiframeDetector.axis1Length,MultiframeDetector.axis2Length "
            + "FROM    Multiframe "
            + "INNER JOIN MultiframeDetector ON Multiframe.multiframeID = MultiframeDetector.multiframeID "
            + "INNER JOIN CurrentAstrometry ON Multiframe.multiframeID = CurrentAstrometry.multiframeID AND "
            + "MultiframeDetector.extNum = CurrentAstrometry.extNum "
            + "INNER JOIN ProgrammeFrame ON Multiframe.multiframeID = programmeframe.multiframeID";

    private static String BASESQL_SELECT;
    private static String BASESQL_FROM;
    private static String BASESQL_WHERE;
    private static String COLOURCGIDIRURL;
    private static String WSACGIDIRURL;
 //   private String ukidss_database;
    private String defaultUKIDSSDatabase;
    private String defaultWorldDatabase;
    private String server;
    
    private static String [] VSASERVERS=null;
    private static String [] WSASERVERS=null;
    private static String [] VSACUSERVERS=null;
    private static String [] WSACUSERVERS=null;
    private static String [] WSANSSERVERS=null;
    
    private static final float MINCOLOURPIXSIZE=0.1f;
    private static final float MAXCOLOURSIZE=60.0f;
    private static final int MAXPIXSIZE=9000;
   
    
    private static synchronized int getNextRunNumber() {
        RunNumber++;

        if (RunNumber > RUNNUM_UPPERLIMIT) {
            RunNumber = 1;
        }
        ;

        return RunNumber;
    };

    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
        logger = Logger.getLogger("wsa.simple");
        logger.debug("initializing GetImage servlet");

        // read in global properties
        Properties properties = new Properties();
        String path = getServletContext().getRealPath("/");
        try {
            properties.load(new FileInputStream(path
                    + "WEB-INF/WSA.properties"));

        } catch (IOException e) {
            logger.error("GetImage, properties file not found");
            return;
        }
        server = properties.getProperty("server");
        WSASERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("WSASERVERS").trim());
        VSASERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("VSASERVERS").trim());
        WSACUSERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("WSACUSERVERS").trim());
        VSACUSERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("VSACUSERVERS").trim());
        WSANSSERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("WSANSSERVERS").trim());
        
 //       String user = properties.getProperty("user");
 //      String passwd = properties.getProperty("passwd");
 //       ukidss_database = properties.getProperty("ukidss_database");
        defaultUKIDSSDatabase = properties.getProperty("defaultUKIDSSDatabase");
        defaultWorldDatabase = properties.getProperty("defaultWorldDatabase");
//        String public_database = properties.getProperty("public_database");
//       String poolLogfile = properties.getProperty("pool.logfile");
        colourTempPath = properties.getProperty("colourTempPath");
        colourTempURL = properties.getProperty("colourTempURL");
        tempPath=properties.getProperty("GetImageTempPath");
        photomTempPath=properties.getProperty("photomTempPath");
        LISTCGIDIRURL=properties.getProperty("LISTCGIDIRURL");
        progPath = properties.getProperty("GetImageProgPath");
        tempURL = properties.getProperty("GetImageTempURL");
        filePrefix = properties.getProperty("GetImageFilePrefix");
        BASESQL_SELECT = properties.getProperty("GetImageBASESQL_SELECT");
        BASESQL_FROM = properties.getProperty("GetImageBASESQL_FROM");
        BASESQL_WHERE = properties.getProperty("GetImageBASESQL_WHERE");
        COLOURCGIDIRURL=properties.getProperty("COLOURCGIDIRURL");
        WSACGIDIRURL=properties.getProperty("WSACGIDIRURL");
        if (WSACGIDIRURL == null) {
            WSACGIDIRURL=WSAHTMLSchema.baseCGIURL;
        }
        //connMgr = DBConnectionManager.getInstance(); // previous connection manager
        /* no longer using connection pool as different logins required
        try {
            myBroker = new DbConnectionBroker(
                    "com.microsoft.jdbc.sqlserver.SQLServerDriver",
                    "jdbc:microsoft:sqlserver://" + server
                            + ":1433;DatabaseName=" + public_database, user, passwd,
                    2, 10, poolLogfile, 0.25, false, 300, 1);
        } 
        catch (IOException e) {
            logger.error(e);
        }
        */

    }

    static {

        try {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // A class not found error means the SQL driver class could not be
            // found.
            // Which means that this driver would not be available until this is
            // remedied. This flag variable will signal this to the class!

            logger.error("GetImage, Could not load SQLServerDriver class!");
        }
        // originally need to load jni library but the libary is in the java path
        //System.out.println(System.getProperty("java.library.path"));

        //System.loadLibrary("libjniast.so");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // get seesion and see if user logged in
        boolean loginboolean=false;
        HttpSession session = req.getSession();
    String archive="WSA";
        
        if (req.getParameter("archive") != null) {
            archive=req.getParameter("archive");
        }
        
        Enumeration eP= req.getParameterNames();
        StringBuffer urlSB=new StringBuffer(req.getRequestURL()+"?");
        String eParam=null;
        while (eP.hasMoreElements()) {
        	eParam=(String)eP.nextElement();
        	urlSB.append(eParam);
        	urlSB.append("=");
        	urlSB.append(req.getParameter(eParam));
        	urlSB.append("&");
        }
        logger.info("URL: "+urlSB);
        
        if (archive.equalsIgnoreCase("osa") && req.getParameter("passThrough")!=null  ) {
        	if( req.getParameter("passThrough").equalsIgnoreCase(OSASchema.ATLASPASSTHROUGHPASSWORD)){
        	session=new ATLASHTTPSession();
        	}
        }
    
        int archiveID=VDFSSchema.getArchiveID(archive);
        String community=VDFSSession.getCommunity(session,archiveID);
        String [] servers = VDFSSession.getServers(community,archive,WSASERVERS,WSACUSERVERS,VSASERVERS,VSACUSERVERS,WSANSSERVERS);
        
      
        try {
            loginboolean=VDFSSession.getLoginBoolean(session,archive);
            }
            catch (Exception e){
                loginboolean=false;
            }
            String userSess=VDFSSession.getUser(session,archiveID,false);//(String)session.getAttribute("user");
            String genUser=VDFSSession.getUser(session,archiveID,true);
            String communitySess=VDFSSession.getCommunity(session,archiveID);//(String)session.getAttribute("community");
         
            // start OFFLINE
        if (req.getParameter("mode") != null && req.getParameter("mode").equalsIgnoreCase("offline")) {
            String auth=null;
            if (req.getParameter("user") != null && req.getParameter("passwd") != null && req.getParameter("community") != null) {
                auth=req.getParameter("user")+req.getParameter("passwd")+req.getParameter("community");
            }
    
 

            if (DBLogin.userMap != null && auth!=null && DBLogin.userMap.get(auth) != null) {
                loginboolean=true;
            } else {
                //out.print("notin");
                DBLogin dbl = new DBLogin();
                try {
                    loginboolean=dbl.VerfiyUserSQL(req.getParameter("user"),req.getParameter("passwd"),req.getParameter("community"),null,VDFSSchema.WSAARCHIVEID);
                } catch (Exception e1) {
                  //  e1.printStackTrace(out);
                }
            }
            String database;
            if (loginboolean) {
                database=WSASchema.LATESTUKIDSSDATABASE;
            }
            else {
                database=WSASchema.LATESTWORLDDATABASE;
            }
            String durl=DatabaseURL.getDatabaseURLWSA(loginboolean,"ifa33p",database,true);

            Connection con=null;
            try {
            con = DriverManager.getConnection(durl);
            Statement stmt= null;
            ResultSetMetaData md = null;
            stmt = con.createStatement();
            String qStr="select mf.multiframeID,mf.frametype,mf.obstype,mfd.filterid,f.shortname,mf.dateObs,mfd.extNum,mf.filename,mfd.axis1Length,mfd.axis2Length,ca.cTypeX,ca.cTypeY,ca.crValX,ca.crValY,ca.crPixX,ca.crPixY,ca.pv21,ca.pv23,ca.cd11,ca.cd12,ca.cd22,ca.cd21,ca.xpixsize,ca.ypixsize from marframesets as fs, currentastrometry as ca, multiframe as mf,multiframeDetector as mfd, filter as f where ca.multiframeid=fs.multiframeid and ca.extnum=fs.extnum and mfd.extNum=ca.extNum and mf.multiframeId=mfd.multiframeId and f.filterid=mf.filterid and ((118.83 >= minRA and 118.83 <= maxRA) or (118.83 + 360.0 >= minRA and 118.83 + 360.0 <= maxRA))  and ( 4.5 >= minDec and 4.5 <= maxDec)  and mf.multiframeid=ca.multiframeid";
            ResultSet rs = stmt.executeQuery(qStr);
            md = rs.getMetaData();
            Calendar rightNow=Calendar.getInstance();
            String uniqID = 
                String.valueOf(rightNow.get(Calendar.MINUTE))
              + String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)+rightNow.get(Calendar.HOUR_OF_DAY))        
              +"_"
              + String.valueOf(rightNow.get(Calendar.MILLISECOND))
              +"_"
              + String.valueOf(rightNow.get(Calendar.SECOND))        
              + "_"+ getNextRunNumber();
            ImageSelect ImgSel = new ImageSelect(archiveID);
            ImgSel.setUniqueID(uniqID);
            boolean check = ImgSel.setRSMD(md);
            
            String resArray[][] = ImgSel.setRS(rs,118.83,4.5,1,1);
            if (resArray[0][0] !=null){
                res.sendRedirect(WSACGIDIRURL+"getFImage1.cgi?"+ImgSel.getQueryString(resArray[0]));
            }
            else {
                res.setContentType("text/html");
                PrintWriter out = res.getWriter();
                out.print(durl);
                out.print("No match");
            }
            }
            catch (SQLException se){
                //out.print(se);
            }
            finally {
                try {
                    con.close();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                }
                System.gc();
            }
           // res.sendRedirect(" http://www-wfau.roe.ac.uk/~sss/cgi-bin/gaia_pix.cgi?ra=14:12:01.662&dec=-16:58:44.89&survey=3&mime-type=image/x-gfits&x=0.8&y=0.5");
   
            return ;
        }
        
        // END OFFLINE
        
        StringBuffer select = new StringBuffer(BASESQL_SELECT);
        StringBuffer from = new StringBuffer(BASESQL_FROM);
        StringBuffer where = new StringBuffer(BASESQL_WHERE);
        
        if (archiveID == VDFSSchema.VSAARCHIVEID) {
            select.append(",pv24,pv25");
        }
        
        boolean proceed=true;
        boolean doForce=true;

        res.setContentType("text/html");
        
        PrintWriter out = res.getWriter();

        

        Calendar rightNow=Calendar.getInstance();
        String uniqID = 
                  String.valueOf(rightNow.get(Calendar.MINUTE))
                + String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)+rightNow.get(Calendar.HOUR_OF_DAY))        
                +"_"
                + String.valueOf(rightNow.get(Calendar.MILLISECOND))
                +"_"
                + String.valueOf(rightNow.get(Calendar.SECOND))        
                + "_"+ getNextRunNumber();
        
        
        
 
        StringBuffer errorMessage = new StringBuffer("");
        String outputMessage = "";

        String UKIDSSDatabase=defaultUKIDSSDatabase.toString();
        String worldDatabase=defaultWorldDatabase.toString();
   
        String database=req.getParameter("database");
        
        if (database.equalsIgnoreCase("none")) {
            proceed=false;
            out.println("<b>Error: No valid database.</b><br>");
        }
        if (database == null) {
            
            if (communitySess.equalsIgnoreCase("nonSurvey")) {
              
                database = userSess;
            } else {
                if (loginboolean) {
                    
                    database = defaultUKIDSSDatabase.toString();
                } else {
                    
                    database = defaultWorldDatabase.toString();
                }
            }
        } else {
            
            UKIDSSDatabase = database;
            worldDatabase = database;
        }
        /*
        if (database.equalsIgnoreCase(VSASchema.PRERELEASEDATABASE) && archiveID==VDFSSchema.VSAARCHIVEID && community.equalsIgnoreCase(VSASchema.PROPRIETARYCOMMUNITY)) {
            servers=VSACUSERVERS;
        }*/
        
        Connection con = null;
        ResultSet rs = null;
        Statement stmt=null;
        String xsize = "1"; //defualt
        if (req.getParameter("xsize") != null) {
            xsize = req.getParameter("xsize");
        }
        String ysize = "1"; //defualt
        if (req.getParameter("ysize") != null) {
            ysize = req.getParameter("ysize");
        }
        
        
        String[] coordsStr2000 = null;
        String sesameName=null;
        String sys="J"; //default
        ParseCoords pc=null;
        if (req.getParameter("sys") !=null){
            sys=req.getParameter("sys");
        }
        
        if (req.getParameter("name") != null && !req.getParameter("name").trim().equals("")) {
            try {
                sesameName=req.getParameter("name");
                SesameClient sClient=new SesameClient(sesameName);
            
            pc=new ParseCoords(sClient.getRA(),sClient.getDec(),"J");
            coordsStr2000 = pc.getCoordsString2000();
            }
            catch (Exception e) {
                proceed=false;
                errorMessage.append("<br><b>"+e.getMessage()+".</b>");
            }
        }
        else {
        try {
            pc = new ParseCoords(req.getParameter("ra"), req.getParameter("dec"), sys);
            coordsStr2000 = pc.getCoordsString2000();
            
        } catch (AnException ae) {
            proceed=false;
            //out.print("<br><b>"+ae.getMore()+".</b>");
            errorMessage.append("<br><b>"+ae.getMore()+".</b>");
            
        }
        }
        
        
        // start LIST
        
        if (req.getParameter("mode") != null && req.getParameter("mode").equalsIgnoreCase("photom")) {
            out.print(HTMLSnippets.getStartPageWithTitleAndBody("WSA Photometry","onLoad=\"swap(0);\"","",WSAHTMLSchema.baseURL+"imSwap.js"));
            out.println("<td><img name=\"imgMain\" src=\""+WSAHTMLSchema.baseURL+"static.gif\" border=\"1\"></td></table><p>");
            out.flush();
            
            
            try {
                // out.print(coordsStr2000[0]+" "+coordsStr2000[1]);
                 double [] fk5Coords =pc.getCoordsDouble2000();
                 double [] galCoords=SLALIB.EQGAL(fk5Coords[0]*Math.PI/180.0,fk5Coords[1]*Math.PI/180.0);
                 
                 
                 if (fk5Coords[0] < 0 || fk5Coords[0] > 360 || fk5Coords[1] < -90 || fk5Coords[1] > 90  ) {
                     proceed=false;
                     errorMessage.append("<br>RA = "+ParseCoords.formatP(fk5Coords[0],6));
                     errorMessage.append("<br>Dec = "+ParseCoords.formatP(fk5Coords[1],6));
                     errorMessage.append("<br><b>RA and Dec of centre outside range 0 &lt; RA &lt; 360 , -90 &lt; Dec &lt; 90</b>");
                 }
                 String programmeID=null, photoSQL=null, mergelog=null;

                 try {
                 programmeID=req.getParameter("programmeID").trim();
                 mergelog=VDFSSchema.getMergeTableName(Integer.valueOf(programmeID).intValue(),archive);        
                 }
                 catch (Exception e) {
                     proceed=false;
                     errorMessage.append("<br><b>Unable to parse programme or filters</b>");
                     
                 }
                 
                 double userX=1.0;
                 double userY=1.0;
                 try {
                     userX = Double.valueOf(xsize).doubleValue();
                     userY = Double.valueOf(ysize).doubleValue();
                       }
                       catch (Exception e) {
                           proceed=false;
                           errorMessage.append("Unable to parse X-size/Y-size, go BACK and check inputs");
                           return;
                       }
                String photomSQL=SQLMethods.getPhotomSQL(BASESQL_SELECT,coordsStr2000[0],coordsStr2000[1],Integer.valueOf(programmeID).intValue());
                
                if (!proceed) {
                 out.print("<p>"+errorMessage.toString());
                 return;
                }
                 out.flush();
                 res.flushBuffer();
                 out.println("<!-- "+photomSQL+" -->");
                 
                 
                 //String durl=DatabaseURL.getDatabaseURL(session,true,server,UKIDSSDatabase,worldDatabase);
                
                 
                 
                 //out.println("<br>Connecting to database: "+DatabaseURL.getDatabaseNameFromURL(durl,true));
                 out.println("<br>Connecting to database: "+database);
                 out.println("<script language=\"JavaScript\" type=\"text/javascript\"> <!-- ");
                 out.println("swap(1);");
                 out.println("--> </script>");
                 out.flush();
                 
                 if (archiveID==VDFSSchema.VSAARCHIVEID && VSASchema.isProprietary(community) && (database.equalsIgnoreCase(VSASchema.rollingDB) || database.equalsIgnoreCase(VSASchema.PRERELEASEDATABASE))) {
                     database=VSASchema.actualRollingDB;
                   //  out.print(" ("+database+")");
                 }
                 if (archiveID==VDFSSchema.OSAARCHIVEID && OSASchema.isProprietary(community) && (database.equalsIgnoreCase(OSASchema.rollingDB) || database.equalsIgnoreCase(OSASchema.PRERELEASEDATABASE))) {
                     database=OSASchema.actualRollingDB;
                   //  out.print(" ("+database+")");
                 }
                 con=DatabaseConnection.getConnection(servers,database,archive,session);
                 //con = DriverManager.getConnection(durl);
                 if (con == null) {
                     out.println("Can't get connection");
                     return;
                 }
                 out.print("<p>Querying for pixel data at RA: "+ParseCoords.formatP(fk5Coords[0],6) + " Dec: "+ ParseCoords.formatP(fk5Coords[1],6));
                 out.flush();
                 res.flushBuffer();
                 
                 int crows=0;
                 
                 ResultSetMetaData md = null;
                 
                 
                 ImageSelect ImgSel = new ImageSelect();
                 
                 try {
                     stmt = con.createStatement();
                     rs=stmt.executeQuery(photomSQL);
                     md = rs.getMetaData();
                     boolean check = ImgSel.setRSMD(md);
                     ImgSel.setFilterIDAsObjNum(true);
                     String [][] strArray=ImgSel.setRS(rs,fk5Coords[0],fk5Coords[1],userX,userY,NOFILTERS);
                     /*
                     String resFile=colourTempPath+"/"+uniqID+"c.res";
                     String resURL=colourTempURL+"/"+uniqID+"c.res";
                     BufferedWriter resultsFile = new BufferedWriter(new FileWriter(resFile));
                     int filterID;
                     String colour;
                     String redMFID;
                     String greenMFID;
                     String blueMFID;
                     */
                     /*
                     while (rs.next()) {
                         for (int i=0; i < rs.getMetaData().getColumnCount();  i++) {
                             out.println(rs.getString(i+1)+"<br>");
            
                         }
                         crows++;
                         out.println("<p>");
                           }
               */ 
                     out.print("<p>Finding charts: "+userX+" x "+userY+" arcmin (unless edge of detector/tile)");
                     out.print("<table>");
                     String resFile=photomTempPath+"/"+uniqID+"p.res";
                     resFile=resFile.trim();
                     BufferedWriter resultsFile = new BufferedWriter(new FileWriter(resFile));
                     
                     for (int i=0; i< NOFILTERS;i++) {
                         if (strArray[i][0] != null) {
                             resultsFile.write(fk5Coords[0]+","+fk5Coords[1]);
                             for (int j=0; j<strArray[i].length;j++){
                                 resultsFile.write(","+strArray[i][j]);
                             }
                             resultsFile.write(",band="+VDFSSchema.getFilterName(Integer.valueOf(strArray[i][2]).intValue(),archiveID)+",objName=obj,upID=1\n");
                             
                             crows++;
                             out.print("<td align=\"center\"><b>"+VDFSSchema.getFilterName(Integer.valueOf(strArray[i][2]).intValue(),archiveID)+"</b><br>");
                             out.print("<p><img src=\""+ImageSelect.getImageURL(WSACGIDIRURL+"getJFImage.cgi",strArray[i])+"\">");
                             out.print("</td>");
                         //out.println("<p>"+strArray[i][0]+" "+strArray[i][2]);
                         }
                     }
                     out.print("</table>");
                       
                       
                       //resultsFile.close();
                       if (crows ==0) {
                           out.print ("<p><b>No multiframes at the position requested</b>"); 
                           return;
                       }
                       
               
                    
                         
                         
                         resultsFile.close();
                        res.flushBuffer();
                      
                       
                       
                       out.print ("<p>Initial query performed.");
                       res.flushBuffer();
                       try {
                           URL url=null;
                           
                               out.print("<p>Initiating list driven photometry ....<p>");
                               res.flushBuffer();
                               url = new URL (LISTCGIDIRURL+"interactivePhotometryContd.jsp?file="+resFile+"&progID="+programmeID+"&luptitudePar="+req.getParameter("luptitudePar"));
                               logger.info("GetImage: photomurl "+url.getFile());
                               
                       //out.println(url.getFile()+"<p>");
                       URLConnection uc = url.openConnection();
                       InputStream content = (InputStream)uc.getInputStream();
                       BufferedReader in   = 
                         new BufferedReader (new InputStreamReader (content));
                       String wLine;
                       while ((wLine = in.readLine()) != null) {
                         out.println (wLine);
                       }
                     } catch (MalformedURLException e) {
                       out.println ("Invalid URL");
                     } catch (IOException e) {
                       out.println ("Error reading URL");
                     }
                      
            
                 }
                 catch (Exception e){
                     logger.error("GETIMAGE PHOTOM "+e.getMessage());
                 }
                 finally {
                     out.print("<script language=\"JavaScript\" type=\"text/javascript\">\n <!--\n swap(0)\n -->\n </script>\n </body></html>");
                     try {
                         con.close();
                         con=null;
                     }
                     catch (Exception e){
                        
                     }
                 }
                 
                 
                 return;
                     }
                     catch (Exception e) {
                         logger.error("GETIMAGE PHOTOM "+e.getMessage());
                     }
                     finally {
                         if (con != null) {
                         try {
                             con.close();
                         }
                         catch (Exception e){
                            
                         } 
                         }
                     }
            
            
            
        } // end photom
        
        // COLOUR
        if (req.getParameter("mode") != null && req.getParameter("mode").equalsIgnoreCase("colour")) {
            out.print(HTMLSnippets.getStartPageWithTitleAndBody("WSA ColourImage","onLoad=\"swap(0);\"","",WSAHTMLSchema.baseURL+"imSwap.js"));
            out.println("<td><img name=\"imgMain\" src=\""+WSAHTMLSchema.baseURL+"static.gif\" border=\"1\"></td></table><p>");
            out.flush();
            String email=null;
            String email1=null;
            float userX=5.0f;
            float userY=5.0f;
            float userPix=0.4f;
            int nX=0;
            int nY=0;
            String pixSize="0.4";
            if (req.getParameter("pixsize") !=null){
                pixSize=req.getParameter("pixsize").trim();
            }        
            if (req.getParameter("email") !=null){
                email=req.getParameter("email").trim();
            }
            if (req.getParameter("email1") !=null){
                email1=req.getParameter("email1").trim();
            }
            
            if (email == null || email1 == null || !email.equalsIgnoreCase(email1) || email.length() < 3 || email.indexOf('@') < 1) {
                proceed=false;
                errorMessage.append("<br><b>Invalid email address(es) or they don't match</b>");
            }
            try {
                userX = Float.valueOf(xsize).floatValue();
                userY = Float.valueOf(ysize).floatValue();
                userPix = Float.valueOf(pixSize).floatValue();
                  }
            
                  catch (Exception e) {
                      proceed=false;
                      errorMessage.append("<br><b>Unable to parse X-size, Y-size or pixel size, check inputs</b>");
                      
                  }
                  if (userX > MAXCOLOURSIZE || userX < 0.1 || userY < 0.1 || userY > MAXCOLOURSIZE || userPix < MINCOLOURPIXSIZE) {
                      proceed=false;
                      errorMessage.append("<br><b>X-size/Y-size &gt; "+MAXCOLOURSIZE+" or pixel size &lt; "+MINCOLOURPIXSIZE+"</b>");
                  }
                  try {
                  nX=(int)(userX*60.0/userPix);
                  nY=(int)(userY*60.0/userPix);}
                  catch (Exception e) {
                      proceed=false;
                      errorMessage.append("<br><b>Unable to parse number of pixels (size/pixSize) for output</b>");
                  }
                  if (nX >  MAXPIXSIZE || nY > MAXPIXSIZE) {
                      proceed=false;
                      errorMessage.append("<br><b>Output image calculated as "+nX+" x "+nY+" pixels. Maximum allowed is "+MAXPIXSIZE +" pixels in X and Y</b>");
           
                  }
            try {
       // out.print(coordsStr2000[0]+" "+coordsStr2000[1]);
        double [] fk5Coords =pc.getCoordsDouble2000();
        double [] galCoords=SLALIB.EQGAL(fk5Coords[0]*Math.PI/180.0,fk5Coords[1]*Math.PI/180.0);
        
        
        if (fk5Coords[0] < 0 || fk5Coords[0] > 360 || fk5Coords[1] < -90 || fk5Coords[1] > 90  ) {
            proceed=false;
            errorMessage.append("<br>RA = "+ParseCoords.formatP(fk5Coords[0],6));
            errorMessage.append("<br>Dec = "+ParseCoords.formatP(fk5Coords[1],6));
            errorMessage.append("<br><b>RA and Dec of centre outside range 0 &lt; RA &lt; 360 , -90 &lt; Dec &lt; 90</b>");
        }
        String red=null,green=null,blue=null,programmeID=null,mergelog=null,colourSQL=null;

        try {
            
        if (req.getParameter("programmeID") != null) {    
        programmeID=req.getParameter("programmeID");
        }
        else if ((community.equalsIgnoreCase("nonSurvey") || VDFSSchema.isProprietary(community,archiveID))&& VDFSSession.getLoginBoolean(session,archive)) {
            programmeID=VDFSSession.getProgID(session,archiveID);
           // out.print(programmeID);
        }
        
        red=req.getParameter("red");
        green=req.getParameter("green");
        blue=req.getParameter("blue");
        if (programmeID != null && !communitySess.equalsIgnoreCase("nonsurvey")) {
            logger.info(programmeID+" "+archive);
        mergelog=VDFSSchema.getMergeTableName(Integer.valueOf(programmeID).intValue(),archive); 
        if (mergelog == null) {
            mergelog=genUser+"mergelog";
        }
        }
        else if (communitySess.equalsIgnoreCase("nonsurvey")) {
            mergelog=userSess+"mergelog";
        }
        }
        catch (Exception e) {
            proceed=false;
            errorMessage.append("<br><b>Unable to parse programme or filters</b>");
            
        }
        
        String [] rgb={red,green,blue};
        TangentRectangle tr=new TangentRectangle(fk5Coords[0],fk5Coords[1],userX,userY);
        double minLat=tr.getMinLatitude();
        double maxLat=tr.getMaxLatitude();
        double minLong=tr.getMinLongitude();
        double maxLong=tr.getMaxLongitude();
        
        if (maxLong < minLong){
            maxLong=maxLong+360.0;
        }
        
       
       
        
       colourSQL=SQLMethods.getColourRegionSQL(Double.toString(minLong),Double.toString(maxLong),
               Double.toString(minLat),Double.toString(maxLat),rgb,mergelog,archiveID);
       
       if (!proceed) {
        out.print("<p>"+errorMessage.toString());
        return;
       }
        out.flush();
        res.flushBuffer();
        
        //String durl=DatabaseURL.getDatabaseURL(session,true,server,UKIDSSDatabase,worldDatabase);
        out.println("<br>Connecting to database: "+database);
        out.println("<script language=\"JavaScript\" type=\"text/javascript\"> <!-- ");
        out.println("swap(1);");
        out.println("--> </script>");
        out.flush();
 
        con=DatabaseConnection.getConnection(servers,database,archive,session);
         //con = DriverManager.getConnection(durl);
        if (con == null) {
            out.println("Can't get connection");
            return;
        }
        out.print("<p>Querying around RA: "+ParseCoords.formatP(fk5Coords[0],6) + " Dec: "+ ParseCoords.formatP(fk5Coords[1],6));
        out.flush();
        res.flushBuffer();
        
        int crows=0;
        
        ResultSetMetaData md = null;
        try {
            stmt = con.createStatement();
            logger.info("colour SQL: "+colourSQL);
            rs=stmt.executeQuery(colourSQL);
            String resFile=colourTempPath+"/"+uniqID+"c.res";
            String resURL=colourTempURL+"/"+uniqID+"c.res";
            BufferedWriter resultsFile = new BufferedWriter(new FileWriter(resFile));
            int filterID;
            String colour;
            String redMFID;
            String greenMFID;
            String blueMFID;
            
            while (rs.next()) {
                for (int i=0; i < rs.getMetaData().getColumnCount();  i++) {
                    resultsFile.write(rs.getString(i+1)+",");
                /*
                filterID=rs.getInt("filterID");
                if  (rs.getString("multiframeID").equals(rs.getString(rgb[0]+"MFID") )) {
                    resultsFile.write("R ,"+rs.getString(rgb[0]+"enum"));
                    resultsFile.write(", "+rs.getString("filename")+"\n");
                }
               if (rs.getString("multiframeID").equals(rs.getString(rgb[1]+"MFID"))) {
                    resultsFile.write("G ,"+rs.getString(rgb[1]+"enum"));
                    resultsFile.write(", "+rs.getString("filename")+"\n");
                }
               if (rs.getString("multiframeID").equals(rs.getString(rgb[2]+"MFID"))){
                    resultsFile.write("B ,"+rs.getString(rgb[2]+"enum"));
                    resultsFile.write(", "+rs.getString("filename")+"\n");
                }
                  */  
                 
                }
                crows++;
                resultsFile.write("\n");
                  }
      
       
              
              
              resultsFile.close();
              if (crows ==0) {
                  out.print ("<p><b>No multiframes found in the area requested</b>"); 
                  return;
              }
              
              out.print ("<p>Initial query performed, submitting job ");
              try {
 
                  String scale="A";
                  if (programmeID != null) {
              if (Integer.valueOf(programmeID).intValue() == WSASchema.UKIDSSGPSPROGRAMMEID || Math.abs(galCoords[1]*180/Math.PI) < 10){
                  scale="L";
              }
                  }
              URL url = new URL (COLOURCGIDIRURL+"ColourParent.cgi?file="+resFile+"&email="+email+"&cRA="+fk5Coords[0]+
                      "&cDec="+fk5Coords[1]+"&pixSize="+userPix+"&nX="+nX+"&nY="+nY+"&scale="+scale+"&progID="+programmeID+
                      "&R="+red+"&G="+green+"&B="+blue+"&archive="+archive.toLowerCase()+"&url="+resURL);
             // out.print(url);
              logger.info("ColourGetImage: cgiurl "+url.getFile()+","+req.getRemoteAddr());
              URLConnection uc = url.openConnection();
              InputStream content = (InputStream)uc.getInputStream();
              BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
              String wLine;
              while ((wLine = in.readLine()) != null) {
                out.println (wLine);
              }
              out.println("<!-- <UNIQUEID>"+uniqID+"</UNIQUEID> -->");
            } catch (MalformedURLException e) {
              out.println ("Invalid URL");
            } catch (IOException e) {
              out.println ("Error reading URL");
            }
              
            
        }
        catch (Exception e){
            logger.error("GETIMAGE COLOUR "+e.getMessage());
        }
        finally {
            out.print("<script language=\"JavaScript\" type=\"text/javascript\">\n <!--\n swap(0)\n -->\n </script>\n </body></html>");
            try {
                con.close();
                con=null;
            }
            catch (Exception e){
               
            }
        }
        
        
        return;
            }
            catch (Exception e) {
                logger.error("GETIMAGE COLOUR "+e.getMessage());
            }
            finally {
                if (con != null) {
                try {
                    con.close();
                }
                catch (Exception e){
                   
                } 
                }
            }

        } // end COLOUR
        
        
        out.print("<HTML><HEAD>");
        out.print(WSAHTMLSchema.focusJS);
        out.print("</HEAD>");
    //    out.print("here");
        out.flush();
        res.flushBuffer();
        if (proceed) {  
        where.append(
                " and (("+coordsStr2000[0]+" >= minRA and "+
                coordsStr2000[0]+" <= maxRA)" +
                " or ("+coordsStr2000[0]+" + 360.0 >= minRA and "+
                coordsStr2000[0]+" + 360.0 <= maxRA))" +
                " and ( "+coordsStr2000[1]+" >= minDec and "+
                coordsStr2000[1]+" <= maxDec)"
                );
        }
        String mode="";
        if (req.getParameter("mode") != null){
            mode=req.getParameter("mode");
        }
        String programmeID="all"; // default was null
        String programmeStr=VDFSSchema.getAllSurveys(archiveID) ;// default
        
        
        
        if ((community.equalsIgnoreCase("nonSurvey") || VDFSSchema.isProprietary(community,archiveID))&& VDFSSession.getLoginBoolean(session,archive)) {
            programmeID=VDFSSession.getProgID(session,archiveID);
           // out.print(programmeID);
        }
        else {
            if (req.getParameter("programmeID") != null && !communitySess.equalsIgnoreCase("nonSurvey") && !VDFSSchema.isProprietary(communitySess,archiveID)){
                programmeID=req.getParameter("programmeID");
                if (!programmeID.equals("all")){
                    try {
                        programmeStr=VDFSSchema.getSurveyName(Integer.valueOf(programmeID).intValue(),archiveID);
                        }
                        catch (NumberFormatException nfe) {
                            proceed=false;
                            errorMessage.append("<br><b>Invalid programmeID.</b>");
                        }
            }
        }
        }

        if (communitySess != null && (communitySess.equalsIgnoreCase("nonSurvey") || VDFSSchema.isProprietary(communitySess,archiveID))) {
            
            try {
                int iPID=Integer.valueOf(programmeID).intValue();
                if (iPID <1000 && (archiveID==VDFSSchema.VSAARCHIVEID || archiveID==VDFSSchema.OSAARCHIVEID)) {
                    programmeStr=VDFSSchema.getSurveyName(iPID,archiveID);
                }
                else {
                programmeStr=userSess;
                }
                }
                catch (NumberFormatException nfe) {
                    programmeStr=userSess;
                }
            
            
        }
        
     
        
       // if (!loginboolean && database.equalsIgnoreCase("ukidssdr8plus") && programmeID != null && (programmeID.equalsIgnoreCase("102") || programmeID.equalsIgnoreCase("105"))) {
       if (!loginboolean && database.equalsIgnoreCase("ukidssdr8plus") && programmeID != null && (programmeID.equalsIgnoreCase("102"))) { 
        proceed=false;
        errorMessage.append("<br><b>GPS not yet publically available in UKIDSSDR8PLUS, please use an earlier version.</b>");
        }
        String notAll=null;
        if (programmeID != null) { // && !communitySess.equalsIgnoreCase("nonSurvey")){
           // programmeID=req.getParameter("programmeID");
            if (!programmeID.equals("all")){
                from.append(",programmeFrame as pf ");
                where.append(" and mf.multiframeid=pf.multiframeid and pf.programmeId="+programmeID+" ");
            }
            else {
                from.append(",programmeFrame as pf ");
                where.append(" and mf.multiframeid=pf.multiframeid and pf.programmeId < 1000  and pf.programmeId > 10 ");
                if (!loginboolean && database.equalsIgnoreCase("ukidssdr8plus")) {
                    //where.append(" and pf.programmeId !=102 and pf.programmeId != 105 ");
                    where.append(" and pf.programmeId !=102  ");
                    
                    notAll="<br>(LAS, GCS, DXS and UDS only)";
                }
            }
        }      
        String multiframeID=null;
        if (req.getParameter("multiframeID") != null){
            multiframeID=req.getParameter("multiframeID").trim();
            where.append(" and mf.multiframeid="+multiframeID+" ");
        }
        String extNum=null;
        if (req.getParameter("extNum") != null){
            extNum=req.getParameter("extNum");
            where.append(" and mfd.extNum="+extNum+" ");
        }
        String filterID="all"; //default was null
        String filterName="all";
        if (req.getParameter("filterID") != null){
            filterID=req.getParameter("filterID");
            if (!filterID.equalsIgnoreCase("all")){
                try {
                filterName=VDFSSchema.getFilterName(Integer.valueOf(filterID).intValue(),archiveID);
                }
                catch (NumberFormatException nfe) {
                    proceed=false;
                    errorMessage.append("<br><b>Invalid filterID.</b>");
                }
            where.append(" and mf.filterID="+filterID+" ");
            }
        }
        
        String obsType=req.getParameter("obsType");
        String frameType=req.getParameter("frameType");
        
        if (obsType != null){
            if (obsType.equalsIgnoreCase("object")) {
                where.append(" and ( "+
                        "obstype NOT LIKE 'BIAS%' AND frametype NOT LIKE 'BIAS%' AND "+
                        "obstype NOT LIKE 'DARK%' AND frametype NOT LIKE 'DARK%' AND "+
                        "obstype NOT LIKE 'SKY%' AND frametype NOT LIKE 'SKY%' AND "+
                        "obstype NOT LIKE 'FOCUS%' AND frametype NOT LIKE 'FOCUS%' AND "+
                        "obstype NOT LIKE 'CONFIDENCE%' AND frametype NOT LIKE 'CONFIDENCE%' AND "+
                        "obstype NOT LIKE '%FLAT%' AND frametype NOT LIKE '%FLAT%'"+
                        ") ");
            }
            else if (obsType.equalsIgnoreCase("bias")){
                where.append(" and ( obstype like 'BIAS%' or frametype like 'BIAS%') ");               
            }
            else if (obsType.equalsIgnoreCase("dark")){
                where.append(" and ( obstype like 'DARK%' or frametype like 'DARK%') ");               
            }
            else if (obsType.equalsIgnoreCase("flat")){
                where.append(" and ( obstype like '%FLAT%' or frametype like '%FLAT%') ");               
            }
            else if (obsType.equalsIgnoreCase("sky")){
                where.append(" and ( obstype like 'SKY%' or frametype like 'SKY%') ");               
            }
            else if (obsType.equalsIgnoreCase("focus")){
                where.append(" and ( obstype like 'FOCUS%' or frametype like 'FOCUS%') ");               
            }
            else if (obsType.equalsIgnoreCase("confidence")){
                where.append(" and ( obstype like 'CONFIDENCE%' or frametype like 'CONFIDENCE%') ");               
            }
            
        }
        
        if (frameType != null && !frameType.equalsIgnoreCase("all")){
                where.append(" and ( "+
                        "frametype LIKE '%"+frameType+"%') ");
            }
        
        out.println ("<h3>GetImage cut-out results</h3>");
        
        String suppliedMFID=req.getParameter("mfid");
        
        if (suppliedMFID != null && !suppliedMFID.equals("")) {
            try {
                long lMFID=Long.valueOf(suppliedMFID.trim()).longValue();
                out.println("<br><b>MultiframeID: </b>"+suppliedMFID);
                where.append(" and (MF.multiframeID="+suppliedMFID+")");
                doForce=false;
            }
            catch (NumberFormatException nfe){
                // do nothing
            }
        }
        
        String framesetID=req.getParameter("fsid");
        
        // frameset
        String mergeLog=null;
        long lPID=0;
        if (framesetID != null && !framesetID.equals("")) {
            doForce=false;
            try {
                long lFSID=Long.valueOf(framesetID.trim()).longValue();
                long maska=0xffff00000000L;
                long maskb=0x100000000L;
                lPID=(lFSID & maska)/maskb;
                if (communitySess != null){
                if (communitySess.equalsIgnoreCase("nonsurvey")) {
                    mergeLog=userSess+"mergelog";
                
                }
                else {
                    //mergeLog=WSASchema.getMergeTableName((int)lPID);
                    mergeLog=VDFSSchema.getMergeTableName((int)lPID,archive);
                    if (mergeLog == null) {
                        mergeLog=genUser+"mergelog";
                    }
                    //programmeStr=WSASchema.getSurveyName((int)lPID);
                    programmeStr=VDFSSchema.getSurveyName((int)lPID,archiveID);
                }
                }
                else {
                    //mergeLog=WSASchema.getMergeTableName((int)lPID);
                    mergeLog=VDFSSchema.getMergeTableName((int)lPID,archive);
                   //programmeStr=WSASchema.getSurveyName((int)lPID);
                    programmeStr=VDFSSchema.getSurveyName((int)lPID,archiveID);
                }
                
                
                //out.println("pid"+lPID+" user "+userSess+" comm "+communitySess+ " mergelog "+mergeLog);
                if (mergeLog == null) {
                    out.println("<b>Warning: Unable to resolve mergelog name from framesetID.</b><br>");
                    proceed=false; 
                }
                
                
            }
            catch (NumberFormatException nfe){
                out.println("<b>Warning: The supplied framesetID is not a valid number.</b><br>");
                proceed=false;
            }
            
            
        }
        double userRA;
        double userDec;
        double userX;
        double userY;
        
        if (!proceed){
            out.println(errorMessage);
            out.println("<p><b>Query stopped: check warnings above and try again.</b>");
            return;
        }
          try {
        userRA = Double.valueOf(coordsStr2000[0]).doubleValue();
        userDec = Double.valueOf(coordsStr2000[1]).doubleValue();
        userX = Double.valueOf(xsize).doubleValue();
        userY = Double.valueOf(ysize).doubleValue();
          }
          catch (Exception e) {
              out.println("Unable to parse coordinates or X-size/Y-size, go BACK and check inputs");
              return;
          }
        
          if (req.getParameter("project")!= null) {
          	programmeStr=req.getParameter("project");
          	suppliedMFID="";
          }
          
        if (sesameName !=null) {
            out.println("<br><b>Name:</b> "+sesameName);
        }
        out.println("<br><b>J2000 coords:</b> RA: "+ParseCoords.formatP(userRA,7) + " Dec:" + ParseCoords.formatP(userDec,6));
        out.println("<br><b>Programme:</b> "+programmeStr);
        if (notAll != null) {
            out.print(notAll);
        }
        out.println("<br><b>Filter:</b> "+filterName);
        
        out.println("<br>Processing ...");
        res.flushBuffer();
        out.flush();
        res.flushBuffer();
        int numPixels = 0;

        String bestFile = null;
        
        ImageSelect ImgSel = new ImageSelect(archiveID);
        ImgSel.setPrintWriter(out);
        ImgSel.setCgiURL(WSACGIDIRURL+"getImage.cgi?");
        ImgSel.setUniqueID(uniqID);
        if (mode.equalsIgnoreCase("show") && (suppliedMFID !=null || framesetID !=null)) {
            ImgSel.setDoMap(true);
        }
        Map resMap;
        //System.out.println("must be at least here");
        
        

        
        
        try {
            logger.info("GetImage,Login,"+userSess+","+communitySess+","+req.getRemoteAddr()+","+programmeID);
           // con = myBroker.getConnection();
            //String durl=DatabaseURL.getDatabaseURL(session,true,server,UKIDSSDatabase,worldDatabase);
            out.println("<br>Connecting to database: "+database+"<p>");
            logger.info("GETIMAGE getting connection");
            
            if (archiveID==VDFSSchema.VSAARCHIVEID && VSASchema.isProprietary(community) &&
                    (database.equalsIgnoreCase(VSASchema.rollingDB) || database.equalsIgnoreCase(VSASchema.PRERELEASEDATABASE))) {
                database=VSASchema.actualRollingDB;
              
            }
            if (archiveID==VDFSSchema.OSAARCHIVEID && OSASchema.isProprietary(community) &&
                    (database.equalsIgnoreCase(OSASchema.rollingDB) || database.equalsIgnoreCase(OSASchema.PRERELEASEDATABASE))) {
                database=OSASchema.actualRollingDB;
              
            }
            
            con=DatabaseConnection.getConnection(servers,database,archive,session);
            servers=null;
            
             // con = DriverManager.getConnection(durl);
            if (con == null) {
                out.println("Can't get connection");
                return;
            }
            

            
            
            
            ResultSetMetaData md = null;
            try {
                stmt = con.createStatement();
                logger.info("GetImage created stmt.");
                if (mergeLog != null) {
                    
                    /*rs = stmt.executeQuery(WSASchema.getRequiredFiltersSQL()+" where programmeID= "+lPID);
                    String framesetSQL=WSASchema.getFramesetSQL(rs,mergeLog,"mf").toString();
                    rs.close();	
                    */
                    int [] farray;
                    if (!communitySess.equalsIgnoreCase("nonsurvey")) {
                        farray=VDFSSchema.getReqFilters(database,(int)lPID,archiveID);
                    }
                    else {
                        farray=WSASession.getReqFilters(session);
                    }
                    
                   // rs = stmt.executeQuery(SQLMethods.getRequiredFiltersSQL()+" where programmeID= "+lPID);
                    //StringBuffer framesetSQL=SQLMethods.getFramesetSQL(rs,mergeLog,"mf",archiveID);
                    rs = stmt.executeQuery(SQLMethods.getRequiredFiltersSQL()+" where programmeID= "+lPID);
                    StringBuffer framesetSQL=SQLMethods.getFramesetSQL(rs,mergeLog,"mf",archiveID,framesetID);
                    logger.info("GETIMAGE post framesetsql");
                   // logger.info("GETIMAGE post1 "+SQLMethods.getFramesetSQL(rs,mergeLog,"mf",archiveID,framesetID));
                    //out.print(framesetSQL);
                    //out.flush();
                    //String framesetSQL=WSASchema.getFramesetSQL(farray,mergeLog,"mf").toString();
                    //logger.info(framesetSQL);
                    if (framesetSQL==null){
                        out.print("<br><b>Unable to construct frameset SQL.</b><br>");
                        con.close();
                        return;
                    }
                    
                    // from.append(","+mergeLog);
                    from.append(",("+framesetSQL+") as t");
                    //where.append(" and framesetid="+framesetID+" and ("+framesetSQL+")");
                    where.append(" and t.mfid=mfd.multiframeid and t.enum=mfd.extnum ");
                    
                }
                
 
                
                
                
                
                
                
                
                
                //stmt.executeUpdate("use wsa");
              String SQL;
              if (doForce) {
              SQL=select+" "+from+" "+where+" order by mf.filterID,mf.dateobs option (force order)";
              }
              else {
                  SQL=select+" "+from+" "+where+" order by mf.filterID,mf.dateobs";
              }
               // out.println("<p>"+SQL +"<p>");
                
               /*if (loginboolean){
                    stmt.executeUpdate("use "+ukidss_database);
                }
                */
              logger.info("GetImage SQL " +SQL);
                rs = stmt.executeQuery(SQL);
                md = rs.getMetaData();

                int row = 0;
                String filename = null;
                double xPixelSize = 0.0;
                double yPixelSize = 0.0;
                double nx = 0;
                double ny = 0;
                int lowx = 0;
                int highx = 0;
                int lowy = 0;
                int highy = 0;
                String jpegFile = tempPath + uniqID + ".jpg";
                String fitsFile = tempPath + uniqID + ".fits.gz";
                
                String options = null;
                
                
                boolean check = ImgSel.setRSMD(md);
                
                String resArray[][] = ImgSel.setRS(rs,userRA,userDec,userX,userY);
                out.println(ImgSel.getNoRows()+ " rows returned. ");
                
                resArray=null;
                if (mode.equalsIgnoreCase("show") && (suppliedMFID !=null || framesetID !=null)) {
                resMap = ImgSel.getResMap();
                List keys=new ArrayList(resMap.keySet());
                Collections.sort(keys);
                //Set keyValuePairs = resMap.keySet();
               

                //Iterator it = keyValuePairs.iterator();
                Iterator it = keys.iterator();
                //out.println(resMap.size());
                
                int j=0;
                String newUrl=null;
                out.print("<p><center><table border=\"2\" cellpadding=\"4\" cellspacing=\"4\"><tr>");
                int width=300;
                int height=300;
                while (it.hasNext() ) {
                    width=300;
                    height=300;
                    out.flush();
                    res.flushBuffer();
                  
                    j=j+1;
                    
                    //System.out.println("here");
                    String name = (String) it.next();
                    String[] sa = (String[]) resMap.get(name);
                    if (sa[16].equalsIgnoreCase("1") || sa[16].equalsIgnoreCase("3") ) {
                        width=Integer.valueOf(sa[7]).intValue()-Integer.valueOf(sa[6]).intValue()+1;
                        height=Integer.valueOf(sa[5]).intValue()-Integer.valueOf(sa[4]).intValue()+1; 
                    }
                    else {
                        width=Integer.valueOf(sa[5]).intValue()-Integer.valueOf(sa[4]).intValue()+1;
                        height=Integer.valueOf(sa[7]).intValue()-Integer.valueOf(sa[6]).intValue()+1;
                    }
                    if (width < 0 || width > 460) {
                        width=450;
                    }
                    if (height < 0 || height > 460) {
                        height=450;
                    }
                    out.print("<td align=\"center\"><b>"+VDFSSchema.getFilterName(Integer.valueOf(sa[2]).intValue(),archiveID)+"</b><br>"
                            +VDFSSchema.getDateFromFile(sa[0],archiveID)+"<br>");
                    
                    if (height > width) {
                    	out.print("<p><img height=\""+height+"\" src=\""+ImageSelect.getImageURL(WSACGIDIRURL+"getJFImage.cgi",sa)+"\">");
                    	//width=height;
                    }
                    else {
                    	out.print("<p><img width=\""+width+"\" src=\""+ImageSelect.getImageURL(WSACGIDIRURL+"getJFImage.cgi",sa)+"\">");
                    }

                    
                    out.print("</td>");
                    if (j%2==0) {
                        out.print("<tr>");
                    }
                    out.flush();
                    res.flushBuffer();
                    Thread.sleep(1000);
                
                }
                out.print("</table></center>");
                it=null;
                keys=null;
                
                }
                resMap=null;
                
                
                
                
                
                /* out.println("<p><a href=\"http://surveys.roe.ac.uk/~mar/cgi-bin/getImage.cgi?"+
                        ImgSel.getQueryString(resArray)+
                        "\">link </a>");
                options = " " + resArray[3] + " " + resArray[4] + " "
                        + resArray[5] + " " + resArray[6] + " " + resArray[7]
                        + " '" + resArray[10] + "'";
                        */
                
                //out.flush();
//                bestFile = filePrefix + resArray[0];

//             File baseFitsFile = new File(bestFile);

  
                /*
                if (baseFitsFile.exists()) {
                    try {
                        System.out.println("file exists");
                        Runtime rt = Runtime.getRuntime();
                        String[] execStrArray1 = { progPath + "read_img.e",
                                bestFile, fitsFile, resArray[3], resArray[4],
                                resArray[5], resArray[6], resArray[7],
                                resArray[10] };
                        //             Process proc = rt.exec(progPath+"read_img.e
                        // "+bestFile
                        //     +" "+fitsFile+options);
                        Process proc = rt.exec(execStrArray1);
                        // any error message?
                        StreamGobbler errorGobbler = new StreamGobbler(proc
                                .getErrorStream(), "ERROR");

                        // any output?
                        StreamGobbler outputGobbler = new StreamGobbler(proc
                                .getInputStream(), "OUTPUT");

                        // kick them off
                        errorGobbler.start();
                        outputGobbler.start();

                        // any error???
                        int exitVal = proc.waitFor();
                        System.out.println("ExitValue: " + exitVal);
                        errorMessage = errorGobbler.getMessageBuffer();
                        outputMessage = outputGobbler.getMessageBuffer();

                        out.println("<p><a href=\"" + tempURL + uniqID
                                + ".fits.gz\">FITS file</a>");
                        out.println("/home/mar/fits2jpeg -fits '"
                                + fitsFile.trim() + "[1]' -jpeg " + jpegFile);
                        String[] execStrArray = { progPath + "fits2jpeg",
                                "-fits", fitsFile.trim() + "[1]", "-jpeg",
                                jpegFile };
                        proc = rt.exec(execStrArray);
                        // any error message?
                        errorGobbler = new StreamGobbler(proc.getErrorStream(),
                                "ERROR");

                        // any output?
                        outputGobbler = new StreamGobbler(
                                proc.getInputStream(), "OUTPUT");

                        // kick them off
                        errorGobbler.start();
                        outputGobbler.start();

                        // any error???
                        exitVal = proc.waitFor();
                        System.out.println("ExitValue: " + exitVal);
                        errorMessage = errorGobbler.getMessageBuffer();
                        out.println(errorMessage.toString());
                        outputMessage = outputGobbler.getMessageBuffer();
                        File JPEGFile = new File(jpegFile);
                        if (JPEGFile.exists()) {
                            out.println("<p><img src=\"" + tempURL + uniqID
                                    + ".jpg\">");
                        }
                        System.out.println("number 1");
                        resMap = ImgSel.getResMap();
                        Set keyValuePairs = resMap.keySet();

                        Iterator it = keyValuePairs.iterator();
                        out.println(resMap.size());
                        if (mode.equalsIgnoreCase("list")){
                            out.println("<p><table>");
                        }
                        int j=0;
                        String newUrl=null;
                        String sqlExtNum=null;
                        while (it.hasNext() && 1==2) {
                            out.flush();
                            res.flushBuffer();
                            if (mode.equalsIgnoreCase("list")){
                                out.println("<tr>");
                                }
                            j=j+1;
                            //System.out.println("here");
                            String name = (String) it.next();
                            String[] sa = (String[]) resMap.get(name);
                            sqlExtNum=String.valueOf(Integer.valueOf(sa[3]).intValue()+WSASchema.FITS_OFFSET);
                            newUrl="http://relnx03.roe.ac.uk:8080/ssa/GetImage?"+
                            "ra="+userRA+
                            "&dec="+userDec+
                            "&xsize="+userX+
                            "&ysize="+userY+
                            "&multiframeID="+sa[1]+
                            "&extNum="+sqlExtNum;
                        
                            
                            out.println("<td><a href=\""+newUrl+"\">link</a></td>");
                            for (int i = 0; i < 4; i++) {
                                if (mode.equalsIgnoreCase("list")){
                                out.println("<td>"+sa[i]+"</td>");
                                }
                            }
                            String uniqName=uniqID+j;
                            if (imageExtract(sa,uniqName)){
                                out.println("<p><a href=\"" + tempURL + uniqName
                                        + ".fits.gz\">FITS file</a>");
                                out.println("<p><img src=\"" + tempURL + uniqName
                                        + ".jpg\">");
                                
                            }   
                        }
                        if (mode.equalsIgnoreCase("list")){
                            out.println("</table>");
                            }
                        //System.out.println(sa[0]+" "+sa[1]);
                        System.out.println("number 2");
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                    System.out.println("number 3");

                }
                */
                
                
               
            } catch (SQLException se) {
                out.println("<p>Error querying the database: "
                        + se.getErrorCode() + se);

                if (se.getErrorCode() == 0) {
                    con.close();
                }
            }
            

            catch (Exception e) {
                out.println("<p>Error "+e);
                System.out.println(e);
                //e.printStackTrace(out);
            }


        } 
        
        catch (SQLException se) {
            out.println("<p>Error querying the database, unable to get connection ");
            logger.error("GetImage,"+se);
        }
        
        
        catch (Exception e) {
            logger.error("GetImage,"+e);
           // System.out.println("errorher");
           // System.out.println(e);
           // e.printStackTrace(out);
  
        } finally {

            resMap=null;
            ImgSel=null;
            
            System.gc();
            //System.out.println("gc called");
            //out.flush();
            //out.close();
            try {
                //Thread.	(6000);
                stmt.close();

            } catch (Exception e) {
                ;
            }
            if (con != null) {

                
                //	connMgr.freeConnection("idb", con);
              //  myBroker.freeConnection(con);
                try {
                    con.close();
                    con=null;
                    stmt=null;
                    rs=null;
                }
                catch (Exception e) {
                    ;
                }    

                
            }

        } // finally

    } // doGet

    public void destroy() {
        //          connMgr.release();
        //myBroker.destroy();
        logger=null;
        super.destroy();
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // Data received by an HTTP POST is handled the same way
        // as data sent with a HTTP GET request... simply pass on to above...
        doGet(req, res);
    }; // END of doPost()

    protected boolean imageExtract(String[] strArray, String uniqName) {
        String baseFitsFileName = filePrefix + strArray[0];
        String outFitsFileName=tempPath + uniqName + ".fits.gz";
        String outJpegFileName=tempPath + uniqName + ".jpg";
        String errorMessage = "";
        String outputMessage = "";
        File baseFitsFile = new File(baseFitsFileName);
        File JPEGFile;
        if (baseFitsFile.exists()) {
            try {
               // System.out.println("file exists");
                Runtime rt = Runtime.getRuntime();
                String[] execStrArray1 = { progPath + "read_img.e",
                        baseFitsFileName, outFitsFileName, strArray[3], strArray[4],
                        strArray[5], strArray[6], strArray[7],
                        strArray[10] };   
                Process proc = rt.exec(execStrArray1);
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc
                        .getErrorStream(), "ERROR");
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc
                        .getInputStream(), "OUTPUT");

                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                // any error???
                int exitVal = proc.waitFor();
                
                errorMessage = errorGobbler.getMessageBuffer();
                outputMessage = outputGobbler.getMessageBuffer();

  
                String[] execStrArray = { progPath + "fits2jpeg",
                        "-fits", outFitsFileName.trim() + "[1]", "-jpeg",
                        outJpegFileName };
                proc = rt.exec(execStrArray);
                // any error message?
                errorGobbler = new StreamGobbler(proc.getErrorStream(),
                        "ERROR");

                // any output?
                outputGobbler = new StreamGobbler(
                        proc.getInputStream(), "OUTPUT");

                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                // any error???
                exitVal = proc.waitFor();
               // System.out.println("ExitValue: " + exitVal);
                errorMessage = errorGobbler.getMessageBuffer();                
                outputMessage = outputGobbler.getMessageBuffer();
                JPEGFile = new File(outJpegFileName);
                if (JPEGFile.exists()) {
                    return true;
                    }
            }
                catch (Exception e) {
                    return false;
                }
        }
        else {
            return false;
        }
        return false;
    }
}

class StreamGobbler extends Thread {
    InputStream is;

    String type;

    OutputStream os;

    StringBuffer messageBuffer = new StringBuffer("a");

    StreamGobbler(InputStream is, String type) {
        this(is, type, null);
    }

    StreamGobbler(InputStream is, String type, OutputStream redirect) {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }

    public synchronized void run() {
        try {
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);

            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (pw != null)
                    pw.println(line);
                messageBuffer.append(line);
                //System.out.println(messageBuffer.toString());
            }
            if (pw != null)
                pw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        // System.out.println(messageBuffer.toString());
    }

    public synchronized String getMessageBuffer() {
        return messageBuffer.toString();
    }
}

