#!/usr/bin/env php
<?php # (jEdit options) :folding=explicit:collapseFolds=1:
/*****************************************************************************
    Given a PDB code, download it, get the map (if possible), add H,
    and make a multikin.


INPUTS (via $_SERVER['argv']):
    one or more PDB codes

OUTPUTS:

*****************************************************************************/
// EVERY *top-level* page must start this way:
// 1. Define it's relationship to the root of the MolProbity installation.
// Pages in subdirectories of lib/ or public_html/ will need more "/.." 's.
    if(!defined('MP_BASE_DIR')) define('MP_BASE_DIR', realpath(dirname(__FILE__).'/..'));
// 2. Include core functionality - defines constants, etc.
    require_once(MP_BASE_DIR.'/lib/core.php');
    require_once(MP_BASE_DIR.'/lib/model.php');
    require_once(MP_BASE_DIR.'/lib/analyze.php');
    require_once(MP_BASE_DIR.'/lib/visualize.php');
// 3. Restore session data. If you don't want to access the session
// data for some reason, you must call mpInitEnvirons() instead.
    mpInitEnvirons();       // use std PATH, etc.
    //mpStartSession(true);   // create session dir
// 5. Set up reasonable values to emulate CLI behavior if we're CGI
    set_time_limit(0); // don't want to bail after 30 sec!
// 6. Unlimited memory for processing large files
    ini_set('memory_limit', -1);

#{{{ a_function_definition - sumary_statement_goes_here
############################################################################
/**
* Documentation for this function.
*/
//function someFunctionName() {}
#}}}########################################################################

# MAIN - the beginning of execution for this page
############################################################################
// Default options
#$optClash   = true;
#$optCbeta   = true;
#$optRota    = true;
#$optRama    = true;
$optNuclear = false;
$optVerbose = true;
$optGzipKin = true;
$optMultikin = array(
    'ribbons'   => true,
    'Bscale'    => true,
    'Qscale'    => true,
    'altconf'   => true,
    'rama'      => true,
    'rota'      => true,
    'cbdev'     => true,
    'pperp'     => true,
    'clashdots' => true,
    'hbdots'    => true,
    'vdwdots'   => true,
);

$pdbCodeList = array();
// First argument is the name of this script...
if(is_array($_SERVER['argv'])) foreach(array_slice($_SERVER['argv'], 1) as $arg)
{
    #if($arg == '-noclash')      $optClash = false;
    #elseif($arg == '-nocbeta')  $optCbeta = false;
    #elseif($arg == '-norota')   $optRota = false;
    #elseif($arg == '-norama')   $optRama = false;
    if($arg == '-nuclear')       $optNuclear = true;
    else                        $pdbCodeList[] = $arg;
    #$pdbCodeList[] = $arg;
}
if(count($pdbCodeList) == 0)
    die("Must provide at least one PDB code on the command line!\n");

// Loop through all PDBs
foreach($pdbCodeList as $pdbCode)
{
  mpStartSession(true); // create a new session

  if($optVerbose) echo "Getting PDB file for $pdbCode...\n";
  $infile = getPdbModel($pdbCode);

  $inpath = $infile;
  $modelID = addModelOrEnsemble(
               $inpath,
               basename($inpath),
               false,
               true,
               true,
               false);

  $model =& $_SESSION['models'][$modelID];
  //$reduce_blength = $_SESSION['reduce_blength'];
  //$bcutval = 40; TO-DO - make these user controllable
  //$ocutval = 10;
  $pdbfile = $_SESSION['dataDir'].'/'.MP_DIR_MODELS."/$model[pdb]";
  $rawDir  = $_SESSION['dataDir'].'/'.MP_DIR_RAWDATA;
  if(!file_exists($rawDir)) mkdir($rawDir, 0777);
  $filename = basename($pdbfile);

  //$stats = $model['stats'];
  //$hasProtein = ($stats['sidechains'] > 0 ? True : False);
  //$hasNucAcid = ($stats['nucacids'] > 0 ? True : False);

  $infileH = $pdbCode."FH.pdb";

  if ($optNuclear)
  {
    $reduce_blength = 'nuclear';
    $_SESSION['reduce_blength'] = 'nuclear';
  }
  else $reduce_blength = 'ecloud';

  if($optVerbose)
  {
    if($optNuclear) echo "Adding hydrogens with -build -nuclear for $pdbCode...\n";
    else echo "Adding hydrogens with -build for $pdbCode...\n";
  }
  reduceBuild($pdbfile, $infileH, $reduce_blength);
  unlink($infile);

  $mapfile = "$pdbCode.2fofc.omap";
  if(!file_exists($mapfile))
  {
      if($optVerbose) echo "Getting electron density map for $pdbCode...\n";
      $tmpmap = getEdsMap($pdbCode, 'omap', '2fofc');
      if($tmpmap != null)
      {
          //rename($tmpmap, $mapfile);
          // Otherwise permissions are weird
          copy($tmpmap, $mapfile);
          unlink($tmpmap);
      }
      else echo "Unable to get map for $pdbCode!\n";
  }
  else echo "$mapfile already exists!\n";

  $mapfile = "$pdbCode.fofc.omap";
  if(!file_exists($mapfile))
  {
      if($optVerbose) echo "Getting electron density map for $pdbCode...\n";
      $tmpmap = getEdsMap($pdbCode, 'omap', 'fofc');
      if($tmpmap != null)
      {
          //rename($tmpmap, $mapfile);
          // Otherwise permissions are weird
          copy($tmpmap, $mapfile);
          unlink($tmpmap);
      }
      else echo "Unable to get map for $pdbCode!\n";
  }
  else echo "$mapfile already exists!\n";

  $kinfile = $pdbCode."H-multi.kin";
  if(!file_exists($kinfile))
  {
      if($optVerbose) echo "Making multicrit kinemage for $pdbCode...\n";
      makeMulticritKin2(
          array($infileH),
          $kinfile,
          $optMultikin);
      // Needed to get separate disulfides, which I want for the SS study.
      exec("prekin -cass -append -nogroup $infileH >> $kinfile");
      if($optGzipKin) destructiveGZipFile($kinfile);
  }
  else echo "$kinfile already exists!\n";
  mpDestroySession();
}

############################################################################
// Clean up and go home
?>
