#!/usr/bin/perl
#
#  Action module for Ant monitoring system
#
#  Dumps data into plain files, naming them on FIRST ARGUMENT
#
#  Arguments - dir to log
#
#  Template for logging: filename what_to_log
#  what_to_log must be finalized by carriage return. If you want to
#  write carriage return, then you can use '\n' sequence. If you want
#  to write '\', then you must send '\\'.
#

use Fcntl;
use IO::Handle;

#open STDERR,">>$ARGV[0]" or die "Cannot open $ARGV[0] to append\n";

$|=1;

my ($name,$data,$dir,$string,$last);

$dir=$ARGV[0];

for(;;){
  $string=$last='';
INNER_LOOP:
  for(;;){
    while(read(STDIN,$p,1)>0){
      if($p eq "\n"){
        if($last eq "\\"){
          $string = $string . "\\";
        }
        last INNER_LOOP;
      }
      elsif($p eq "\\" and $last ne "\\"){
        $last="\\";
        next;
      }
      if($last eq "\\"){
        if($p eq 'n'){
           $p="\n";
        }
        elsif($p eq "\\"){}
        else{
          $p="\\$p";
        }
      }
      $string .= $p;
      if($p eq "\\" and $last eq "\\"){
        $last='';
      }
      else{
        $last=$p;
      }
    }
    select(undef,undef,undef,0.1);
  }
#  print STDERR "STR:'$string'\n";
  ($name,$data)=($string=~/^(\S+)\s+(.*)$/s);
  unless($name =~ m(^/)){
    $name = "$dir/$name";
  } 
#  print STDERR "Writing '$data' to $name.\n";
  if(open X, ">$name"){
    print X $data;
    close X;
  }
}

#print STDERR "logger end! ($!)\n";

