#!/usr/bin/perl

# Thérèse Malliavin November 16, 2004
# Prepare the chemical shifts for input to RESCUE2, in xml format
# syntax: ./prep_rescue2.pl cs.in > cs.xml
# cs.in format: 
#
# spin system xxx
# H 7.64 
# C 62.5 
# N 110 
# spin system xxx
# H
# C 173.48 58.1 37.93
# N

open(IN,$ARGV[0]) || die "cannot open CS file"; 
while (<IN>) {
  @ff = split(' ',$_);
  if (($ff[0] eq "spin") && ($uu >= 1)) {
# write the spin system just read 
    printf "<res type=\" \"> \n";
    if ($nbH != 0) { 
     printf "  <cs type=\"H\" n=\"%d\"> \n",$nbH;
     printf "    ";
     for ($ii = 1; $ii <= $nbH; $ii++) {
      printf "%.2f ",$csH[$ii]; 
     };
     printf "\n";
     printf "  </cs> \n";
    };
    if ($nbC != 0) { 
     printf "  <cs type=\"C\" n=\"%d\"> \n",$nbC;
     printf "    ";
     for ($ii = 1; $ii <= $nbC; $ii++) {
      printf "%.2f ",$csC[$ii]; 
     };
     printf "\n";
     printf "  </cs> \n";
    };
    if ($nbN != 0) { 
     printf "  <cs type=\"N\" n=\"%d\"> \n",$nbC;
     printf "    ";
     for ($ii = 1; $ii <= $nbN; $ii++) {
      printf "%.2f ",$csN[$ii]; 
     };
     printf "\n";
     printf "  </cs> \n";
    };
    printf "</res> \n";
  }; 
  if ($ff[0] eq "spin") {
    $uu++; 
  };
  if ($ff[0] eq "H") {
# read the H chemical shifts
    @csH = split(' ',$_);
    $nbH = @csH-1;
  };  
  if ($ff[0] eq "C") {
# read the C chemical shifts
    @csC = split(' ',$_);
    $nbC = @csC-1;
  };  
  if ($ff[0] eq "N") {
# read the N chemical shifts
    @csN = split(' ',$_);
    $nbN = @csN-1;
  };  
}; 
close(IN); 

# write the last spin system just read 
printf "<res type=\" \"> \n";
if ($nbH != 0) { 
 printf "  <cs type=\"H\" n=\"%d\"> \n",$nbH;
 printf "    ";
 for ($ii = 1; $ii <= $nbH; $ii++) {
  printf "%.2f ",$csH[$ii]; 
 };
 printf "\n";
 printf "  </cs> \n";
};
if ($nbC != 0) { 
 printf "  <cs type=\"C\" n=\"%d\"> \n",$nbC;
 printf "    ";
 for ($ii = 1; $ii <= $nbC; $ii++) {
  printf "%.2f ",$csC[$ii]; 
 };
 printf "\n";
 printf "  </cs> \n";
};
if ($nbN != 0) { 
 printf "  <cs type=\"N\" n=\"%d\"> \n",$nbC;
 printf "    ";
 for ($ii = 1; $ii <= $nbN; $ii++) {
  printf "%.2f ",$csN[$ii]; 
 };
 printf "\n";
 printf "  </cs> \n";
};
printf "</res> \n";
