#!/usr/bin/perl

use strict;
use warnings;

$|=1;

require POSIX;

if (!-p "/tmp/swo.log")
{
    POSIX::mkfifo("/tmp/swo.log", 0666) or die "can't mknod swo.log: $!";
}

while(1)
{
    if (!sysopen(SWO, "/tmp/swo.log", 0))
    {
        print "Can't sysopen swo.log: $!\n";
        sleep 1;
    }
    else
    {
        print "Opened /tmp/swo.log for reading\n";
        binmode SWO;
        
        my $n;
        my $rem = 0;
        my $cnt = 0;
        do
        {
            my $buf;
            $n = sysread(SWO, $buf, 100);
            if ($n)
            {
                my @data = unpack("C*", $buf);
                for (my $j = 0; $j<$n; $j++)
                {
                    my $c = $data[$j];
                    if ($rem == 0)
                    {
                        if ($c == 1 || $c == 2 || $c == 4)
                        {
                            $rem = $c;
                        }
                        else
                        {
                            printf "\nUnknown header 0x%02x\n", $c;
                        }
                    }
                    else
                    {
                        if ($c == 10 || $c == 13)
                        {
                            if ($cnt != 0)
                            {
                                print "\n";
                            }
                            $cnt = 0;
                        }
                        else
                        {
                            if ($cnt == 0)
                            {
                                print scalar localtime, " ";
                            }
 
                            printf "%c", $c;
                            $cnt++;
                        }
                        $rem--;
                    }
                }
            }
        }
        while ($n);
        close(SWO);
    }
}
