/* Set cond_ds.direction from ft_attr by cond_id */
UPDATE cond_ds SET direction=(SELECT value::smallint FROM ft_attr WHERE ft_id=cond_id AND key='direction');
DELETE FROM ft_attr WHERE ft_id IN (SELECT cond_id FROM cond WHERE cond_type=20);
/* Create cond copies with cond_id from bound cond_ds line starters */
SELECT *  INTO cond_ds_work FROM cond_ds;
UPDATE cond_ds_work w SET seq_num=0 WHERE seq_num=(SELECT min(seq_num) FROM cond_ds c WHERE c.cond_id=w.cond_id);
ALTER TABLE cond_ds_work ADD COLUMN new_line boolean DEFAULT false;
UPDATE cond_ds_work SET new_line=(cond_ds_id IN
    (SELECT ft_id FROM ft_attr WHERE key='new_line' AND value='1'));
INSERT INTO cond
    SELECT cond_ds_id as cond_id, cond_type, cond_seq_id, access_id
        FROM cond_ds_work w INNER JOIN cond c ON c.cond_id=w.cond_id WHERE new_line AND seq_num > 0;

INSERT INTO cond_isocode
    SELECT cond_ds_id as cond_id, isocode
        FROM cond_ds_work w INNER JOIN cond_isocode c ON c.cond_id=w.cond_id WHERE new_line AND seq_num > 0;

/* Bind cond_ds to cond with id of cond_ds preceding this*/
UPDATE cond_ds c
    SET cond_id=
        (SELECT
            (CASE WHEN w.seq_num=0 THEN w.cond_id ELSE cond_ds_id END)
            FROM cond_ds_work w
            WHERE (w.seq_num=0 OR w.new_line) AND w.cond_id=c.cond_id AND c.seq_num >= w.seq_num
            ORDER BY w.seq_num DESC LIMIT 1);
DROP TABLE cond_ds_work;

/*Make seq_num continous zero based*/
SELECT *  INTO cond_ds_work FROM cond_ds;
UPDATE cond_ds c SET seq_num =
    (SELECT count(*)
        FROM cond_ds_work w
        WHERE w.cond_id = c.cond_id AND w.seq_num < c.seq_num);
DROP TABLE cond_ds_work;
DELETE FROM ft_attr WHERE ft_id IN (SELECT cond_ds_id FROM cond_ds);