+static int collision(int piece, const int *pos)
+{
+ int i;
+ unsigned char *p = pieces[piece][cur_rot];
+
+ for(i=0; i<4; i++) {
+ int x = PF_XOFFS + pos[1] + BLKX(*p);
+ int y = PF_YOFFS + pos[0] + BLKY(*p);
+ p++;
+
+ if(y < 0) continue;
+
+ if(scr[y * SCR_COLS + x] != TILE_PF) return 1;
+ }
+
+ return 0;
+}
+
+static void stick(int piece, const int *pos)
+{
+ int i, j, nblank;
+ int *pfline;
+ unsigned char *p = pieces[piece][cur_rot];
+
+ for(i=0; i<4; i++) {
+ int x = pos[1] + BLKX(*p);
+ int y = pos[0] + BLKY(*p);
+ p++;
+
+ pfline = scr + (y + PF_YOFFS) * SCR_COLS + PF_XOFFS;
+ pfline[x] = piece + FIRST_PIECE_TILE;
+
+ nblank = 0;
+ for(j=0; j<PF_COLS; j++) {
+ if(pfline[j] == TILE_PF) {
+ nblank++;
+ }
+ }
+
+ if(nblank == 0) {
+ complines[num_complines++] = y;
+ }
+ }
+
+ if(use_bell) {
+ putchar('\a');
+ fflush(stdout);
+ }
+}
+
+static void erase_completed(void)
+{
+ int i, j, srow, drow;
+ int *pfstart = scr + PF_YOFFS * SCR_COLS + PF_XOFFS;
+
+ /* sort completed lines from highest to lowest row number */
+ for(i=0; i<num_complines-1; i++) {
+ for(j=i+1; j<num_complines; j++) {
+ if(complines[j] > complines[i]) {
+ int tmp = complines[j];
+ complines[j] = complines[i];
+ complines[i] = tmp;
+ }
+ }
+ }
+
+ srow = drow = PF_ROWS - 1;
+
+ for(i=0; i<PF_ROWS; i++) {
+ for(j=0; j<num_complines; j++) {
+ if(complines[j] == srow) {
+ srow--;
+ }
+ }
+
+ if(srow < 0) break;
+
+ if(srow != drow) {
+ int *sptr = pfstart + srow * SCR_COLS;
+ int *dptr = pfstart + drow * SCR_COLS;
+ memcpy(dptr, sptr, PF_COLS * sizeof *dptr);
+ }
+
+ srow--;
+ drow--;
+ }
+
+ drawpf();
+ fflush(stdout);
+}
+
+static void draw_piece(int piece, const int *pos, int rot, int mode)
+{
+ int i;
+ int tile = mode == ERASE_PIECE ? TILE_PF : FIRST_PIECE_TILE + piece;
+ unsigned char *p = pieces[piece][rot];
+
+ for(i=0; i<4; i++) {
+ int x = PF_XOFFS + pos[1] + BLKX(*p);
+ int y = PF_YOFFS + pos[0] + BLKY(*p);
+ p++;
+
+ if(y < 0) continue;
+
+ ansi_setcursor(y, x * 2);
+ wrtile(tile);
+ }
+ fflush(stdout);
+}
+
+static void drawbg(void)
+{
+ int i, j;
+ int *sptr = scr;
+
+ for(i=0; i<SCR_ROWS; i++) {
+ ansi_setcursor(i, 0);
+ for(j=0; j<SCR_COLS; j++) {
+ wrtile(*sptr++);
+ }
+ }
+}
+
+static void drawpf(void)
+{
+ int i, j;
+ int *sptr = scr + PF_YOFFS * SCR_COLS + PF_XOFFS;
+
+ for(i=0; i<PF_ROWS; i++) {
+ ansi_setcursor(i, PF_XOFFS * 2);
+ for(j=0; j<PF_COLS; j++) {
+ wrtile(sptr[j]);
+ }
+ sptr += SCR_COLS;
+ }
+}
+
+static void draw_line(int row, int blink)