#!/usr/bin/perl

use strict;
use warnings;

# Read in strings from a file and generate
# an interesting song/album/artist name

# File to get strings from
my $seed_file = $ARGV[0];
my @data = split("\n", `cat $seed_file`);

# Length of random name (in words)
my $length = int(1 + rand(4 - 1));

my @words;

sub word_from_seed() {
my $word = $data[ rand @data ];
chomp $word;
return $word;
}

sub get_word {
my $tmp_word = word_from_seed();
chomp $tmp_word;
my $final = "";
if ( $tmp_word =~ m/ / ) {
my @strings = split(" ", $tmp_word);
my $string = $strings[ rand @strings ];
$final = $string;
} elsif ( $tmp_word =~ m/\./ ) {
my @strings = split(".", $tmp_word);
my $string = $strings[ rand @strings ];
$final = $string;
} else {
$final = $tmp_word;
}

# Chance to splice
my $flip = 1 + int(rand(2));
if ( $flip == 1 || $length == 1 ) {
# Get word, take the first 3 chars,
# save in $splice_word
my $splice_word = word_from_seed();
if ( length $splice_word >= 3 ) {
if ( $splice_word =~ m/(^.{3})/ ) {
$splice_word = $1;
}
} else {
$splice_word =~ m/(^.{1})/;
$splice_word = $1;
}

# Get final word, take last $rand chars,
# add to splice_word
if ( ! defined $final || $final eq "" ) {
$final = word_from_seed();
}
my $splice_char_num = 1 + int(rand(length $final));
if ( $splice_char_num < 1 ) {
$splice_char_num = 1;
}

$final =~ m/(.{$splice_char_num}$)/;
my $splice_word_2 = $1;

$final = $splice_word . $splice_word_2;
}

return $final;

}

if ( defined $ARGV[1] && $ARGV[1] eq "--gen-seed" ) {
my @seed_words = ();
foreach my $i ( 1..10000 ) {
my $word = get_word();
push(@seed_words, $word);
}
my $word_list = join("\n", @seed_words);
open(my $fh, '>', "generated_seed.txt");
print $fh $word_list;
close $fh;
my $sorted_list = `cat generated_seed.txt | sort | uniq`;
open(my $fh2, '>', "generated_seed.txt");
print $fh2 $sorted_list;
close $fh2;

exit 0;
}

foreach my $word ( 1..$length ) {
push(@words, get_word());
}

my $output = "";
foreach my $word (@words){
if ( ! defined $word || $word eq "") {
next;
}
$output = $output . $word . " ";
}

print "$output\n";