use 5.020;
use strict;
use warnings;


binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst());


sub binaryRand
{
    return int(rand(2));
}

sub convert
{
    my $randNum = binaryRand();
    if($randNum == 0)
    {
        return "T"
    }
    else
    {
        return "H";
    }
}


sub uSeq
{
    print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n>");
    my $uString = <STDIN>;

    while(1)
    {
        
        chomp($uString);
        $uString = uc $uString;
        
        if(length $uString == 3 && (substr($uString, 0, 1) =~ /[HT]/ &&
                                    substr($uString, 1, 1) =~ /[HT]/ &&
                                    substr($uString, 2, 1) =~ /[HT]/))
        {
            last;
        }
        else
        {
            print("Error, try again. \n");
            print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n");
            $uString = <STDIN>;
        }
    }
    return $uString;
}


sub compFirst
{
    my $cSeq;
    
    for(my $i = 0; $i < 3; $i++)
    {
        $cSeq = $cSeq . convert();
    }

    print("The computer guesses first:\ncomp- $cSeq\n");
    my $uSeq = uSeq();
    print("user- $uSeq\n");
    my @seqArr = ($uSeq, $cSeq);
    return @seqArr;
}


sub userFirst
{
    print("The user quesses first:\n");
    my $uSeq = uSeq();
    my $cSeq;
    
    my $middle = substr($uSeq, 1, 1);
    $middle eq "H" ? $cSeq = "T" : $cSeq = "H";
    $cSeq = $cSeq . substr($uSeq, 0, 2); 

    print("user- $uSeq\ncomp- $cSeq\n");
    my @seqArr = ($uSeq, $cSeq);
    return @seqArr; 
}


sub flipCoin
{
    my ($uSeq, $cSeq) = @_;
    my $coin;
    while(1)
    {
        $coin = $coin . convert();
        if($coin =~ m/$uSeq/)
        {
            print("The sequence of tosses was: $coin\n");
            say("The player wins! ");
            last;
        }
        elsif($coin =~ m/$cSeq/)
        {
            print("The sequence of tosses was: $coin\n");
            say("The computer wins! ");
            last;
        }
    }
}