#!/usr/bin/perl

# open input files for reading
open(OBJECTS_DTD, "objects.dtd") or die "Can't open objects.dtd: $!\n";
open(IDMAP, "objectsIDs.dtd") or die "Can't open objectsIDs.dtd: $!\n";
open(OBJECTS_EN_XIB, "objects_en.xib") or die "Can't open original objects.dtd: $!\n";

# open output file for writing
open(OBJECTS_XIB, ">objects.xib");

# map entity names to their corresponding ID in .xib file
%ids=();
while ($line = <IDMAP>) {
  if($line=~m/(\w+)\.id\s*\"(\d*)\"/)
  {
    $ids{$1} = $2;
  }
};


# read objects.dtd and store values mapped to their IDs in hashtables
%titles = ();
%bounds = ();
while ($line = <OBJECTS_DTD>) {
  if($line=~m/(\w+)\.label\s*\"(.*)\"/)
  {
    $id=$ids{$1};
    $titles{$id} = $2;
  }
  if($line=~/(\w+)\.size/)
  {
    # initialize values with -1 so that we can test if they have been assigned to afterwards
    $top = -1;
    $left = -1;
    $bottom = -1;
    $right = -1;
    # test all values individually as we don't know if the order has been changed by the translator
    if($line=~/(\w+)\.size\s*\".*top:\s*(\d+)px;.*\"/)
    {
      $top = $2;
    }
    if($line=~/(\w+)\.size\s*\".*left:\s*(\d+)px;.*\"/)
    {
      $left = $2;
    }
    if($line=~/(\w+)\.size\s*\".*height:\s*(\d+)px;.*\"/)
    {
      # Apple uses the relative distance of the lower bound, 
      # so we have to calculate this from the height 
      # (relative to upper bound of the parent element)
      $bottom = $top+$2; 
    }
    if($line=~/(\w+)\.size\s*\".*width:\s*(\d+)px;.*\"/)
    {
      # Apple uses the relative distance of the right bound, 
      # so we have to calculate this from the width 
      # (relative to left bound of the parent element)
      $right = $left+$2; 
    }
    # only proceed if all values are specified
    if(($top >= 0) && ($left >= 0) && ($bottom >= 0) && ($right >= 0)) {
      $id=$ids{$1};
      $bounds{$id} = "$top $left $bottom $right "; # space after last value is used in original file, too
    }
  }
};

# read original objects.xib (OBJECTS_EN_XIB) and fill in the translated values
# leave entry unchanged if no translation exists
$current_id = 0;
while ($line = <OBJECTS_EN_XIB>) {
  if ($line=~/<object.*id=\"(\d*)\">/) { $current_id = $1;
  }
  if($line=~/<\/object>/) {$current_id = 0;}
  if($titles{$current_id} && ($line=~/<string name=\"title\">(.*)<\/string>/)) 
  {
    $line=~s/$1/$titles{$current_id}/;
  }
  if($bounds{$current_id} && ($line=~/<string name=\"bounds\">(.*)<\/string>/)) 
  {
    $line=~s/$1/$bounds{$current_id}/;
  }
  print OBJECTS_XIB "$line"
}


