cleaned up code, added length limiter by period counter