extern crate rand;

use std::io::{stdin, stdout, Write};
use std::thread;
use std::time::Duration;

use rand::Rng;

fn toss_coin<R: Rng>(rng: &mut R, print: bool) -> char {
    let c = if rng.gen() { 'H' } else { 'T' };
    if print {
        print!("{}", c);
        stdout().flush().expect("Could not flush stdout");
    }
    c
}

fn gen_sequence<R: Rng>(rng: &mut R, seed: Option<&str>) -> String {
    let mut seq = String::new();
    match seed {
        Some(s) => {
            let mut iter = s.chars();
            let c0 = iter.next().unwrap();
            let next = if c0 == 'H' { 'T' } else { 'H' };
            seq.push(next);
            seq.push(c0);
            seq.push(iter.next().unwrap());
        }
        None => {
            for _ in 0..3 {
                seq.push(toss_coin(rng, false))
            }
        }
    }
    seq
}

fn read_sequence(used_seq: Option<&str>) -> String {
    let mut seq = String::new();
    loop {
        seq.clear();
        println!("Please, enter sequence of 3 coins: H (heads) or T (tails): ");
        stdin().read_line(&mut seq).expect("failed to read line");
        seq = seq.trim().to_uppercase();