Incremental Game Time Format Incremental Game Time Format

Goal

Incremental games often have a countdown timer expressing the days, hours, minutes and seconds until a task is complete.  Depending on the space available, they can be formatted as:

2d 13h
23h 59m 48s
14m
3h 0m 0s


The goal of this code golf is to write a function or program that performs this formatting.

Inputs


The total number of seconds.
The maximum number of segments to output.


Output


Segments include:


0w weeks
0d days
0h hours
0m minutes
0s seconds

Each segment is separated by a single space.
Displayed segments must be contiguous.  For example, you will not show hours and seconds without showing minutes, even if there are zero minutes.
Single-digit values do not have leading zeros, though a value of zero must be shown as 0.
Values are rounded down.
The first segment displayed is the first non-zero value.


Test Cases

seconds  segments  output
     0      1      0s
   123      1      2m
   123      2      2m 3s
   123      3      2m 3s
 82815      3      23h 0m 15s
307891      2      3d 13h
307891      4      3d 13h 31m 31s
604800      1      1w
604800      6      1w 0d 0h 0m 0s


Winning

The lowest byte-count solution in one week will win "acceptance".

Edits


Clarified which segment is first, as shown in examples.
Added test case 4 as per request.
CJam (snapshot), 41 38 bytes

q~"&lt;&lt;^X^G"{imd\}%W%"wdhms":s.+_{0=}#&gt;&lt;S*


The above uses caret notation, since two of the characters are unprintable.

Thanks to @Sp3000 for golfing off 2 bytes.

Testing

The latest stable release (0.6.5) has a bug that can cause {}# to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (i).

To run this with code with the online interpreter, click this permalink or copy the code from this paste.

Alternatively, you can download and build the latest snapshot by executing the following commands:

hg clone http://hg.code.sf.net/p/cjam/code cjam-code
cd cjam-code/
ant


You can create the CJam file like this:

base64 -d &gt; game-time.cjam &lt;&lt;&lt; cX4iPDwYByJ7aW1kXH0lVyUid2RobXMiOnMuK197MD19Iz48Uyo=


How it works

q~        e# Read an evaluate the input.
"&lt;&lt;^X^G"  e# Push the string corresponding to the array [60 60 24 7
{         e# For each character:
  i       e#   Replace it by its code point.
  md      e#   Push divisor and residue of the division by that code point.
  \       e#   Swap their order.
}%
W%        e# Reverse the resulting array.
"wdhms":s e# Push ["w" "d" "h" "m" "s"].
.+        e# Perform vectorized concatenation.
_         e# Push a copy.
{0=}#     e# Find the index of the first pair with positive integer.
&gt;         e# Remove the preceding pairs.
&lt;         e# Truncate to the number of pairs specified in the input.
S*        e# Join, separating by spaces.